xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision c07d6445eb89d9dd3950361b065b7bd110e3a043)
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_ratelimit.h"
40 #include <sys/param.h>
41 #include <sys/arb.h>
42 #include <sys/module.h>
43 #include <sys/kernel.h>
44 #include <sys/libkern.h>
45 #ifdef TCP_HHOOK
46 #include <sys/hhook.h>
47 #endif
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/proc.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/systm.h>
55 #ifdef STATS
56 #include <sys/qmath.h>
57 #include <sys/tree.h>
58 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
59 #endif
60 #include <sys/refcount.h>
61 #include <sys/queue.h>
62 #include <sys/eventhandler.h>
63 #include <sys/smp.h>
64 #include <sys/kthread.h>
65 #include <sys/lock.h>
66 #include <sys/mutex.h>
67 #include <sys/tim_filter.h>
68 #include <sys/time.h>
69 #include <sys/protosw.h>
70 #include <vm/uma.h>
71 #include <sys/kern_prefetch.h>
72 
73 #include <net/route.h>
74 #include <net/route/nhop.h>
75 #include <net/vnet.h>
76 
77 #define TCPSTATES		/* for logging */
78 
79 #include <netinet/in.h>
80 #include <netinet/in_kdtrace.h>
81 #include <netinet/in_pcb.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
84 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
85 #include <netinet/ip_var.h>
86 #include <netinet/ip6.h>
87 #include <netinet6/in6_pcb.h>
88 #include <netinet6/ip6_var.h>
89 #define	TCPOUTFLAGS
90 #include <netinet/tcp.h>
91 #include <netinet/tcp_fsm.h>
92 #include <netinet/tcp_seq.h>
93 #include <netinet/tcp_timer.h>
94 #include <netinet/tcp_var.h>
95 #include <netinet/tcpip.h>
96 #include <netinet/tcp_hpts.h>
97 #include <netinet/cc/cc.h>
98 #include <netinet/tcp_log_buf.h>
99 #include <netinet/tcp_ratelimit.h>
100 #include <netinet/tcp_lro.h>
101 #ifdef TCP_OFFLOAD
102 #include <netinet/tcp_offload.h>
103 #endif
104 #ifdef INET6
105 #include <netinet6/tcp6_var.h>
106 #endif
107 #include <netinet/tcp_fastopen.h>
108 
109 #include <netipsec/ipsec_support.h>
110 #include <net/if.h>
111 #include <net/if_var.h>
112 #include <net/ethernet.h>
113 
114 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
115 #include <netipsec/ipsec.h>
116 #include <netipsec/ipsec6.h>
117 #endif				/* IPSEC */
118 
119 #include <netinet/udp.h>
120 #include <netinet/udp_var.h>
121 #include <machine/in_cksum.h>
122 
123 #ifdef MAC
124 #include <security/mac/mac_framework.h>
125 #endif
126 
127 #include "sack_filter.h"
128 #include "tcp_bbr.h"
129 #include "rack_bbr_common.h"
130 uma_zone_t bbr_zone;
131 uma_zone_t bbr_pcb_zone;
132 
133 struct sysctl_ctx_list bbr_sysctl_ctx;
134 struct sysctl_oid *bbr_sysctl_root;
135 
136 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
137 	(tv) = (value); \
138 	if ((u_long)(tv) < (u_long)(tvmin)) \
139 		(tv) = (tvmin); \
140 	if ((u_long)(tv) > (u_long)(tvmax)) \
141 		(tv) = (tvmax); \
142 } while(0)
143 
144 /*#define BBR_INVARIANT 1*/
145 
146 /*
147  * initial window
148  */
149 static uint32_t bbr_def_init_win = 10;
150 static int32_t bbr_persist_min = 250000;	/* 250ms */
151 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
152 static int32_t bbr_cwnd_may_shrink = 0;
153 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
154 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
155 static int32_t bbr_hardware_pacing_limit = 8000;
156 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
157 static int32_t bbr_no_retran = 0;
158 
159 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
160 static int32_t bbr_max_net_error_cnt = 10;
161 /* Should the following be dynamic too -- loss wise */
162 static int32_t bbr_rtt_gain_thresh = 0;
163 /* Measurement controls */
164 static int32_t bbr_use_google_algo = 1;
165 static int32_t bbr_ts_limiting = 1;
166 static int32_t bbr_ts_can_raise = 0;
167 static int32_t bbr_do_red = 600;
168 static int32_t bbr_red_scale = 20000;
169 static int32_t bbr_red_mul = 1;
170 static int32_t bbr_red_div = 2;
171 static int32_t bbr_red_growth_restrict = 1;
172 static int32_t  bbr_target_is_bbunit = 0;
173 static int32_t bbr_drop_limit = 0;
174 /*
175  * How much gain do we need to see to
176  * stay in startup?
177  */
178 static int32_t bbr_marks_rxt_sack_passed = 0;
179 static int32_t bbr_start_exit = 25;
180 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
181 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
182 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
183 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
184 					 * if we go back ever to where the pacer
185 					 * has priority over timers.
186 					 */
187 static int32_t bbr_policer_call_from_rack_to = 0;
188 static int32_t bbr_policer_detection_enabled = 1;
189 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
190 						 * measurements before we are
191 						 * "good" note that 2 == 1.
192 						 * This is because we use a >
193 						 * comparison. This means if
194 						 * min_measure was 0, it takes
195 						 * num-measures > min(0) and
196 						 * you get 1 measurement and
197 						 * you are good. Set to 1, you
198 						 * have to have two
199 						 * measurements (this is done
200 						 * to prevent it from being ok
201 						 * to have no measurements). */
202 static int32_t bbr_no_pacing_until = 4;
203 
204 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
205 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
206 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
207 
208 static int32_t bbr_target_cwnd_mult_limit = 8;
209 /*
210  * bbr_cwnd_min_val is the number of
211  * segments we hold to in the RTT probe
212  * state typically 4.
213  */
214 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
215 
216 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
217 
218 static int32_t bbr_gain_to_target = 1;
219 static int32_t bbr_gain_gets_extra_too = 1;
220 /*
221  * bbr_high_gain is the 2/ln(2) value we need
222  * to double the sending rate in startup. This
223  * is used for both cwnd and hptsi gain's.
224  */
225 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
226 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
227 static int32_t bbr_use_lower_gain_in_startup = 1;
228 
229 /* thresholds for reduction on drain in sub-states/drain */
230 static int32_t bbr_drain_rtt = BBR_SRTT;
231 static int32_t bbr_drain_floor = 88;
232 static int32_t google_allow_early_out = 1;
233 static int32_t google_consider_lost = 1;
234 static int32_t bbr_drain_drop_mul = 4;
235 static int32_t bbr_drain_drop_div = 5;
236 static int32_t bbr_rand_ot = 50;
237 static int32_t bbr_can_force_probertt = 0;
238 static int32_t bbr_can_adjust_probertt = 1;
239 static int32_t bbr_probertt_sets_rtt = 0;
240 static int32_t bbr_can_use_ts_for_rtt = 1;
241 static int32_t bbr_is_ratio = 0;
242 static int32_t bbr_sub_drain_app_limit = 1;
243 static int32_t bbr_prtt_slam_cwnd = 1;
244 static int32_t bbr_sub_drain_slam_cwnd = 1;
245 static int32_t bbr_slam_cwnd_in_main_drain = 1;
246 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
247 					 * hold */
248 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
249 /*
250  * bbr_drain_gain is the reverse of the high_gain
251  * designed to drain back out the standing queue
252  * that is formed in startup by causing a larger
253  * hptsi gain and thus drainging the packets
254  * in flight.
255  */
256 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
257 static int32_t bbr_rttprobe_gain = 192;
258 
259 /*
260  * The cwnd_gain is the default cwnd gain applied when
261  * calculating a target cwnd. Note that the cwnd is
262  * a secondary factor in the way BBR works (see the
263  * paper and think about it, it will take some time).
264  * Basically the hptsi_gain spreads the packets out
265  * so you never get more than BDP to the peer even
266  * if the cwnd is high. In our implemenation that
267  * means in non-recovery/retransmission scenarios
268  * cwnd will never be reached by the flight-size.
269  */
270 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
271 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
272 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
273 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
274 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
275 static int32_t bbr_ignore_data_after_close = 1;
276 static int16_t bbr_hptsi_gain[] = {
277 	(BBR_UNIT *5 / 4),
278 	(BBR_UNIT * 3 / 4),
279 	BBR_UNIT,
280 	BBR_UNIT,
281 	BBR_UNIT,
282 	BBR_UNIT,
283 	BBR_UNIT,
284 	BBR_UNIT
285 };
286 int32_t bbr_use_rack_resend_cheat = 1;
287 int32_t bbr_sends_full_iwnd = 1;
288 
289 #define BBR_HPTSI_GAIN_MAX 8
290 /*
291  * The BBR module incorporates a number of
292  * TCP ideas that have been put out into the IETF
293  * over the last few years:
294  * - Yuchung Cheng's RACK TCP (for which its named) that
295  *    will stop us using the number of dup acks and instead
296  *    use time as the gage of when we retransmit.
297  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
298  *    of Dukkipati et.al.
299  * - Van Jacobson's et.al BBR.
300  *
301  * RACK depends on SACK, so if an endpoint arrives that
302  * cannot do SACK the state machine below will shuttle the
303  * connection back to using the "default" TCP stack that is
304  * in FreeBSD.
305  *
306  * To implement BBR and RACK the original TCP stack was first decomposed
307  * into a functional state machine with individual states
308  * for each of the possible TCP connection states. The do_segment
309  * functions role in life is to mandate the connection supports SACK
310  * initially and then assure that the RACK state matches the conenction
311  * state before calling the states do_segment function. Data processing
312  * of inbound segments also now happens in the hpts_do_segment in general
313  * with only one exception. This is so we can keep the connection on
314  * a single CPU.
315  *
316  * Each state is simplified due to the fact that the original do_segment
317  * has been decomposed and we *know* what state we are in (no
318  * switches on the state) and all tests for SACK are gone. This
319  * greatly simplifies what each state does.
320  *
321  * TCP output is also over-written with a new version since it
322  * must maintain the new rack scoreboard and has had hptsi
323  * integrated as a requirment. Still todo is to eliminate the
324  * use of the callout_() system and use the hpts for all
325  * timers as well.
326  */
327 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
328 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
329 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
330 						 * free list */
331 static int32_t bbr_tlp_thresh = 1;
332 static int32_t bbr_reorder_thresh = 2;
333 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
334 						 * 60,000,000 - 60 seconds */
335 static int32_t bbr_pkt_delay = 1000;
336 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
337 static int32_t bbr_incr_timers = 1;
338 
339 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
340 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
341 static int32_t bbr_exit_startup_at_loss = 1;
342 
343 /*
344  * bbr_lt_bw_ratio is 1/8th
345  * bbr_lt_bw_diff is  < 4 Kbit/sec
346  */
347 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
348 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
349 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
350 						 * the lt_bw for */
351 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
352 						 * lt_bw */
353 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
354 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
355 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
356 
357 static int32_t bbr_verbose_logging = 0;
358 /*
359  * Currently regular tcp has a rto_min of 30ms
360  * the backoff goes 12 times so that ends up
361  * being a total of 122.850 seconds before a
362  * connection is killed.
363  */
364 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
365 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
366 
367 /****************************************************/
368 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
369 /****************************************************/
370 /* What amount is our formula using to get TSO size */
371 static int32_t bbr_hptsi_per_second = 1000;
372 
373 /*
374  * For hptsi under bbr_cross_over connections what is delay
375  * target 7ms (in usec) combined with a seg_max of 2
376  * gets us close to identical google behavior in
377  * TSO size selection (possibly more 1MSS sends).
378  */
379 static int32_t bbr_hptsi_segments_delay_tar = 7000;
380 
381 /* Does pacing delay include overhead's in its time calculations? */
382 static int32_t bbr_include_enet_oh = 0;
383 static int32_t bbr_include_ip_oh = 1;
384 static int32_t bbr_include_tcp_oh = 1;
385 static int32_t bbr_google_discount = 10;
386 
387 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
388 static int32_t bbr_state_is_pkt_epoch = 0;
389 static int32_t bbr_state_drain_2_tar = 1;
390 /* What is the max the 0 - bbr_cross_over MBPS TSO target
391  * can reach using our delay target. Note that this
392  * value becomes the floor for the cross over
393  * algorithm.
394  */
395 static int32_t bbr_hptsi_segments_max = 2;
396 static int32_t bbr_hptsi_segments_floor = 1;
397 static int32_t bbr_hptsi_utter_max = 0;
398 
399 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
400 static int32_t bbr_hptsi_bytes_min = 1460;
401 static int32_t bbr_all_get_min = 0;
402 
403 /* Cross over point from algo-a to algo-b */
404 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
405 
406 /* Do we deal with our restart state? */
407 static int32_t bbr_uses_idle_restart = 0;
408 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
409 
410 /* Do we allow hardware pacing? */
411 static int32_t bbr_allow_hdwr_pacing = 0;
412 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
413 static int32_t bbr_hdwr_pace_floor = 1;
414 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
415 
416 /****************************************************/
417 static int32_t bbr_resends_use_tso = 0;
418 static int32_t bbr_tlp_max_resend = 2;
419 static int32_t bbr_sack_block_limit = 128;
420 
421 #define  BBR_MAX_STAT 19
422 counter_u64_t bbr_state_time[BBR_MAX_STAT];
423 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
424 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
425 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
426 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
427 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
428 counter_u64_t bbr_flows_whdwr_pacing;
429 counter_u64_t bbr_flows_nohdwr_pacing;
430 
431 counter_u64_t bbr_nohdwr_pacing_enobuf;
432 counter_u64_t bbr_hdwr_pacing_enobuf;
433 
434 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
435 
436 /*
437  * Static defintions we need for forward declarations.
438  */
439 static uint32_t
440 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
441 		      uint32_t useconds_time, uint64_t bw);
442 static uint32_t
443 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
444 static void
445 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
446 static void
447 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
448 static void
449 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
450 		    int dolog);
451 static uint32_t
452 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
453 static void
454 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
455 		 int32_t pkt_epoch, uint32_t losses);
456 static uint32_t
457 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts,
458 		     struct bbr_sendmap *rsm);
459 static uint32_t
460 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
461 static uint32_t
462 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
463 		    struct bbr_sendmap *rsm, uint32_t srtt, uint32_t cts);
464 static void
465 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
466 		 int32_t line);
467 static void
468 bbr_set_state_target(struct tcp_bbr *bbr, int line);
469 static void
470 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
471 static void
472 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick,
473 		       int event, int line);
474 static void
475 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
476 static void
477 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
478 static void
479 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
480 		    uint32_t rtt, uint32_t line, uint8_t is_start,
481 		    uint16_t set);
482 static struct bbr_sendmap *
483 bbr_find_lowest_rsm(struct tcp_bbr *bbr);
484 static __inline uint32_t
485 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
486 static void
487 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot,
488 		 uint8_t which);
489 static void
490 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts,
491 		  uint32_t time_since_sent, uint32_t srtt,
492 		  uint32_t thresh, uint32_t to);
493 static void
494 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
495 static void
496 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
497 		    uint32_t del_by, uint32_t cts, uint32_t sloton,
498 		    uint32_t prev_delay);
499 static void
500 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
501 		  int32_t line);
502 static void
503 bbr_stop_all_timers(struct tcpcb *tp);
504 static void
505 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
506 static void
507 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
508 static void
509 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
510 static void
511 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
512 			  uint32_t cts, uint32_t usecs, uint64_t bw,
513 			  uint32_t override, int mod);
514 static int
515 bbr_ctloutput(struct inpcb *inp, struct sockopt *sopt);
516 
517 static inline uint8_t
518 bbr_state_val(struct tcp_bbr *bbr)
519 {
520 	return(bbr->rc_bbr_substate);
521 }
522 
523 static inline uint32_t
524 get_min_cwnd(struct tcp_bbr *bbr)
525 {
526 	int mss;
527 
528 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
529 		  bbr->r_ctl.rc_pace_max_segs);
530 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
531 		return (bbr_cwnd_min_val_hs * mss);
532 	else
533 		return (bbr_cwnd_min_val * mss);
534 }
535 
536 static uint32_t
537 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
538 {
539 	uint64_t srtt, var;
540 	uint64_t ret_val;
541 
542 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
543 	if (tp->t_srtt == 0) {
544 		srtt = (uint64_t)BBR_INITIAL_RTO;
545 		var = 0;
546 	} else {
547 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
548 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
549 	}
550 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
551 	    bbr_persist_min, bbr_persist_max);
552 	return ((uint32_t)ret_val);
553 }
554 
555 static uint32_t
556 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
557 {
558 	/*
559 	 * Start the FR timer, we do this based on getting the first one in
560 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
561 	 * events we need to stop the running timer (if its running) before
562 	 * starting the new one.
563 	 */
564 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
565 	int32_t idx;
566 	int32_t is_tlp_timer = 0;
567 	struct bbr_sendmap *rsm;
568 
569 	if (bbr->rc_all_timers_stopped) {
570 		/* All timers have been stopped none are to run */
571 		return (0);
572 	}
573 	if (bbr->rc_in_persist) {
574 		/* We can't start any timer in persists */
575 		return (bbr_get_persists_timer_val(tp, bbr));
576 	}
577 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
578 	if ((rsm == NULL) ||
579 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
580 	    (tp->t_state < TCPS_ESTABLISHED)) {
581 		/* Nothing on the send map */
582 activate_rxt:
583 		if (SEQ_LT(tp->snd_una, tp->snd_max) ||
584 		    sbavail(&tptosocket(tp)->so_snd)) {
585 			uint64_t tov;
586 
587 			time_since_sent = 0;
588 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
589 			if (rsm) {
590 				idx = rsm->r_rtr_cnt - 1;
591 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
592 					tstmp_touse = rsm->r_tim_lastsent[idx];
593 				else
594 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
595 				if (TSTMP_GT(tstmp_touse, cts))
596 				    time_since_sent = cts - tstmp_touse;
597 			}
598 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
599 			if (tp->t_srtt == 0)
600 				tov = BBR_INITIAL_RTO;
601 			else
602 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
603 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
604 			if (tp->t_rxtshift)
605 				tov *= tcp_backoff[tp->t_rxtshift];
606 			if (tov > time_since_sent)
607 				tov -= time_since_sent;
608 			else
609 				tov = bbr->r_ctl.rc_min_to;
610 			TCPT_RANGESET_NOSLOP(to, tov,
611 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
612 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
613 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
614 			return (to);
615 		}
616 		return (0);
617 	}
618 	if (rsm->r_flags & BBR_ACKED) {
619 		rsm = bbr_find_lowest_rsm(bbr);
620 		if (rsm == NULL) {
621 			/* No lowest? */
622 			goto activate_rxt;
623 		}
624 	}
625 	/* Convert from ms to usecs */
626 	if (rsm->r_flags & BBR_SACK_PASSED) {
627 		if ((tp->t_flags & TF_SENTFIN) &&
628 		    ((tp->snd_max - tp->snd_una) == 1) &&
629 		    (rsm->r_flags & BBR_HAS_FIN)) {
630 			/*
631 			 * We don't start a bbr rack timer if all we have is
632 			 * a FIN outstanding.
633 			 */
634 			goto activate_rxt;
635 		}
636 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
637 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
638 		idx = rsm->r_rtr_cnt - 1;
639 		exp = rsm->r_tim_lastsent[idx] + thresh;
640 		if (SEQ_GEQ(exp, cts)) {
641 			to = exp - cts;
642 			if (to < bbr->r_ctl.rc_min_to) {
643 				to = bbr->r_ctl.rc_min_to;
644 			}
645 		} else {
646 			to = bbr->r_ctl.rc_min_to;
647 		}
648 	} else {
649 		/* Ok we need to do a TLP not RACK */
650 		if (bbr->rc_tlp_in_progress != 0) {
651 			/*
652 			 * The previous send was a TLP.
653 			 */
654 			goto activate_rxt;
655 		}
656 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
657 		if (rsm == NULL) {
658 			/* We found no rsm to TLP with. */
659 			goto activate_rxt;
660 		}
661 		if (rsm->r_flags & BBR_HAS_FIN) {
662 			/* If its a FIN we don't do TLP */
663 			rsm = NULL;
664 			goto activate_rxt;
665 		}
666 		time_since_sent = 0;
667 		idx = rsm->r_rtr_cnt - 1;
668 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
669 			tstmp_touse = rsm->r_tim_lastsent[idx];
670 		else
671 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
672 		if (TSTMP_GT(tstmp_touse, cts))
673 		    time_since_sent = cts - tstmp_touse;
674 		is_tlp_timer = 1;
675 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
676 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
677 		if (thresh > time_since_sent)
678 			to = thresh - time_since_sent;
679 		else
680 			to = bbr->r_ctl.rc_min_to;
681 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
682 			/*
683 			 * If the TLP time works out to larger than the max
684 			 * RTO lets not do TLP.. just RTO.
685 			 */
686 			goto activate_rxt;
687 		}
688 		if ((bbr->rc_tlp_rtx_out == 1) &&
689 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
690 			/*
691 			 * Second retransmit of the same TLP
692 			 * lets not.
693 			 */
694 			bbr->rc_tlp_rtx_out = 0;
695 			goto activate_rxt;
696 		}
697 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
698 			/*
699 			 * The tail is no longer the last one I did a probe
700 			 * on
701 			 */
702 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
703 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
704 		}
705 	}
706 	if (is_tlp_timer == 0) {
707 		BBR_STAT_INC(bbr_to_arm_rack);
708 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
709 	} else {
710 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
711 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
712 			/*
713 			 * We have exceeded how many times we can retran the
714 			 * current TLP timer, switch to the RTO timer.
715 			 */
716 			goto activate_rxt;
717 		} else {
718 			BBR_STAT_INC(bbr_to_arm_tlp);
719 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
720 		}
721 	}
722 	return (to);
723 }
724 
725 static inline int32_t
726 bbr_minseg(struct tcp_bbr *bbr)
727 {
728 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
729 }
730 
731 static void
732 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
733 {
734 	struct inpcb *inp = tptoinpcb(tp);
735 	struct hpts_diag diag;
736 	uint32_t delayed_ack = 0;
737 	uint32_t left = 0;
738 	uint32_t hpts_timeout;
739 	uint8_t stopped;
740 	int32_t delay_calc = 0;
741 	uint32_t prev_delay = 0;
742 
743 	if (tcp_in_hpts(inp)) {
744 		/* A previous call is already set up */
745 		return;
746 	}
747 	if ((tp->t_state == TCPS_CLOSED) ||
748 	    (tp->t_state == TCPS_LISTEN)) {
749 		return;
750 	}
751 	stopped = bbr->rc_tmr_stopped;
752 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
753 		left = bbr->r_ctl.rc_timer_exp - cts;
754 	}
755 	bbr->r_ctl.rc_hpts_flags = 0;
756 	bbr->r_ctl.rc_timer_exp = 0;
757 	prev_delay = bbr->r_ctl.rc_last_delay_val;
758 	if (bbr->r_ctl.rc_last_delay_val &&
759 	    (slot == 0)) {
760 		/*
761 		 * If a previous pacer delay was in place we
762 		 * are not coming from the output side (where
763 		 * we calculate a delay, more likely a timer).
764 		 */
765 		slot = bbr->r_ctl.rc_last_delay_val;
766 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
767 			/* Compensate for time passed  */
768 			delay_calc = cts - bbr->rc_pacer_started;
769 			if (delay_calc <= slot)
770 				slot -= delay_calc;
771 		}
772 	}
773 	/* Do we have early to make up for by pushing out the pacing time? */
774 	if (bbr->r_agg_early_set) {
775 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
776 		slot += bbr->r_ctl.rc_agg_early;
777 		bbr->r_ctl.rc_agg_early = 0;
778 		bbr->r_agg_early_set = 0;
779 	}
780 	/* Are we running a total debt that needs to be compensated for? */
781 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
782 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
783 			/* We nuke the delay */
784 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
785 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
786 		} else {
787 			/* We nuke some of the delay, put in a minimal 100usecs  */
788 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
789 			bbr->r_ctl.rc_last_delay_val = slot = 100;
790 		}
791 	}
792 	bbr->r_ctl.rc_last_delay_val = slot;
793 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
794 	if (tp->t_flags & TF_DELACK) {
795 		if (bbr->rc_in_persist == 0) {
796 			delayed_ack = bbr_delack_time;
797 		} else {
798 			/*
799 			 * We are in persists and have
800 			 * gotten a new data element.
801 			 */
802 			if (hpts_timeout > bbr_delack_time) {
803 				/*
804 				 * Lets make the persists timer (which acks)
805 				 * be the smaller of hpts_timeout and bbr_delack_time.
806 				 */
807 				hpts_timeout = bbr_delack_time;
808 			}
809 		}
810 	}
811 	if (delayed_ack &&
812 	    ((hpts_timeout == 0) ||
813 	     (delayed_ack < hpts_timeout))) {
814 		/* We need a Delayed ack timer */
815 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
816 		hpts_timeout = delayed_ack;
817 	}
818 	if (slot) {
819 		/* Mark that we have a pacing timer up */
820 		BBR_STAT_INC(bbr_paced_segments);
821 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
822 	}
823 	/*
824 	 * If no timers are going to run and we will fall off thfe hptsi
825 	 * wheel, we resort to a keep-alive timer if its configured.
826 	 */
827 	if ((hpts_timeout == 0) &&
828 	    (slot == 0)) {
829 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
830 		    (tp->t_state <= TCPS_CLOSING)) {
831 			/*
832 			 * Ok we have no timer (persists, rack, tlp, rxt  or
833 			 * del-ack), we don't have segments being paced. So
834 			 * all that is left is the keepalive timer.
835 			 */
836 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
837 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
838 			} else {
839 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
840 			}
841 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
842 		}
843 	}
844 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
845 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
846 		/*
847 		 * RACK, TLP, persists and RXT timers all are restartable
848 		 * based on actions input .. i.e we received a packet (ack
849 		 * or sack) and that changes things (rw, or snd_una etc).
850 		 * Thus we can restart them with a new value. For
851 		 * keep-alive, delayed_ack we keep track of what was left
852 		 * and restart the timer with a smaller value.
853 		 */
854 		if (left < hpts_timeout)
855 			hpts_timeout = left;
856 	}
857 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
858 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
859 		/*
860 		 * If configured to do so, and the timer is either
861 		 * the TLP or RXT timer, we need to increase the timeout
862 		 * by the pacing time. Consider the bottleneck at my
863 		 * machine as an example, we are sending something
864 		 * to start a TLP on. The last packet won't be emitted
865 		 * fully until the pacing time (the bottleneck will hold
866 		 * the data in place). Once the packet is emitted that
867 		 * is when we want to start waiting for the TLP. This
868 		 * is most evident with hardware pacing (where the nic
869 		 * is holding the packet(s) before emitting). But it
870 		 * can also show up in the network so we do it for all
871 		 * cases. Technically we would take off one packet from
872 		 * this extra delay but this is easier and being more
873 		 * conservative is probably better.
874 		 */
875 		hpts_timeout += slot;
876 	}
877 	if (hpts_timeout) {
878 		/*
879 		 * Hack alert for now we can't time-out over 2147 seconds (a
880 		 * bit more than 35min)
881 		 */
882 		if (hpts_timeout > 0x7ffffffe)
883 			hpts_timeout = 0x7ffffffe;
884 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
885 	} else
886 		bbr->r_ctl.rc_timer_exp = 0;
887 	if ((slot) &&
888 	    (bbr->rc_use_google ||
889 	     bbr->output_error_seen ||
890 	     (slot <= hpts_timeout))  ) {
891 		/*
892 		 * Tell LRO that it can queue packets while
893 		 * we pace.
894 		 */
895 		bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
896 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
897 		    (bbr->rc_cwnd_limited == 0)) {
898 			/*
899 			 * If we are not cwnd limited and we
900 			 * are running a rack timer we put on
901 			 * the do not disturbe even for sack.
902 			 */
903 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
904 		} else
905 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
906 		bbr->rc_pacer_started = cts;
907 
908 		(void)tcp_hpts_insert_diag(inp, HPTS_USEC_TO_SLOTS(slot),
909 					   __LINE__, &diag);
910 		bbr->rc_timer_first = 0;
911 		bbr->bbr_timer_src = frm;
912 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
913 		bbr_log_hpts_diag(bbr, cts, &diag);
914 	} else if (hpts_timeout) {
915 		(void)tcp_hpts_insert_diag(inp, HPTS_USEC_TO_SLOTS(hpts_timeout),
916 					   __LINE__, &diag);
917 		/*
918 		 * We add the flag here as well if the slot is set,
919 		 * since hpts will call in to clear the queue first before
920 		 * calling the output routine (which does our timers).
921 		 * We don't want to set the flag if its just a timer
922 		 * else the arrival of data might (that causes us
923 		 * to send more) might get delayed. Imagine being
924 		 * on a keep-alive timer and a request comes in for
925 		 * more data.
926 		 */
927 		if (slot)
928 			bbr->rc_pacer_started = cts;
929 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
930 		    (bbr->rc_cwnd_limited == 0)) {
931 			/*
932 			 * For a rack timer, don't wake us even
933 			 * if a sack arrives as long as we are
934 			 * not cwnd limited.
935 			 */
936 			bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
937 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
938 		} else {
939 			/* All other timers wake us up */
940 			bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
941 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
942 		}
943 		bbr->bbr_timer_src = frm;
944 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
945 		bbr_log_hpts_diag(bbr, cts, &diag);
946 		bbr->rc_timer_first = 1;
947 	}
948 	bbr->rc_tmr_stopped = 0;
949 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
950 }
951 
952 static void
953 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
954 {
955 	/*
956 	 * We received an ack, and then did not call send or were bounced
957 	 * out due to the hpts was running. Now a timer is up as well, is it
958 	 * the right timer?
959 	 */
960 	struct inpcb *inp;
961 	struct bbr_sendmap *rsm;
962 	uint32_t hpts_timeout;
963 	int tmr_up;
964 
965 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
966 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
967 		return;
968 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
969 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
970 	    (tmr_up == PACE_TMR_RXT)) {
971 		/* Should be an RXT */
972 		return;
973 	}
974 	inp = bbr->rc_inp;
975 	if (rsm == NULL) {
976 		/* Nothing outstanding? */
977 		if (tp->t_flags & TF_DELACK) {
978 			if (tmr_up == PACE_TMR_DELACK)
979 				/*
980 				 * We are supposed to have delayed ack up
981 				 * and we do
982 				 */
983 				return;
984 		} else if (sbavail(&inp->inp_socket->so_snd) &&
985 		    (tmr_up == PACE_TMR_RXT)) {
986 			/*
987 			 * if we hit enobufs then we would expect the
988 			 * possibility of nothing outstanding and the RXT up
989 			 * (and the hptsi timer).
990 			 */
991 			return;
992 		} else if (((V_tcp_always_keepalive ||
993 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
994 			    (tp->t_state <= TCPS_CLOSING)) &&
995 			    (tmr_up == PACE_TMR_KEEP) &&
996 		    (tp->snd_max == tp->snd_una)) {
997 			/* We should have keep alive up and we do */
998 			return;
999 		}
1000 	}
1001 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1002 		if ((tp->t_flags & TF_SENTFIN) &&
1003 		    ((tp->snd_max - tp->snd_una) == 1) &&
1004 		    (rsm->r_flags & BBR_HAS_FIN)) {
1005 			/* needs to be a RXT */
1006 			if (tmr_up == PACE_TMR_RXT)
1007 				return;
1008 			else
1009 				goto wrong_timer;
1010 		} else if (tmr_up == PACE_TMR_RACK)
1011 			return;
1012 		else
1013 			goto wrong_timer;
1014 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1015 		/* Rack timer has priority if we have data out */
1016 		return;
1017 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1018 		    ((tmr_up == PACE_TMR_TLP) ||
1019 	    (tmr_up == PACE_TMR_RXT))) {
1020 		/*
1021 		 * Either a TLP or RXT is fine if no sack-passed is in place
1022 		 * and data is outstanding.
1023 		 */
1024 		return;
1025 	} else if (tmr_up == PACE_TMR_DELACK) {
1026 		/*
1027 		 * If the delayed ack was going to go off before the
1028 		 * rtx/tlp/rack timer were going to expire, then that would
1029 		 * be the timer in control. Note we don't check the time
1030 		 * here trusting the code is correct.
1031 		 */
1032 		return;
1033 	}
1034 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1035 	    ((tmr_up == PACE_TMR_RXT) ||
1036 	     (tmr_up == PACE_TMR_TLP) ||
1037 	     (tmr_up == PACE_TMR_RACK))) {
1038 		/*
1039 		 * We have outstanding data and
1040 		 * we *do* have a RACK, TLP or RXT
1041 		 * timer running. We won't restart
1042 		 * anything here since thats probably ok we
1043 		 * will get called with some timer here shortly.
1044 		 */
1045 		return;
1046 	}
1047 	/*
1048 	 * Ok the timer originally started is not what we want now. We will
1049 	 * force the hpts to be stopped if any, and restart with the slot
1050 	 * set to what was in the saved slot.
1051 	 */
1052 wrong_timer:
1053 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1054 		if (tcp_in_hpts(inp))
1055 			tcp_hpts_remove(inp);
1056 		bbr_timer_cancel(bbr, __LINE__, cts);
1057 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1058 		    0);
1059 	} else {
1060 		/*
1061 		 * Output is hptsi so we just need to switch the type of
1062 		 * timer. We don't bother with keep-alive, since when we
1063 		 * jump through the output, it will start the keep-alive if
1064 		 * nothing is sent.
1065 		 *
1066 		 * We only need a delayed-ack added and or the hpts_timeout.
1067 		 */
1068 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1069 		if (tp->t_flags & TF_DELACK) {
1070 			if (hpts_timeout == 0) {
1071 				hpts_timeout = bbr_delack_time;
1072 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1073 			}
1074 			else if (hpts_timeout > bbr_delack_time) {
1075 				hpts_timeout = bbr_delack_time;
1076 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1077 			}
1078 		}
1079 		if (hpts_timeout) {
1080 			if (hpts_timeout > 0x7ffffffe)
1081 				hpts_timeout = 0x7ffffffe;
1082 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1083 		}
1084 	}
1085 }
1086 
1087 int32_t bbr_clear_lost = 0;
1088 
1089 /*
1090  * Considers the two time values now (cts) and earlier.
1091  * If cts is smaller than earlier, we could have
1092  * had a sequence wrap (our counter wraps every
1093  * 70 min or so) or it could be just clock skew
1094  * getting us two different time values. Clock skew
1095  * will show up within 10ms or so. So in such
1096  * a case (where cts is behind earlier time by
1097  * less than 10ms) we return 0. Otherwise we
1098  * return the true difference between them.
1099  */
1100 static inline uint32_t
1101 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1102 	/*
1103 	 * Given two timestamps, the current time stamp cts, and some other
1104 	 * time-stamp taken in theory earlier return the difference. The
1105 	 * trick is here sometimes locking will get the other timestamp
1106 	 * after the cts. If this occurs we need to return 0.
1107 	 */
1108 	if (TSTMP_GEQ(cts, earlier_time))
1109 		return (cts - earlier_time);
1110 	/*
1111 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1112 	 * If its more than 10ms difference then we had a time wrap. Else
1113 	 * its just the normal locking foo. I wonder if we should not go to
1114 	 * 64bit TS and get rid of this issue.
1115 	 */
1116 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1117 		return (0);
1118 	/*
1119 	 * Ok the time must have wrapped. So we need to answer a large
1120 	 * amount of time, which the normal subtraction should do.
1121 	 */
1122 	return (cts - earlier_time);
1123 }
1124 
1125 static int
1126 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1127 {
1128 	uint32_t stat;
1129 	int32_t error;
1130 
1131 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1132 	if (error || req->newptr == NULL)
1133 		return error;
1134 
1135 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1136 	if (error)
1137 		return (error);
1138 	if (stat == 1) {
1139 #ifdef BBR_INVARIANTS
1140 		printf("Clearing BBR lost counters\n");
1141 #endif
1142 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1143 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1144 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1145 	} else if (stat == 2) {
1146 #ifdef BBR_INVARIANTS
1147 		printf("Clearing BBR option counters\n");
1148 #endif
1149 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1150 	} else if (stat == 3) {
1151 #ifdef BBR_INVARIANTS
1152 		printf("Clearing BBR stats counters\n");
1153 #endif
1154 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1155 	} else if (stat == 4) {
1156 #ifdef BBR_INVARIANTS
1157 		printf("Clearing BBR out-size counters\n");
1158 #endif
1159 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1160 	}
1161 	bbr_clear_lost = 0;
1162 	return (0);
1163 }
1164 
1165 static void
1166 bbr_init_sysctls(void)
1167 {
1168 	struct sysctl_oid *bbr_probertt;
1169 	struct sysctl_oid *bbr_hptsi;
1170 	struct sysctl_oid *bbr_measure;
1171 	struct sysctl_oid *bbr_cwnd;
1172 	struct sysctl_oid *bbr_timeout;
1173 	struct sysctl_oid *bbr_states;
1174 	struct sysctl_oid *bbr_startup;
1175 	struct sysctl_oid *bbr_policer;
1176 
1177 	/* Probe rtt controls */
1178 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1179 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1180 	    OID_AUTO,
1181 	    "probertt",
1182 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1183 	    "");
1184 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1185 	    SYSCTL_CHILDREN(bbr_probertt),
1186 	    OID_AUTO, "gain", CTLFLAG_RW,
1187 	    &bbr_rttprobe_gain, 192,
1188 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1189 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1190 	    SYSCTL_CHILDREN(bbr_probertt),
1191 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1192 	    &bbr_rtt_probe_cwndtarg, 4,
1193 	    "How many mss's are outstanding during probe-rtt");
1194 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1195 	    SYSCTL_CHILDREN(bbr_probertt),
1196 	    OID_AUTO, "int", CTLFLAG_RW,
1197 	    &bbr_rtt_probe_limit, 4000000,
1198 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1199 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1200 	    SYSCTL_CHILDREN(bbr_probertt),
1201 	    OID_AUTO, "mintime", CTLFLAG_RW,
1202 	    &bbr_rtt_probe_time, 200000,
1203 	    "How many microseconds in probe-rtt");
1204 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1205 	    SYSCTL_CHILDREN(bbr_probertt),
1206 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1207 	    &bbr_filter_len_sec, 6,
1208 	    "How long in seconds does the rttProp filter run?");
1209 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1210 	    SYSCTL_CHILDREN(bbr_probertt),
1211 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1212 	    &bbr_drain_rtt, BBR_SRTT,
1213 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1214 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1215 	    SYSCTL_CHILDREN(bbr_probertt),
1216 	    OID_AUTO, "can_force", CTLFLAG_RW,
1217 	    &bbr_can_force_probertt, 0,
1218 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1219 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1220 	    SYSCTL_CHILDREN(bbr_probertt),
1221 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1222 	    &bbr_probertt_sets_rtt, 0,
1223 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1224 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1225 	    SYSCTL_CHILDREN(bbr_probertt),
1226 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1227 	    &bbr_can_adjust_probertt, 1,
1228 	    "Can we dynamically adjust the probe-rtt limits and times?");
1229 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1230 	    SYSCTL_CHILDREN(bbr_probertt),
1231 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1232 	    &bbr_is_ratio, 0,
1233 	    "is the limit to filter a ratio?");
1234 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1235 	    SYSCTL_CHILDREN(bbr_probertt),
1236 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1237 	    &bbr_prtt_slam_cwnd, 0,
1238 	    "Should we set/recover cwnd?");
1239 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1240 	    SYSCTL_CHILDREN(bbr_probertt),
1241 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1242 	    &bbr_can_use_ts_for_rtt, 1,
1243 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1244 
1245 	/* Pacing controls */
1246 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1247 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1248 	    OID_AUTO,
1249 	    "pacing",
1250 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1251 	    "");
1252 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1253 	    SYSCTL_CHILDREN(bbr_hptsi),
1254 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1255 	    &bbr_allow_hdwr_pacing, 1,
1256 	    "Do we allow hardware pacing?");
1257 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1258 	    SYSCTL_CHILDREN(bbr_hptsi),
1259 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1260 	    &bbr_hardware_pacing_limit, 4000,
1261 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1262 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1263 	    SYSCTL_CHILDREN(bbr_hptsi),
1264 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1265 	    &bbr_hdwr_pace_adjust, 2,
1266 	    "Multiplier to calculated tso size?");
1267 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1268 	    SYSCTL_CHILDREN(bbr_hptsi),
1269 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1270 	    &bbr_hdwr_pace_floor, 1,
1271 	    "Do we invoke the hardware pacing floor?");
1272 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1273 	    SYSCTL_CHILDREN(bbr_hptsi),
1274 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1275 	    &bbr_hdwr_pacing_delay_cnt, 10,
1276 	    "How many packets must be sent after hdwr pacing is enabled");
1277 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1278 	    SYSCTL_CHILDREN(bbr_hptsi),
1279 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1280 	    &bbr_cross_over, 3000000,
1281 	    "What is the point where we cross over to linux like TSO size set");
1282 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1283 	    SYSCTL_CHILDREN(bbr_hptsi),
1284 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1285 	    &bbr_hptsi_segments_delay_tar, 7000,
1286 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1287 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1288 	    SYSCTL_CHILDREN(bbr_hptsi),
1289 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1290 	    &bbr_include_enet_oh, 0,
1291 	    "Do we include the ethernet overhead in calculating pacing delay?");
1292 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1293 	    SYSCTL_CHILDREN(bbr_hptsi),
1294 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1295 	    &bbr_include_ip_oh, 1,
1296 	    "Do we include the IP overhead in calculating pacing delay?");
1297 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1298 	    SYSCTL_CHILDREN(bbr_hptsi),
1299 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1300 	    &bbr_include_tcp_oh, 0,
1301 	    "Do we include the TCP overhead in calculating pacing delay?");
1302 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1303 	    SYSCTL_CHILDREN(bbr_hptsi),
1304 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1305 	    &bbr_google_discount, 10,
1306 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1307 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1308 	    SYSCTL_CHILDREN(bbr_hptsi),
1309 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1310 	    &bbr_all_get_min, 0,
1311 	    "If you are less than a MSS do you just get the min?");
1312 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1313 	    SYSCTL_CHILDREN(bbr_hptsi),
1314 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1315 	    &bbr_hptsi_bytes_min, 1460,
1316 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1317 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1318 	    SYSCTL_CHILDREN(bbr_hptsi),
1319 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1320 	    &bbr_hptsi_segments_max, 6,
1321 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1322 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1323 	    SYSCTL_CHILDREN(bbr_hptsi),
1324 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1325 	    &bbr_hptsi_segments_floor, 1,
1326 	    "Minimum TSO size we will fall too in segments");
1327 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1328 	    SYSCTL_CHILDREN(bbr_hptsi),
1329 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1330 	    &bbr_hptsi_utter_max, 0,
1331 	    "The absolute maximum that any pacing (outside of hardware) can be");
1332 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1333 	    SYSCTL_CHILDREN(bbr_hptsi),
1334 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1335 	    &bbr_hptsi_per_second, 100,
1336 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1337 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1338 	    SYSCTL_CHILDREN(bbr_hptsi),
1339 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1340 	    &bbr_hptsi_max_mul, 1,
1341 	    "The multiplier for pace len max");
1342 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1343 	    SYSCTL_CHILDREN(bbr_hptsi),
1344 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1345 	    &bbr_hptsi_max_div, 2,
1346 	    "The divisor for pace len max");
1347 	/* Measurement controls */
1348 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1349 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1350 	    OID_AUTO,
1351 	    "measure",
1352 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1353 	    "Measurement controls");
1354 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1355 	    SYSCTL_CHILDREN(bbr_measure),
1356 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1357 	    &bbr_initial_bw_bps, 62500,
1358 	    "Minimum initial b/w in bytes per second");
1359 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1360 	    SYSCTL_CHILDREN(bbr_measure),
1361 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1362 	    &bbr_sack_not_required, 0,
1363 	    "Do we allow bbr to run on connections not supporting SACK?");
1364 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1365 	    SYSCTL_CHILDREN(bbr_measure),
1366 	    OID_AUTO, "use_google", CTLFLAG_RW,
1367 	    &bbr_use_google_algo, 0,
1368 	    "Use has close to google V1.0 has possible?");
1369 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1370 	    SYSCTL_CHILDREN(bbr_measure),
1371 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1372 	    &bbr_ts_limiting, 1,
1373 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1374 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1375 	    SYSCTL_CHILDREN(bbr_measure),
1376 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1377 	    &bbr_ts_can_raise, 0,
1378 	    "Can we raise the b/w via timestamp b/w calculation?");
1379 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1380 	    SYSCTL_CHILDREN(bbr_measure),
1381 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1382 	    &bbr_min_usec_delta, 20000,
1383 	    "How long in usec between ts of our sends in ts validation code?");
1384 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1385 	    SYSCTL_CHILDREN(bbr_measure),
1386 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1387 	    &bbr_min_peer_delta, 20,
1388 	    "What min numerical value should be between the peer deltas?");
1389 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1390 	    SYSCTL_CHILDREN(bbr_measure),
1391 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1392 	    &bbr_delta_percent, 150,
1393 	    "What percentage (150 = 15.0) do we allow variance for?");
1394 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1395 	    SYSCTL_CHILDREN(bbr_measure),
1396 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1397 	    &bbr_min_measurements_req, 1,
1398 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1399 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1400 	    SYSCTL_CHILDREN(bbr_measure),
1401 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1402 	    &bbr_no_pacing_until, 4,
1403 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1404 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1405 	    SYSCTL_CHILDREN(bbr_measure),
1406 	    OID_AUTO, "quanta", CTLFLAG_RW,
1407 	    &bbr_quanta, 2,
1408 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1409 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1410 	    SYSCTL_CHILDREN(bbr_measure),
1411 	    OID_AUTO, "noretran", CTLFLAG_RW,
1412 	    &bbr_no_retran, 0,
1413 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1414 	/* State controls */
1415 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1416 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1417 	    OID_AUTO,
1418 	    "states",
1419 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1420 	    "State controls");
1421 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1422 	    SYSCTL_CHILDREN(bbr_states),
1423 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1424 	    &bbr_uses_idle_restart, 0,
1425 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1426 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1427 	    SYSCTL_CHILDREN(bbr_states),
1428 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1429 	    &bbr_idle_restart_threshold, 100000,
1430 	    "How long must we be idle before we restart??");
1431 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1432 	    SYSCTL_CHILDREN(bbr_states),
1433 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1434 	    &bbr_state_is_pkt_epoch, 0,
1435 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1436 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1437 	    SYSCTL_CHILDREN(bbr_states),
1438 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1439 	    &bbr_rtt_gain_thresh, 0,
1440 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1441 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1442 	    SYSCTL_CHILDREN(bbr_states),
1443 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1444 	    &bbr_drain_floor, 88,
1445 	    "What is the lowest we can drain (pg) too?");
1446 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1447 	    SYSCTL_CHILDREN(bbr_states),
1448 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1449 	    &bbr_state_drain_2_tar, 1,
1450 	    "Do we drain to target in drain substate?");
1451 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1452 	    SYSCTL_CHILDREN(bbr_states),
1453 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1454 	    &bbr_gain_to_target, 1,
1455 	    "Does probe bw gain to target??");
1456 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1457 	    SYSCTL_CHILDREN(bbr_states),
1458 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1459 	    &bbr_gain_gets_extra_too, 1,
1460 	    "Does probe bw gain get the extra time too?");
1461 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1462 	    SYSCTL_CHILDREN(bbr_states),
1463 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1464 	    &bbr_drain_drop_div, 5,
1465 	    "Long drain drop divider?");
1466 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1467 	    SYSCTL_CHILDREN(bbr_states),
1468 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1469 	    &bbr_drain_drop_mul, 4,
1470 	    "Long drain drop multiplier?");
1471 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1472 	    SYSCTL_CHILDREN(bbr_states),
1473 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1474 	    &bbr_rand_ot, 50,
1475 	    "Random discount of the ot?");
1476 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1477 	    SYSCTL_CHILDREN(bbr_states),
1478 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1479 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1480 	    "How many packet-epochs does the b/w delivery rate last?");
1481 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1482 	    SYSCTL_CHILDREN(bbr_states),
1483 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1484 	    &bbr_sub_drain_app_limit, 0,
1485 	    "Does our sub-state drain invoke app limited if its long?");
1486 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1487 	    SYSCTL_CHILDREN(bbr_states),
1488 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1489 	    &bbr_sub_drain_slam_cwnd, 0,
1490 	    "Should we set/recover cwnd for sub-state drain?");
1491 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1492 	    SYSCTL_CHILDREN(bbr_states),
1493 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1494 	    &bbr_slam_cwnd_in_main_drain, 0,
1495 	    "Should we set/recover cwnd for main-state drain?");
1496 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1497 	    SYSCTL_CHILDREN(bbr_states),
1498 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1499 	    &google_allow_early_out, 1,
1500 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1501 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1502 	    SYSCTL_CHILDREN(bbr_states),
1503 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1504 	    &google_consider_lost, 1,
1505 	    "Should we have losses exit gain of probebw in google mode??");
1506 	/* Startup controls */
1507 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1508 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1509 	    OID_AUTO,
1510 	    "startup",
1511 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1512 	    "Startup controls");
1513 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1514 	    SYSCTL_CHILDREN(bbr_startup),
1515 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1516 	    &bbr_sends_full_iwnd, 1,
1517 	    "Do we not pace but burst out initial windows has our TSO size?");
1518 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1519 	    SYSCTL_CHILDREN(bbr_startup),
1520 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1521 	    &bbr_startup_loss_thresh, 2000,
1522 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1523 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1524 	    SYSCTL_CHILDREN(bbr_startup),
1525 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1526 	    &bbr_use_lower_gain_in_startup, 1,
1527 	    "Should we use a lower hptsi gain if we see loss in startup?");
1528 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1529 	    SYSCTL_CHILDREN(bbr_startup),
1530 	    OID_AUTO, "gain", CTLFLAG_RW,
1531 	    &bbr_start_exit, 25,
1532 	    "What gain percent do we need to see to stay in startup??");
1533 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1534 	    SYSCTL_CHILDREN(bbr_startup),
1535 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1536 	    &bbr_low_start_exit, 15,
1537 	    "What gain percent do we need to see to stay in the lower gain startup??");
1538 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1539 	    SYSCTL_CHILDREN(bbr_startup),
1540 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1541 	    &bbr_exit_startup_at_loss, 1,
1542 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1543 	/* CWND controls */
1544 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1545 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1546 	    OID_AUTO,
1547 	    "cwnd",
1548 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1549 	    "Cwnd controls");
1550 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1551 	    SYSCTL_CHILDREN(bbr_cwnd),
1552 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1553 	    &bbr_cwndtarget_rtt_touse, 0,
1554 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1555 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1556 	    SYSCTL_CHILDREN(bbr_cwnd),
1557 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1558 	    &bbr_cwnd_may_shrink, 0,
1559 	    "Can the cwnd shrink if it would grow to more than the target?");
1560 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1561 	    SYSCTL_CHILDREN(bbr_cwnd),
1562 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1563 	    &bbr_target_cwnd_mult_limit, 8,
1564 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1565 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1566 	    SYSCTL_CHILDREN(bbr_cwnd),
1567 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1568 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1569 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1570 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1571 	    SYSCTL_CHILDREN(bbr_cwnd),
1572 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1573 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1574 	    "What is the min cwnd (rttProp > 1ms)");
1575 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1576 	    SYSCTL_CHILDREN(bbr_cwnd),
1577 	    OID_AUTO, "initwin", CTLFLAG_RW,
1578 	    &bbr_def_init_win, 10,
1579 	    "What is the BBR initial window, if 0 use tcp version");
1580 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1581 	    SYSCTL_CHILDREN(bbr_cwnd),
1582 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1583 	    &bbr_do_red, 600,
1584 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1585 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1586 	    SYSCTL_CHILDREN(bbr_cwnd),
1587 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1588 	    &bbr_red_scale, 20000,
1589 	    "What RTT do we scale with?");
1590 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1591 	    SYSCTL_CHILDREN(bbr_cwnd),
1592 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1593 	    &bbr_red_growth_restrict, 1,
1594 	    "Do we restrict cwnd growth for whats in flight?");
1595 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1596 	    SYSCTL_CHILDREN(bbr_cwnd),
1597 	    OID_AUTO, "red_div", CTLFLAG_RW,
1598 	    &bbr_red_div, 2,
1599 	    "If we reduce whats the divisor?");
1600 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1601 	    SYSCTL_CHILDREN(bbr_cwnd),
1602 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1603 	    &bbr_red_mul, 1,
1604 	    "If we reduce whats the mulitiplier?");
1605 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1606 	    SYSCTL_CHILDREN(bbr_cwnd),
1607 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1608 	    &bbr_target_is_bbunit, 0,
1609 	    "Is the state target the pacing_gain or BBR_UNIT?");
1610 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1611 	    SYSCTL_CHILDREN(bbr_cwnd),
1612 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1613 	    &bbr_drop_limit, 0,
1614 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1615 
1616 	/* Timeout controls */
1617 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1618 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1619 	    OID_AUTO,
1620 	    "timeout",
1621 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1622 	    "Time out controls");
1623 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1624 	    SYSCTL_CHILDREN(bbr_timeout),
1625 	    OID_AUTO, "delack", CTLFLAG_RW,
1626 	    &bbr_delack_time, 100000,
1627 	    "BBR's delayed ack time");
1628 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1629 	    SYSCTL_CHILDREN(bbr_timeout),
1630 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1631 	    &bbr_tlp_type_to_use, 3,
1632 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1633 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1634 	    SYSCTL_CHILDREN(bbr_timeout),
1635 	    OID_AUTO, "persmin", CTLFLAG_RW,
1636 	    &bbr_persist_min, 250000,
1637 	    "What is the minimum time in microseconds between persists");
1638 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1639 	    SYSCTL_CHILDREN(bbr_timeout),
1640 	    OID_AUTO, "persmax", CTLFLAG_RW,
1641 	    &bbr_persist_max, 1000000,
1642 	    "What is the largest delay in microseconds between persists");
1643 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1644 	    SYSCTL_CHILDREN(bbr_timeout),
1645 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1646 	    &bbr_tlp_min, 10000,
1647 	    "TLP Min timeout in usecs");
1648 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1649 	    SYSCTL_CHILDREN(bbr_timeout),
1650 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1651 	    &bbr_delayed_ack_time, 200000,
1652 	    "TLP delayed ack compensation value");
1653 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1654 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1655 	    OID_AUTO, "minrto", CTLFLAG_RW,
1656 	    &bbr_rto_min_ms, 30,
1657 	    "Minimum RTO in ms");
1658 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1659 	    SYSCTL_CHILDREN(bbr_timeout),
1660 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1661 	    &bbr_rto_max_sec, 4,
1662 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1663 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1664 	    SYSCTL_CHILDREN(bbr_timeout),
1665 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1666 	    &bbr_tlp_max_resend, 2,
1667 	    "How many times does TLP retry a single segment or multiple with no ACK");
1668 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1669 	    SYSCTL_CHILDREN(bbr_timeout),
1670 	    OID_AUTO, "minto", CTLFLAG_RW,
1671 	    &bbr_min_to, 1000,
1672 	    "Minimum rack timeout in useconds");
1673 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1674 	    SYSCTL_CHILDREN(bbr_timeout),
1675 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1676 	    &bbr_pkt_delay, 1000,
1677 	    "Extra RACK time (in useconds) besides reordering thresh");
1678 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1679 	    SYSCTL_CHILDREN(bbr_timeout),
1680 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1681 	    &bbr_incr_timers, 1,
1682 	    "Increase the RXT/TLP timer by the pacing time used?");
1683 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1684 	    SYSCTL_CHILDREN(bbr_timeout),
1685 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1686 	    &bbr_marks_rxt_sack_passed, 0,
1687 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1688 	/* Policer controls */
1689 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1690 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1691 	    OID_AUTO,
1692 	    "policer",
1693 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1694 	    "Policer controls");
1695 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1696 	    SYSCTL_CHILDREN(bbr_policer),
1697 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1698 	    &bbr_policer_detection_enabled, 1,
1699 	    "Is policer detection enabled??");
1700 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1701 	    SYSCTL_CHILDREN(bbr_policer),
1702 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1703 	    &bbr_lt_intvl_min_rtts, 4,
1704 	    "Minimum number of PE's?");
1705 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1706 	    SYSCTL_CHILDREN(bbr_policer),
1707 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1708 	    &bbr_lt_bw_diff, (4000/8),
1709 	    "Minimal bw diff?");
1710 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1711 	    SYSCTL_CHILDREN(bbr_policer),
1712 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1713 	    &bbr_lt_bw_ratio, 8,
1714 	    "Minimal bw diff?");
1715 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1716 	    SYSCTL_CHILDREN(bbr_policer),
1717 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1718 	    &bbr_policer_call_from_rack_to, 0,
1719 	    "Do we call the policer detection code from a rack-timeout?");
1720 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1721 	    SYSCTL_CHILDREN(bbr_policer),
1722 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1723 	    &bbr_lt_intvl_fp, 0,
1724 	    "What packet epoch do we do false-positive detection at (0=no)?");
1725 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1726 	    SYSCTL_CHILDREN(bbr_policer),
1727 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1728 	    &bbr_lt_loss_thresh, 196,
1729 	    "Loss threshold 196 = 19.6%?");
1730 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1731 	    SYSCTL_CHILDREN(bbr_policer),
1732 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1733 	    &bbr_lt_fd_thresh, 100,
1734 	    "What percentage is the false detection threshold (150=15.0)?");
1735 	/* All the rest */
1736 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1737 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1738 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1739 	    &bbr_use_rack_resend_cheat, 0,
1740 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1741 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1742 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1743 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1744 	    &bbr_error_base_paceout, 10000,
1745 	    "When we hit an error what is the min to pace out in usec's?");
1746 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1747 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1748 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1749 	    &bbr_max_net_error_cnt, 10,
1750 	    "When we hit this many errors in a row, kill the session?");
1751 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1752 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1753 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1754 	    &bbr_ignore_data_after_close, 1,
1755 	    "Do we hold off sending a RST until all pending data is ack'd");
1756 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1757 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1758 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1759 	    &bbr_resends_use_tso, 0,
1760 	    "Can resends use TSO?");
1761 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1762 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1763 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1764 	    &bbr_sack_block_limit, 128,
1765 	    "When do we start ignoring small sack blocks");
1766 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1767 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1768 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1769 	    &bbr_verbose_logging, 0,
1770 	    "Should BBR black box logging be verbose");
1771 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1772 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1773 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1774 	    &bbr_reorder_thresh, 2,
1775 	    "What factor for rack will be added when seeing reordering (shift right)");
1776 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1777 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1778 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1779 	    &bbr_reorder_fade, 0,
1780 	    "Does reorder detection fade, if so how many ms (0 means never)");
1781 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1782 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1783 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1784 	    &bbr_tlp_thresh, 1,
1785 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1786 	/* Stats and counters */
1787 	/* The pacing counters for hdwr/software can't be in the array */
1788 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1789 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1790 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1791 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1792 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1793 	    &bbr_hdwr_pacing_enobuf,
1794 	    "Total number of enobufs for hardware paced flows");
1795 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1796 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1797 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1798 	    &bbr_nohdwr_pacing_enobuf,
1799 	    "Total number of enobufs for non-hardware paced flows");
1800 
1801 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1802 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1803 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1804 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1805 	    &bbr_flows_whdwr_pacing,
1806 	    "Total number of hardware paced flows");
1807 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1808 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1809 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1810 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1811 	    &bbr_flows_nohdwr_pacing,
1812 	    "Total number of software paced flows");
1813 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1814 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1815 	    OID_AUTO, "stats", CTLFLAG_RD,
1816 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1817 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1818 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1819 	    OID_AUTO, "opts", CTLFLAG_RD,
1820 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1821 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1822 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1823 	    OID_AUTO, "lost", CTLFLAG_RD,
1824 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1825 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1826 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1827 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1828 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1829 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1830 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1831 	    OID_AUTO, "statetime", CTLFLAG_RD,
1832 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1833 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1834 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1835 	    OID_AUTO, "outsize", CTLFLAG_RD,
1836 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1837 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1838 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1839 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1840 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1841 }
1842 
1843 static void
1844 bbr_counter_destroy(void)
1845 {
1846 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1847 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1848 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1849 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1850 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1851 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1852 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1853 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1854 	counter_u64_free(bbr_flows_whdwr_pacing);
1855 	counter_u64_free(bbr_flows_nohdwr_pacing);
1856 
1857 }
1858 
1859 static __inline void
1860 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1861 {
1862 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1863 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1864 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1865 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1866 	l->bw_inuse = bbr_get_bw(bbr);
1867 	l->inflight = ctf_flight_size(bbr->rc_tp,
1868 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1869 	l->applimited = bbr->r_ctl.r_app_limited_until;
1870 	l->delivered = bbr->r_ctl.rc_delivered;
1871 	l->timeStamp = cts;
1872 	l->lost = bbr->r_ctl.rc_lost;
1873 	l->bbr_state = bbr->rc_bbr_state;
1874 	l->bbr_substate = bbr_state_val(bbr);
1875 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1876 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1877 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1878 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1879 	l->inhpts = tcp_in_hpts(bbr->rc_inp);
1880 	l->use_lt_bw = bbr->rc_lt_use_bw;
1881 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1882 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1883 }
1884 
1885 static void
1886 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1887 {
1888 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1889 		union tcp_log_stackspecific log;
1890 
1891 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1892 		log.u_bbr.flex1 = 0;
1893 		log.u_bbr.flex2 = 0;
1894 		log.u_bbr.flex5 = 0;
1895 		log.u_bbr.flex3 = 0;
1896 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1897 		log.u_bbr.flex7 = reason;
1898 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1899 		log.u_bbr.flex8 = 0;
1900 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1901 		    &bbr->rc_inp->inp_socket->so_rcv,
1902 		    &bbr->rc_inp->inp_socket->so_snd,
1903 		    BBR_LOG_BW_RED_EV, 0,
1904 		    0, &log, false, &bbr->rc_tv);
1905 	}
1906 }
1907 
1908 static void
1909 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1910 {
1911 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1912 		union tcp_log_stackspecific log;
1913 
1914 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1915 		log.u_bbr.flex1 = seq;
1916 		log.u_bbr.flex2 = count;
1917 		log.u_bbr.flex8 = mode;
1918 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1919 		    &bbr->rc_inp->inp_socket->so_rcv,
1920 		    &bbr->rc_inp->inp_socket->so_snd,
1921 		    BBR_LOG_LOWGAIN, 0,
1922 		    0, &log, false, &bbr->rc_tv);
1923 	}
1924 }
1925 
1926 static void
1927 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1928     uint8_t reason, uint32_t p_maxseg, int len)
1929 {
1930 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1931 		union tcp_log_stackspecific log;
1932 
1933 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1934 		log.u_bbr.flex1 = p_maxseg;
1935 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1936 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1937 		log.u_bbr.flex4 = reason;
1938 		log.u_bbr.flex5 = bbr->rc_in_persist;
1939 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1940 		log.u_bbr.flex7 = p_maxseg;
1941 		log.u_bbr.flex8 = bbr->rc_in_persist;
1942 		log.u_bbr.pkts_out = 0;
1943 		log.u_bbr.applimited = len;
1944 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1945 		    &bbr->rc_inp->inp_socket->so_rcv,
1946 		    &bbr->rc_inp->inp_socket->so_snd,
1947 		    BBR_LOG_JUSTRET, 0,
1948 		    tlen, &log, false, &bbr->rc_tv);
1949 	}
1950 }
1951 
1952 static void
1953 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1954 {
1955 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1956 		union tcp_log_stackspecific log;
1957 
1958 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1959 		log.u_bbr.flex1 = seq;
1960 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1961 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1962 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1963 		    &bbr->rc_inp->inp_socket->so_rcv,
1964 		    &bbr->rc_inp->inp_socket->so_snd,
1965 		    BBR_LOG_ENTREC, 0,
1966 		    0, &log, false, &bbr->rc_tv);
1967 	}
1968 }
1969 
1970 static void
1971 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)
1972 {
1973 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
1974 		union tcp_log_stackspecific log;
1975 
1976 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1977 		log.u_bbr.flex1 = tso;
1978 		log.u_bbr.flex2 = maxseg;
1979 		log.u_bbr.flex3 = mtu;
1980 		log.u_bbr.flex4 = csum_flags;
1981 		TCP_LOG_EVENTP(tp, NULL,
1982 		    &bbr->rc_inp->inp_socket->so_rcv,
1983 		    &bbr->rc_inp->inp_socket->so_snd,
1984 		    BBR_LOG_MSGSIZE, 0,
1985 		    0, &log, false, &bbr->rc_tv);
1986 	}
1987 }
1988 
1989 static void
1990 bbr_log_flowend(struct tcp_bbr *bbr)
1991 {
1992 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1993 		union tcp_log_stackspecific log;
1994 		struct sockbuf *r, *s;
1995 		struct timeval tv;
1996 
1997 		if (bbr->rc_inp->inp_socket) {
1998 			r = &bbr->rc_inp->inp_socket->so_rcv;
1999 			s = &bbr->rc_inp->inp_socket->so_snd;
2000 		} else {
2001 			r = s = NULL;
2002 		}
2003 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2004 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2005 		    r, s,
2006 		    TCP_LOG_FLOWEND, 0,
2007 		    0, &log, false, &tv);
2008 	}
2009 }
2010 
2011 static void
2012 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2013     uint32_t lost, uint32_t del)
2014 {
2015 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2016 		union tcp_log_stackspecific log;
2017 
2018 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2019 		log.u_bbr.flex1 = lost;
2020 		log.u_bbr.flex2 = del;
2021 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2022 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2023 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2024 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2025 		log.u_bbr.flex7 = line;
2026 		log.u_bbr.flex8 = 0;
2027 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2028 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2029 		    &bbr->rc_inp->inp_socket->so_rcv,
2030 		    &bbr->rc_inp->inp_socket->so_snd,
2031 		    BBR_LOG_PKT_EPOCH, 0,
2032 		    0, &log, false, &bbr->rc_tv);
2033 	}
2034 }
2035 
2036 static void
2037 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2038 {
2039 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2040 		union tcp_log_stackspecific log;
2041 
2042 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2043 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2044 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2045 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2046 		log.u_bbr.flex7 = line;
2047 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2048 		    &bbr->rc_inp->inp_socket->so_rcv,
2049 		    &bbr->rc_inp->inp_socket->so_snd,
2050 		    BBR_LOG_TIME_EPOCH, 0,
2051 		    0, &log, false, &bbr->rc_tv);
2052 	}
2053 }
2054 
2055 static void
2056 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2057 {
2058 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2059 		union tcp_log_stackspecific log;
2060 
2061 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2062 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2063 		log.u_bbr.flex2 = new_tar;
2064 		log.u_bbr.flex3 = line;
2065 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2066 		log.u_bbr.flex5 = bbr_quanta;
2067 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2068 		log.u_bbr.flex7 = bbr->rc_last_options;
2069 		log.u_bbr.flex8 = meth;
2070 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2071 		    &bbr->rc_inp->inp_socket->so_rcv,
2072 		    &bbr->rc_inp->inp_socket->so_snd,
2073 		    BBR_LOG_STATE_TARGET, 0,
2074 		    0, &log, false, &bbr->rc_tv);
2075 	}
2076 
2077 }
2078 
2079 static void
2080 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2081 {
2082 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2083 		union tcp_log_stackspecific log;
2084 
2085 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2086 		log.u_bbr.flex1 = line;
2087 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2088 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2089 		if (bbr_state_is_pkt_epoch)
2090 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2091 		else
2092 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2093 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2094 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2095 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2096 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2097 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2098 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2099 		    &bbr->rc_inp->inp_socket->so_rcv,
2100 		    &bbr->rc_inp->inp_socket->so_snd,
2101 		    BBR_LOG_STATE, 0,
2102 		    0, &log, false, &bbr->rc_tv);
2103 	}
2104 }
2105 
2106 static void
2107 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2108 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2109 {
2110 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2111 		union tcp_log_stackspecific log;
2112 
2113 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2114 		log.u_bbr.flex1 = line;
2115 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2116 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2117 		log.u_bbr.flex4 = applied;
2118 		log.u_bbr.flex5 = rtt;
2119 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2120 		log.u_bbr.flex7 = cond;
2121 		log.u_bbr.flex8 = reas;
2122 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2123 		    &bbr->rc_inp->inp_socket->so_rcv,
2124 		    &bbr->rc_inp->inp_socket->so_snd,
2125 		    BBR_LOG_RTT_SHRINKS, 0,
2126 		    0, &log, false, &bbr->rc_tv);
2127 	}
2128 }
2129 
2130 static void
2131 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2132 {
2133 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2134 		union tcp_log_stackspecific log;
2135 
2136 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2137 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2138 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2139 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2140 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2141 		    &bbr->rc_inp->inp_socket->so_rcv,
2142 		    &bbr->rc_inp->inp_socket->so_snd,
2143 		    BBR_LOG_EXITREC, 0,
2144 		    0, &log, false, &bbr->rc_tv);
2145 	}
2146 }
2147 
2148 static void
2149 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2150     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2151 {
2152 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2153 		union tcp_log_stackspecific log;
2154 
2155 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2156 		log.u_bbr.flex1 = line;
2157 		log.u_bbr.flex2 = prev_acked;
2158 		log.u_bbr.flex3 = bytes_this_ack;
2159 		log.u_bbr.flex4 = chg;
2160 		log.u_bbr.flex5 = th_ack;
2161 		log.u_bbr.flex6 = target;
2162 		log.u_bbr.flex8 = meth;
2163 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2164 		    &bbr->rc_inp->inp_socket->so_rcv,
2165 		    &bbr->rc_inp->inp_socket->so_snd,
2166 		    BBR_LOG_CWND, 0,
2167 		    0, &log, false, &bbr->rc_tv);
2168 	}
2169 }
2170 
2171 static void
2172 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2173 {
2174 	/*
2175 	 * Log the rtt sample we are applying to the srtt algorithm in
2176 	 * useconds.
2177 	 */
2178 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2179 		union tcp_log_stackspecific log;
2180 
2181 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2182 		log.u_bbr.flex1 = rtt;
2183 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2184 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2185 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2186 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2187 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2188 		log.u_bbr.flex6 = tsin;
2189 		log.u_bbr.flex7 = 0;
2190 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2191 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2192 		    &bbr->rc_inp->inp_socket->so_rcv,
2193 		    &bbr->rc_inp->inp_socket->so_snd,
2194 		    TCP_LOG_RTT, 0,
2195 		    0, &log, false, &bbr->rc_tv);
2196 	}
2197 }
2198 
2199 static void
2200 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2201 {
2202 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2203 		union tcp_log_stackspecific log;
2204 
2205 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2206 		log.u_bbr.flex1 = time_in;
2207 		log.u_bbr.flex2 = line;
2208 		log.u_bbr.flex8 = enter_exit;
2209 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2210 		    &bbr->rc_inp->inp_socket->so_rcv,
2211 		    &bbr->rc_inp->inp_socket->so_snd,
2212 		    BBR_LOG_PERSIST, 0,
2213 		    0, &log, false, &bbr->rc_tv);
2214 	}
2215 }
2216 static void
2217 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2218 {
2219 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2220 		union tcp_log_stackspecific log;
2221 
2222 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2223 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2224 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2225 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2226 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2227 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2228 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2229 		    &bbr->rc_inp->inp_socket->so_rcv,
2230 		    &bbr->rc_inp->inp_socket->so_snd,
2231 		    BBR_LOG_ACKCLEAR, 0,
2232 		    0, &log, false, &bbr->rc_tv);
2233 	}
2234 }
2235 
2236 static void
2237 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2238 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2239 {
2240 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2241 		union tcp_log_stackspecific log;
2242 		struct timeval tv;
2243 
2244 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2245 		log.u_bbr.flex1 = nsegs;
2246 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2247 		if (m) {
2248 			struct timespec ts;
2249 
2250 			log.u_bbr.flex3 = m->m_flags;
2251 			if (m->m_flags & M_TSTMP) {
2252 				mbuf_tstmp2timespec(m, &ts);
2253 				tv.tv_sec = ts.tv_sec;
2254 				tv.tv_usec = ts.tv_nsec / 1000;
2255 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2256 			} else {
2257 				log.u_bbr.lt_epoch = 0;
2258 			}
2259 			if (m->m_flags & M_TSTMP_LRO) {
2260 				mbuf_tstmp2timeval(m, &tv);
2261 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2262 			} else {
2263 				/* No arrival timestamp */
2264 				log.u_bbr.flex5 = 0;
2265 			}
2266 
2267 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2268 		} else {
2269 			log.u_bbr.flex3 = 0;
2270 			log.u_bbr.flex5 = 0;
2271 			log.u_bbr.flex6 = 0;
2272 			log.u_bbr.pkts_out = 0;
2273 		}
2274 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2275 		log.u_bbr.flex7 = bbr->r_wanted_output;
2276 		log.u_bbr.flex8 = bbr->rc_in_persist;
2277 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2278 		    &bbr->rc_inp->inp_socket->so_rcv,
2279 		    &bbr->rc_inp->inp_socket->so_snd,
2280 		    TCP_LOG_IN, 0,
2281 		    tlen, &log, true, &bbr->rc_tv);
2282 	}
2283 }
2284 
2285 static void
2286 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2287 {
2288 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2289 		union tcp_log_stackspecific log;
2290 
2291 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2292 		log.u_bbr.flex1 = did_out;
2293 		log.u_bbr.flex2 = nxt_pkt;
2294 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2295 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2296 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2297 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2298 		log.u_bbr.flex7 = bbr->r_wanted_output;
2299 		log.u_bbr.flex8 = bbr->rc_in_persist;
2300 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2301 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2302 		    &bbr->rc_inp->inp_socket->so_rcv,
2303 		    &bbr->rc_inp->inp_socket->so_snd,
2304 		    BBR_LOG_DOSEG_DONE, 0,
2305 		    0, &log, true, &bbr->rc_tv);
2306 	}
2307 }
2308 
2309 static void
2310 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2311     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2312 {
2313 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2314 		union tcp_log_stackspecific log;
2315 
2316 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2317 		log.u_bbr.flex1 = line;
2318 		log.u_bbr.flex2 = o_len;
2319 		log.u_bbr.flex3 = segcnt;
2320 		log.u_bbr.flex4 = segsiz;
2321 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2322 		    &bbr->rc_inp->inp_socket->so_rcv,
2323 		    &bbr->rc_inp->inp_socket->so_snd,
2324 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2325 		    len, &log, true, &bbr->rc_tv);
2326 	}
2327 }
2328 
2329 static void
2330 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2331 {
2332 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2333 		union tcp_log_stackspecific log;
2334 
2335 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2336 		log.u_bbr.flex1 = timers;
2337 		log.u_bbr.flex2 = ret;
2338 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2339 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2340 		log.u_bbr.flex5 = cts;
2341 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2342 		log.u_bbr.flex8 = hpts_calling;
2343 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2344 		    &bbr->rc_inp->inp_socket->so_rcv,
2345 		    &bbr->rc_inp->inp_socket->so_snd,
2346 		    BBR_LOG_TO_PROCESS, 0,
2347 		    0, &log, false, &bbr->rc_tv);
2348 	}
2349 }
2350 
2351 static void
2352 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2353 {
2354 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2355 		union tcp_log_stackspecific log;
2356 		uint64_t ar;
2357 
2358 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2359 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2360 		log.u_bbr.flex2 = 0;
2361 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2362 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2363 		ar >>= 32;
2364 		ar &= 0x00000000ffffffff;
2365 		log.u_bbr.flex4 = (uint32_t)ar;
2366 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2367 		ar &= 0x00000000ffffffff;
2368 		log.u_bbr.flex5 = (uint32_t)ar;
2369 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2370 		log.u_bbr.flex8 = to_num;
2371 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2372 		    &bbr->rc_inp->inp_socket->so_rcv,
2373 		    &bbr->rc_inp->inp_socket->so_snd,
2374 		    BBR_LOG_RTO, 0,
2375 		    0, &log, false, &bbr->rc_tv);
2376 	}
2377 }
2378 
2379 static void
2380 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2381 {
2382 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2383 		union tcp_log_stackspecific log;
2384 
2385 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2386 		log.u_bbr.flex1 = flex1;
2387 		log.u_bbr.flex2 = flex2;
2388 		log.u_bbr.flex3 = flex3;
2389 		log.u_bbr.flex4 = 0;
2390 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2391 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2392 		log.u_bbr.flex8 = reason;
2393 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2394 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2395 		    &bbr->rc_inp->inp_socket->so_rcv,
2396 		    &bbr->rc_inp->inp_socket->so_snd,
2397 		    BBR_LOG_REDUCE, 0,
2398 		    0, &log, false, &bbr->rc_tv);
2399 	}
2400 }
2401 
2402 static void
2403 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2404 {
2405 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2406 		union tcp_log_stackspecific log;
2407 
2408 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2409 		log.u_bbr.flex1 = diag->p_nxt_slot;
2410 		log.u_bbr.flex2 = diag->p_cur_slot;
2411 		log.u_bbr.flex3 = diag->slot_req;
2412 		log.u_bbr.flex4 = diag->inp_hptsslot;
2413 		log.u_bbr.flex5 = diag->slot_remaining;
2414 		log.u_bbr.flex6 = diag->need_new_to;
2415 		log.u_bbr.flex7 = diag->p_hpts_active;
2416 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2417 		/* Hijack other fields as needed  */
2418 		log.u_bbr.epoch = diag->have_slept;
2419 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2420 		log.u_bbr.pkts_out = diag->co_ret;
2421 		log.u_bbr.applimited = diag->hpts_sleep_time;
2422 		log.u_bbr.delivered = diag->p_prev_slot;
2423 		log.u_bbr.inflight = diag->p_runningslot;
2424 		log.u_bbr.bw_inuse = diag->wheel_slot;
2425 		log.u_bbr.rttProp = diag->wheel_cts;
2426 		log.u_bbr.delRate = diag->maxslots;
2427 		log.u_bbr.cur_del_rate = diag->p_curtick;
2428 		log.u_bbr.cur_del_rate <<= 32;
2429 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2430 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2431 		    &bbr->rc_inp->inp_socket->so_rcv,
2432 		    &bbr->rc_inp->inp_socket->so_snd,
2433 		    BBR_LOG_HPTSDIAG, 0,
2434 		    0, &log, false, &bbr->rc_tv);
2435 	}
2436 }
2437 
2438 static void
2439 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2440     uint32_t thresh, uint32_t to)
2441 {
2442 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2443 		union tcp_log_stackspecific log;
2444 
2445 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2446 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2447 		log.u_bbr.flex2 = time_since_sent;
2448 		log.u_bbr.flex3 = srtt;
2449 		log.u_bbr.flex4 = thresh;
2450 		log.u_bbr.flex5 = to;
2451 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2452 		log.u_bbr.flex8 = mode;
2453 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2454 		    &bbr->rc_inp->inp_socket->so_rcv,
2455 		    &bbr->rc_inp->inp_socket->so_snd,
2456 		    BBR_LOG_TIMERPREP, 0,
2457 		    0, &log, false, &bbr->rc_tv);
2458 	}
2459 }
2460 
2461 static void
2462 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2463     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2464 {
2465 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2466 		union tcp_log_stackspecific log;
2467 
2468 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2469 		log.u_bbr.flex1 = usecs;
2470 		log.u_bbr.flex2 = len;
2471 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2472 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2473 		if (override)
2474 			log.u_bbr.flex5 = (1 << 2);
2475 		else
2476 			log.u_bbr.flex5 = 0;
2477 		log.u_bbr.flex6 = override;
2478 		log.u_bbr.flex7 = gain;
2479 		log.u_bbr.flex8 = mod;
2480 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2481 		    &bbr->rc_inp->inp_socket->so_rcv,
2482 		    &bbr->rc_inp->inp_socket->so_snd,
2483 		    BBR_LOG_HPTSI_CALC, 0,
2484 		    len, &log, false, &bbr->rc_tv);
2485 	}
2486 }
2487 
2488 static void
2489 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2490 {
2491 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2492 		union tcp_log_stackspecific log;
2493 
2494 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2495 
2496 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2497 		log.u_bbr.flex2 = to;
2498 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2499 		log.u_bbr.flex4 = slot;
2500 		log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2501 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2502 		log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2503 		log.u_bbr.flex8 = which;
2504 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2505 		    &bbr->rc_inp->inp_socket->so_rcv,
2506 		    &bbr->rc_inp->inp_socket->so_snd,
2507 		    BBR_LOG_TIMERSTAR, 0,
2508 		    0, &log, false, &bbr->rc_tv);
2509 	}
2510 }
2511 
2512 static void
2513 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)
2514 {
2515 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2516 		union tcp_log_stackspecific log;
2517 
2518 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2519 		log.u_bbr.flex1 = thresh;
2520 		log.u_bbr.flex2 = lro;
2521 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2522 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2523 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2524 		log.u_bbr.flex6 = srtt;
2525 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2526 		log.u_bbr.flex8 = frm;
2527 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2528 		    &bbr->rc_inp->inp_socket->so_rcv,
2529 		    &bbr->rc_inp->inp_socket->so_snd,
2530 		    BBR_LOG_THRESH_CALC, 0,
2531 		    0, &log, false, &bbr->rc_tv);
2532 	}
2533 }
2534 
2535 static void
2536 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2537 {
2538 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2539 		union tcp_log_stackspecific log;
2540 
2541 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2542 		log.u_bbr.flex1 = line;
2543 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2544 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2545 		log.u_bbr.flex4 = bbr->rc_in_persist;
2546 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2547 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2548 		log.u_bbr.flex8 = hpts_removed;
2549 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2550 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2551 		    &bbr->rc_inp->inp_socket->so_rcv,
2552 		    &bbr->rc_inp->inp_socket->so_snd,
2553 		    BBR_LOG_TIMERCANC, 0,
2554 		    0, &log, false, &bbr->rc_tv);
2555 	}
2556 }
2557 
2558 static void
2559 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2560 {
2561 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2562 		union tcp_log_stackspecific log;
2563 
2564 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2565 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2566 		log.u_bbr.flex2 = (peer_delta >> 32);
2567 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2568 		log.u_bbr.flex4 = (delta >> 32);
2569 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2570 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2571 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2572 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2573 		    &bbr->rc_inp->inp_socket->so_rcv,
2574 		    &bbr->rc_inp->inp_socket->so_snd,
2575 		    BBR_LOG_TSTMP_VAL, 0,
2576 		    0, &log, false, &bbr->rc_tv);
2577 	}
2578 }
2579 
2580 static void
2581 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)
2582 {
2583 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2584 		union tcp_log_stackspecific log;
2585 
2586 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2587 		log.u_bbr.flex1 = tsosz;
2588 		log.u_bbr.flex2 = tls;
2589 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2590 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2591 		log.u_bbr.flex5 = old_val;
2592 		log.u_bbr.flex6 = maxseg;
2593 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2594 		log.u_bbr.flex7 <<= 1;
2595 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2596 		if (hdwr)
2597 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2598 		else
2599 			log.u_bbr.flex8 = bbr->rc_use_google;
2600 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2601 		    &bbr->rc_inp->inp_socket->so_rcv,
2602 		    &bbr->rc_inp->inp_socket->so_snd,
2603 		    BBR_LOG_BBRTSO, 0,
2604 		    0, &log, false, &bbr->rc_tv);
2605 	}
2606 }
2607 
2608 static void
2609 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2610 		      uint32_t flags, uint32_t line)
2611 {
2612 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2613 		union tcp_log_stackspecific log;
2614 
2615 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2616 		log.u_bbr.flex1 = line;
2617 		log.u_bbr.flex2 = rsm->r_start;
2618 		log.u_bbr.flex3 = rsm->r_end;
2619 		log.u_bbr.flex4 = rsm->r_delivered;
2620 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2621 		log.u_bbr.flex6 = rsm->r_dupack;
2622 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2623 		log.u_bbr.flex8 = rsm->r_flags;
2624 		/* Hijack the pkts_out fids */
2625 		log.u_bbr.applimited = flags;
2626 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2627 		    &bbr->rc_inp->inp_socket->so_rcv,
2628 		    &bbr->rc_inp->inp_socket->so_snd,
2629 		    BBR_RSM_CLEARED, 0,
2630 		    0, &log, false, &bbr->rc_tv);
2631 	}
2632 }
2633 
2634 static void
2635 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2636     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2637     uint32_t flex6, uint32_t pkts_out, int flex7,
2638     uint32_t flex4, uint32_t flex1)
2639 {
2640 
2641 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2642 		union tcp_log_stackspecific log;
2643 
2644 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2645 		log.u_bbr.flex1 = flex1;
2646 		log.u_bbr.flex2 = flex2;
2647 		log.u_bbr.flex3 = flex3;
2648 		log.u_bbr.flex4 = flex4;
2649 		log.u_bbr.flex5 = flex5;
2650 		log.u_bbr.flex6 = flex6;
2651 		log.u_bbr.flex7 = flex7;
2652 		/* Hijack the pkts_out fids */
2653 		log.u_bbr.pkts_out = pkts_out;
2654 		log.u_bbr.flex8 = flex8;
2655 		if (bbr->rc_ack_was_delayed)
2656 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2657 		else
2658 			log.u_bbr.epoch = 0;
2659 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2660 		    &bbr->rc_inp->inp_socket->so_rcv,
2661 		    &bbr->rc_inp->inp_socket->so_snd,
2662 		    BBR_LOG_BBRUPD, 0,
2663 		    flex2, &log, false, &bbr->rc_tv);
2664 	}
2665 }
2666 
2667 static void
2668 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2669 	uint32_t newbw, uint32_t obw, uint32_t diff,
2670 	uint32_t tim)
2671 {
2672 	if (/*bbr_verbose_logging && */(bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2673 		union tcp_log_stackspecific log;
2674 
2675 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2676 		log.u_bbr.flex1 = reason;
2677 		log.u_bbr.flex2 = newbw;
2678 		log.u_bbr.flex3 = obw;
2679 		log.u_bbr.flex4 = diff;
2680 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2681 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2682 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2683 		log.u_bbr.pkts_out = tim;
2684 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2685 		if (bbr->rc_lt_use_bw == 0)
2686 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2687 		else
2688 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2689 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2690 		    &bbr->rc_inp->inp_socket->so_rcv,
2691 		    &bbr->rc_inp->inp_socket->so_snd,
2692 		    BBR_LOG_BWSAMP, 0,
2693 		    0, &log, false, &bbr->rc_tv);
2694 	}
2695 }
2696 
2697 static inline void
2698 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2699 {
2700 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2701 		union tcp_log_stackspecific log;
2702 
2703 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2704 		log.u_bbr.flex1 = line;
2705 		log.u_bbr.flex2 = tick;
2706 		log.u_bbr.flex3 = tp->t_maxunacktime;
2707 		log.u_bbr.flex4 = tp->t_acktime;
2708 		log.u_bbr.flex8 = event;
2709 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2710 		    &bbr->rc_inp->inp_socket->so_rcv,
2711 		    &bbr->rc_inp->inp_socket->so_snd,
2712 		    BBR_LOG_PROGRESS, 0,
2713 		    0, &log, false, &bbr->rc_tv);
2714 	}
2715 }
2716 
2717 static void
2718 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2719 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2720 			 int error)
2721 {
2722 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2723 		union tcp_log_stackspecific log;
2724 
2725 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2726 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2727 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2728 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2729 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2730 		log.u_bbr.bw_inuse = rate;
2731 		log.u_bbr.flex5 = line;
2732 		log.u_bbr.flex6 = error;
2733 		log.u_bbr.flex8 = bbr->skip_gain;
2734 		log.u_bbr.flex8 <<= 1;
2735 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2736 		log.u_bbr.flex8 <<= 1;
2737 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2738 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2739 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2740 		    &bbr->rc_inp->inp_socket->so_rcv,
2741 		    &bbr->rc_inp->inp_socket->so_snd,
2742 		    BBR_LOG_HDWR_PACE, 0,
2743 		    0, &log, false, &bbr->rc_tv);
2744 	}
2745 }
2746 
2747 static void
2748 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)
2749 {
2750 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2751 		union tcp_log_stackspecific log;
2752 
2753 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2754 		log.u_bbr.flex1 = slot;
2755 		log.u_bbr.flex2 = del_by;
2756 		log.u_bbr.flex3 = prev_delay;
2757 		log.u_bbr.flex4 = line;
2758 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2759 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2760 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2761 		log.u_bbr.flex8 = bbr->rc_in_persist;
2762 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2763 		    &bbr->rc_inp->inp_socket->so_rcv,
2764 		    &bbr->rc_inp->inp_socket->so_snd,
2765 		    BBR_LOG_BBRSND, 0,
2766 		    len, &log, false, &bbr->rc_tv);
2767 	}
2768 }
2769 
2770 static void
2771 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)
2772 {
2773 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2774 		union tcp_log_stackspecific log;
2775 
2776 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2777 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2778 		log.u_bbr.flex2 = 0;
2779 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2780 		log.u_bbr.flex4 = end;
2781 		log.u_bbr.flex5 = seq;
2782 		log.u_bbr.flex6 = t;
2783 		log.u_bbr.flex7 = match;
2784 		log.u_bbr.flex8 = flags;
2785 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2786 		    &bbr->rc_inp->inp_socket->so_rcv,
2787 		    &bbr->rc_inp->inp_socket->so_snd,
2788 		    BBR_LOG_BBRRTT, 0,
2789 		    0, &log, false, &bbr->rc_tv);
2790 	}
2791 }
2792 
2793 static void
2794 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2795 {
2796 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2797 		union tcp_log_stackspecific log;
2798 
2799 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2800 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2801 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2802 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2803 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2804 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2805 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2806 		log.u_bbr.flex7 = 0;
2807 		log.u_bbr.flex8 = entry_method;
2808 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2809 		    &bbr->rc_inp->inp_socket->so_rcv,
2810 		    &bbr->rc_inp->inp_socket->so_snd,
2811 		    BBR_LOG_EXIT_GAIN, 0,
2812 		    0, &log, false, &bbr->rc_tv);
2813 	}
2814 }
2815 
2816 static void
2817 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2818 {
2819 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2820 		union tcp_log_stackspecific log;
2821 
2822 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2823 		/* R-HU */
2824 		log.u_bbr.flex1 = 0;
2825 		log.u_bbr.flex2 = 0;
2826 		log.u_bbr.flex3 = 0;
2827 		log.u_bbr.flex4 = 0;
2828 		log.u_bbr.flex7 = 0;
2829 		log.u_bbr.flex8 = settings_desired;
2830 
2831 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2832 		    &bbr->rc_inp->inp_socket->so_rcv,
2833 		    &bbr->rc_inp->inp_socket->so_snd,
2834 		    BBR_LOG_SETTINGS_CHG, 0,
2835 		    0, &log, false, &bbr->rc_tv);
2836 	}
2837 }
2838 
2839 /*
2840  * Returns the bw from the our filter.
2841  */
2842 static inline uint64_t
2843 bbr_get_full_bw(struct tcp_bbr *bbr)
2844 {
2845 	uint64_t bw;
2846 
2847 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2848 
2849 	return (bw);
2850 }
2851 
2852 static inline void
2853 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2854 {
2855 	uint64_t calclr;
2856 	uint32_t lost, del;
2857 
2858 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2859 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2860 	else
2861 		lost = 0;
2862 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2863 	if (lost == 0)  {
2864 		calclr = 0;
2865 	} else if (del) {
2866 		calclr = lost;
2867 		calclr *= (uint64_t)1000;
2868 		calclr /= (uint64_t)del;
2869 	} else {
2870 		/* Nothing delivered? 100.0% loss */
2871 		calclr = 1000;
2872 	}
2873 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2874 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2875 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2876 	bbr->r_ctl.rc_pkt_epoch++;
2877 	if (bbr->rc_no_pacing &&
2878 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2879 		bbr->rc_no_pacing = 0;
2880 		tcp_bbr_tso_size_check(bbr, cts);
2881 	}
2882 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2883 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2884 	/* What was our loss rate */
2885 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2886 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2887 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2888 }
2889 
2890 static inline void
2891 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2892 {
2893 	uint32_t epoch_time;
2894 
2895 	/* Tick the RTT clock */
2896 	bbr->r_ctl.rc_rtt_epoch++;
2897 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2898 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2899 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2900 }
2901 
2902 static inline void
2903 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2904 {
2905 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2906 		bbr->rc_is_pkt_epoch_now = 1;
2907 	}
2908 }
2909 
2910 /*
2911  * Returns the bw from either the b/w filter
2912  * or from the lt_bw (if the connection is being
2913  * policed).
2914  */
2915 static inline uint64_t
2916 __bbr_get_bw(struct tcp_bbr *bbr)
2917 {
2918 	uint64_t bw, min_bw;
2919 	uint64_t rtt;
2920 	int gm_measure_cnt = 1;
2921 
2922 	/*
2923 	 * For startup we make, like google, a
2924 	 * minimum b/w. This is generated from the
2925 	 * IW and the rttProp. We do fall back to srtt
2926 	 * if for some reason (initial handshake) we don't
2927 	 * have a rttProp. We, in the worst case, fall back
2928 	 * to the configured min_bw (rc_initial_hptsi_bw).
2929 	 */
2930 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2931 		/* Attempt first to use rttProp */
2932 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2933 		if (rtt && (rtt < 0xffffffff)) {
2934 measure:
2935 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2936 				((uint64_t)1000000);
2937 			min_bw /= rtt;
2938 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2939 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2940 			}
2941 
2942 		} else if (bbr->rc_tp->t_srtt != 0) {
2943 			/* No rttProp, use srtt? */
2944 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2945 			goto measure;
2946 		} else {
2947 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2948 		}
2949 	} else
2950 		min_bw = 0;
2951 
2952 	if ((bbr->rc_past_init_win == 0) &&
2953 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2954 		bbr->rc_past_init_win = 1;
2955 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2956 		gm_measure_cnt = 0;
2957 	if (gm_measure_cnt &&
2958 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2959 	     (bbr->rc_past_init_win == 0))) {
2960 		/* For google we use our guess rate until we get 1 measurement */
2961 
2962 use_initial_window:
2963 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2964 		if (rtt && (rtt < 0xffffffff)) {
2965 			/*
2966 			 * We have an RTT measurement. Use that in
2967 			 * combination with our initial window to calculate
2968 			 * a b/w.
2969 			 */
2970 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2971 				((uint64_t)1000000);
2972 			bw /= rtt;
2973 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2974 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2975 			}
2976 		} else {
2977 			/* Drop back to the 40 and punt to a default */
2978 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2979 		}
2980 		if (bw < 1)
2981 			/* Probably should panic */
2982 			bw = 1;
2983 		if (bw > min_bw)
2984 			return (bw);
2985 		else
2986 			return (min_bw);
2987 	}
2988 	if (bbr->rc_lt_use_bw)
2989 		bw = bbr->r_ctl.rc_lt_bw;
2990 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2991 		bw = bbr->r_ctl.red_bw;
2992 	else
2993 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2994 	if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
2995 		/*
2996 		 * Enforce user set rate limit, keep in mind that
2997 		 * t_peakrate_thr is in B/s already
2998 		 */
2999 		bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3000 	}
3001 	if (bw == 0) {
3002 		/* We should not be at 0, go to the initial window then  */
3003 		goto use_initial_window;
3004 	}
3005 	if (bw < 1)
3006 		/* Probably should panic */
3007 		bw = 1;
3008 	if (bw < min_bw)
3009 		bw = min_bw;
3010 	return (bw);
3011 }
3012 
3013 static inline uint64_t
3014 bbr_get_bw(struct tcp_bbr *bbr)
3015 {
3016 	uint64_t bw;
3017 
3018 	bw = __bbr_get_bw(bbr);
3019 	return (bw);
3020 }
3021 
3022 static inline void
3023 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3024 {
3025 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3026 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3027 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3028 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3029 }
3030 
3031 static inline void
3032 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3033 {
3034 	bbr->rc_lt_is_sampling = 0;
3035 	bbr->rc_lt_use_bw = 0;
3036 	bbr->r_ctl.rc_lt_bw = 0;
3037 	bbr_reset_lt_bw_interval(bbr, cts);
3038 }
3039 
3040 static inline void
3041 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3042 {
3043 	uint64_t diff;
3044 
3045 	/* Do we have a previous sample? */
3046 	if (bbr->r_ctl.rc_lt_bw) {
3047 		/* Get the diff in bytes per second */
3048 		if (bbr->r_ctl.rc_lt_bw > bw)
3049 			diff = bbr->r_ctl.rc_lt_bw - bw;
3050 		else
3051 			diff = bw - bbr->r_ctl.rc_lt_bw;
3052 		if ((diff <= bbr_lt_bw_diff) ||
3053 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3054 			/* Consider us policed */
3055 			uint32_t saved_bw;
3056 
3057 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3058 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3059 			bbr->rc_lt_use_bw = 1;
3060 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3061 			/*
3062 			 * Use pkt based epoch for measuring length of
3063 			 * policer up
3064 			 */
3065 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3066 			/*
3067 			 * reason 4 is we need to start consider being
3068 			 * policed
3069 			 */
3070 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3071 			return;
3072 		}
3073 	}
3074 	bbr->r_ctl.rc_lt_bw = bw;
3075 	bbr_reset_lt_bw_interval(bbr, cts);
3076 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3077 }
3078 
3079 static void
3080 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3081 {
3082 	uint32_t ran, deduct;
3083 
3084 	ran = arc4random_uniform(bbr_rand_ot);
3085 	if (ran) {
3086 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3087 		bbr->r_ctl.rc_level_state_extra -= deduct;
3088 	}
3089 }
3090 /*
3091  * Return randomly the starting state
3092  * to use in probebw.
3093  */
3094 static uint8_t
3095 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3096 {
3097 	uint32_t ran;
3098 	uint8_t ret_val;
3099 
3100 	/* Initialize the offset to 0 */
3101 	bbr->r_ctl.rc_exta_time_gd = 0;
3102 	bbr->rc_hit_state_1 = 0;
3103 	bbr->r_ctl.rc_level_state_extra = 0;
3104 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3105 	/*
3106 	 * The math works funny here :) the return value is used to set the
3107 	 * substate and then the state change is called which increments by
3108 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3109 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3110 	 * we return 1 - 7, so we dont return 0 and end up starting in
3111 	 * state 1 (DRAIN).
3112 	 */
3113 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3114 	/* Set an epoch */
3115 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3116 		bbr_set_epoch(bbr, cts, __LINE__);
3117 
3118 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3119 	return (ret_val);
3120 }
3121 
3122 static void
3123 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3124 {
3125 	uint32_t diff, d_time;
3126 	uint64_t del_time, bw, lost, delivered;
3127 
3128 	if (bbr->r_use_policer == 0)
3129 		return;
3130 	if (bbr->rc_lt_use_bw) {
3131 		/* We are using lt bw do we stop yet? */
3132 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3133 		if (diff > bbr_lt_bw_max_rtts) {
3134 			/* Reset it all */
3135 reset_all:
3136 			bbr_reset_lt_bw_sampling(bbr, cts);
3137 			if (bbr->rc_filled_pipe) {
3138 				bbr_set_epoch(bbr, cts, __LINE__);
3139 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3140 				bbr_substate_change(bbr, cts, __LINE__, 0);
3141 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3142 				bbr_log_type_statechange(bbr, cts, __LINE__);
3143 			} else {
3144 				/*
3145 				 * This should not happen really
3146 				 * unless we remove the startup/drain
3147 				 * restrictions above.
3148 				 */
3149 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3150 				bbr_set_epoch(bbr, cts, __LINE__);
3151 				bbr->r_ctl.rc_bbr_state_time = cts;
3152 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3153 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3154 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3155 				bbr_set_state_target(bbr, __LINE__);
3156 				bbr_log_type_statechange(bbr, cts, __LINE__);
3157 			}
3158 			/* reason 0 is to stop using lt-bw */
3159 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3160 			return;
3161 		}
3162 		if (bbr_lt_intvl_fp == 0) {
3163 			/* Not doing false-positive detection */
3164 			return;
3165 		}
3166 		/* False positive detection */
3167 		if (diff == bbr_lt_intvl_fp) {
3168 			/* At bbr_lt_intvl_fp we record the lost */
3169 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3170 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3171 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3172 			/* Now is our loss rate still high? */
3173 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3174 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3175 			if ((delivered == 0) ||
3176 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3177 				/* No still below our threshold */
3178 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3179 			} else {
3180 				/* Yikes its still high, it must be a false positive */
3181 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3182 				goto reset_all;
3183 			}
3184 		}
3185 		return;
3186 	}
3187 	/*
3188 	 * Wait for the first loss before sampling, to let the policer
3189 	 * exhaust its tokens and estimate the steady-state rate allowed by
3190 	 * the policer. Starting samples earlier includes bursts that
3191 	 * over-estimate the bw.
3192 	 */
3193 	if (bbr->rc_lt_is_sampling == 0) {
3194 		/* reason 1 is to begin doing the sampling  */
3195 		if (loss_detected == 0)
3196 			return;
3197 		bbr_reset_lt_bw_interval(bbr, cts);
3198 		bbr->rc_lt_is_sampling = 1;
3199 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3200 		return;
3201 	}
3202 	/* Now how long were we delivering long term last> */
3203 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3204 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3205 	else
3206 		d_time = 0;
3207 
3208 	/* To avoid underestimates, reset sampling if we run out of data. */
3209 	if (bbr->r_ctl.r_app_limited_until) {
3210 		/* Can not measure in app-limited state */
3211 		bbr_reset_lt_bw_sampling(bbr, cts);
3212 		/* reason 2 is to reset sampling due to app limits  */
3213 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3214 		return;
3215 	}
3216 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3217 	if (diff < bbr_lt_intvl_min_rtts) {
3218 		/*
3219 		 * need more samples (we don't
3220 		 * start on a round like linux so
3221 		 * we need 1 more).
3222 		 */
3223 		/* 6 is not_enough time or no-loss */
3224 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3225 		return;
3226 	}
3227 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3228 		/*
3229 		 * For now if we wait too long, reset all sampling. We need
3230 		 * to do some research here, its possible that we should
3231 		 * base this on how much loss as occurred.. something like
3232 		 * if its under 10% (or some thresh) reset all otherwise
3233 		 * don't.  Thats for phase II I guess.
3234 		 */
3235 		bbr_reset_lt_bw_sampling(bbr, cts);
3236  		/* reason 3 is to reset sampling due too long of sampling */
3237 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3238 		return;
3239 	}
3240 	/*
3241 	 * End sampling interval when a packet is lost, so we estimate the
3242 	 * policer tokens were exhausted. Stopping the sampling before the
3243 	 * tokens are exhausted under-estimates the policed rate.
3244 	 */
3245 	if (loss_detected == 0) {
3246 		/* 6 is not_enough time or no-loss */
3247 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3248 		return;
3249 	}
3250 	/* Calculate packets lost and delivered in sampling interval. */
3251 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3252 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3253 	if ((delivered == 0) ||
3254 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3255 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3256 		return;
3257 	}
3258 	if (d_time < 1000) {
3259 		/* Not enough time. wait */
3260 		/* 6 is not_enough time or no-loss */
3261 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3262 		return;
3263 	}
3264 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3265 		/* Too long */
3266 		bbr_reset_lt_bw_sampling(bbr, cts);
3267  		/* reason 3 is to reset sampling due too long of sampling */
3268 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3269 		return;
3270 	}
3271 	del_time = d_time;
3272 	bw = delivered;
3273 	bw *= (uint64_t)USECS_IN_SECOND;
3274 	bw /= del_time;
3275 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3276 }
3277 
3278 /*
3279  * Allocate a sendmap from our zone.
3280  */
3281 static struct bbr_sendmap *
3282 bbr_alloc(struct tcp_bbr *bbr)
3283 {
3284 	struct bbr_sendmap *rsm;
3285 
3286 	BBR_STAT_INC(bbr_to_alloc);
3287 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3288 	if (rsm) {
3289 		bbr->r_ctl.rc_num_maps_alloced++;
3290 		return (rsm);
3291 	}
3292 	if (bbr->r_ctl.rc_free_cnt) {
3293 		BBR_STAT_INC(bbr_to_alloc_emerg);
3294 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3295 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3296 		bbr->r_ctl.rc_free_cnt--;
3297 		return (rsm);
3298 	}
3299 	BBR_STAT_INC(bbr_to_alloc_failed);
3300 	return (NULL);
3301 }
3302 
3303 static struct bbr_sendmap *
3304 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3305 {
3306 	if ((V_tcp_map_entries_limit > 0) &&
3307 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3308 		BBR_STAT_INC(bbr_alloc_limited);
3309 		if (!bbr->alloc_limit_reported) {
3310 			bbr->alloc_limit_reported = 1;
3311 			BBR_STAT_INC(bbr_alloc_limited_conns);
3312 		}
3313 		return (NULL);
3314 	}
3315 	return (bbr_alloc(bbr));
3316 }
3317 
3318 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3319 static struct bbr_sendmap *
3320 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3321 {
3322 	struct bbr_sendmap *rsm;
3323 
3324 	if (limit_type) {
3325 		/* currently there is only one limit type */
3326 		if (V_tcp_map_split_limit > 0 &&
3327 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3328 			BBR_STAT_INC(bbr_split_limited);
3329 			if (!bbr->alloc_limit_reported) {
3330 				bbr->alloc_limit_reported = 1;
3331 				BBR_STAT_INC(bbr_alloc_limited_conns);
3332 			}
3333 			return (NULL);
3334 		}
3335 	}
3336 
3337 	/* allocate and mark in the limit type, if set */
3338 	rsm = bbr_alloc(bbr);
3339 	if (rsm != NULL && limit_type) {
3340 		rsm->r_limit_type = limit_type;
3341 		bbr->r_ctl.rc_num_split_allocs++;
3342 	}
3343 	return (rsm);
3344 }
3345 
3346 static void
3347 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3348 {
3349 	if (rsm->r_limit_type) {
3350 		/* currently there is only one limit type */
3351 		bbr->r_ctl.rc_num_split_allocs--;
3352 	}
3353 	if (rsm->r_is_smallmap)
3354 		bbr->r_ctl.rc_num_small_maps_alloced--;
3355 	if (bbr->r_ctl.rc_tlp_send == rsm)
3356 		bbr->r_ctl.rc_tlp_send = NULL;
3357 	if (bbr->r_ctl.rc_resend == rsm) {
3358 		bbr->r_ctl.rc_resend = NULL;
3359 	}
3360 	if (bbr->r_ctl.rc_next == rsm)
3361 		bbr->r_ctl.rc_next = NULL;
3362 	if (bbr->r_ctl.rc_sacklast == rsm)
3363 		bbr->r_ctl.rc_sacklast = NULL;
3364 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3365 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3366 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3367 		rsm->r_limit_type = 0;
3368 		bbr->r_ctl.rc_free_cnt++;
3369 		return;
3370 	}
3371 	bbr->r_ctl.rc_num_maps_alloced--;
3372 	uma_zfree(bbr_zone, rsm);
3373 }
3374 
3375 /*
3376  * Returns the BDP.
3377  */
3378 static uint64_t
3379 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3380 	/*
3381 	 * Calculate the bytes in flight needed given the bw (in bytes per
3382 	 * second) and the specifyed rtt in useconds. We need to put out the
3383 	 * returned value per RTT to match that rate. Gain will normally
3384 	 * raise it up from there.
3385 	 *
3386 	 * This should not overflow as long as the bandwidth is below 1
3387 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3388 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3389 	 */
3390 	uint64_t usec_per_sec;
3391 
3392 	usec_per_sec = USECS_IN_SECOND;
3393 	return ((rtt * bw) / usec_per_sec);
3394 }
3395 
3396 /*
3397  * Return the initial cwnd.
3398  */
3399 static uint32_t
3400 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3401 {
3402 	uint32_t i_cwnd;
3403 
3404 	if (bbr->rc_init_win) {
3405 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3406 	} else if (V_tcp_initcwnd_segments)
3407 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3408 		    max(2 * tp->t_maxseg, 14600));
3409 	else if (V_tcp_do_rfc3390)
3410 		i_cwnd = min(4 * tp->t_maxseg,
3411 		    max(2 * tp->t_maxseg, 4380));
3412 	else {
3413 		/* Per RFC5681 Section 3.1 */
3414 		if (tp->t_maxseg > 2190)
3415 			i_cwnd = 2 * tp->t_maxseg;
3416 		else if (tp->t_maxseg > 1095)
3417 			i_cwnd = 3 * tp->t_maxseg;
3418 		else
3419 			i_cwnd = 4 * tp->t_maxseg;
3420 	}
3421 	return (i_cwnd);
3422 }
3423 
3424 /*
3425  * Given a specified gain, return the target
3426  * cwnd based on that gain.
3427  */
3428 static uint32_t
3429 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3430 {
3431 	uint64_t bdp, rtt;
3432 	uint32_t cwnd;
3433 
3434 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3435 	    (bbr_get_full_bw(bbr) == 0)) {
3436 		/* No measurements yet */
3437 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3438 	}
3439 	/*
3440 	 * Get bytes per RTT needed (rttProp is normally in
3441 	 * bbr_cwndtarget_rtt_touse)
3442 	 */
3443 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3444 	/* Get the bdp from the two values */
3445 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3446 	/* Now apply the gain */
3447 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3448 
3449 	return (cwnd);
3450 }
3451 
3452 static uint32_t
3453 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3454 {
3455 	uint32_t cwnd, mss;
3456 
3457 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3458 	/* Get the base cwnd with gain rounded to a mss */
3459 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3460 	/*
3461 	 * Add in N (2 default since we do not have a
3462 	 * fq layer to trap packets in) quanta's per the I-D
3463 	 * section 4.2.3.2 quanta adjust.
3464 	 */
3465 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3466 	if (bbr->rc_use_google) {
3467 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3468 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3469 			/*
3470 			 * The linux implementation adds
3471 			 * an extra 2 x mss in gain cycle which
3472 			 * is documented no-where except in the code.
3473 			 * so we add more for Neal undocumented feature
3474 			 */
3475 			cwnd += 2 * mss;
3476 		}
3477  		if ((cwnd / mss) & 0x1) {
3478 			/* Round up for odd num mss */
3479 			cwnd += mss;
3480 		}
3481 	}
3482 	/* Are we below the min cwnd? */
3483 	if (cwnd < get_min_cwnd(bbr))
3484 		return (get_min_cwnd(bbr));
3485 	return (cwnd);
3486 }
3487 
3488 static uint16_t
3489 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3490 {
3491 	if (gain < 1)
3492 		gain = 1;
3493 	return (gain);
3494 }
3495 
3496 static uint32_t
3497 bbr_get_header_oh(struct tcp_bbr *bbr)
3498 {
3499 	int seg_oh;
3500 
3501 	seg_oh = 0;
3502 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3503 		/* Do we include TCP overhead? */
3504 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3505 	}
3506 	if (bbr->r_ctl.rc_inc_ip_oh) {
3507 		/* Do we include IP overhead? */
3508 #ifdef INET6
3509 		if (bbr->r_is_v6) {
3510 			seg_oh += sizeof(struct ip6_hdr);
3511 		} else
3512 #endif
3513 		{
3514 
3515 #ifdef INET
3516 			seg_oh += sizeof(struct ip);
3517 #endif
3518 		}
3519 	}
3520 	if (bbr->r_ctl.rc_inc_enet_oh) {
3521 		/* Do we include the ethernet overhead?  */
3522 		seg_oh += sizeof(struct ether_header);
3523 	}
3524 	return(seg_oh);
3525 }
3526 
3527 static uint32_t
3528 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3529 {
3530 	uint64_t divor, res, tim;
3531 
3532 	if (useconds_time == 0)
3533 		return (0);
3534 	gain = bbr_gain_adjust(bbr, gain);
3535 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3536 	tim = useconds_time;
3537 	res = (tim * bw * gain) / divor;
3538 	if (res == 0)
3539 		res = 1;
3540 	return ((uint32_t)res);
3541 }
3542 
3543 /*
3544  * Given a gain and a length return the delay in useconds that
3545  * should be used to evenly space out packets
3546  * on the connection (based on the gain factor).
3547  */
3548 static uint32_t
3549 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3550 {
3551 	uint64_t bw, lentim, res;
3552 	uint32_t usecs, srtt, over = 0;
3553 	uint32_t seg_oh, num_segs, maxseg;
3554 
3555 	if (len == 0)
3556 		return (0);
3557 
3558 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3559 	num_segs = (len + maxseg - 1) / maxseg;
3560 	if (bbr->rc_use_google == 0) {
3561 		seg_oh = bbr_get_header_oh(bbr);
3562 		len += (num_segs * seg_oh);
3563 	}
3564 	gain = bbr_gain_adjust(bbr, gain);
3565 	bw = bbr_get_bw(bbr);
3566 	if (bbr->rc_use_google) {
3567 		uint64_t cbw;
3568 
3569 		/*
3570 		 * Reduce the b/w by the google discount
3571 		 * factor 10 = 1%.
3572 		 */
3573 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3574 		cbw /= (uint64_t)1000;
3575 		/* We don't apply a discount if it results in 0 */
3576 		if (cbw > 0)
3577 			bw = cbw;
3578 	}
3579 	lentim = ((uint64_t)len *
3580 		  (uint64_t)USECS_IN_SECOND *
3581 		  (uint64_t)BBR_UNIT);
3582 	res = lentim / ((uint64_t)gain * bw);
3583 	if (res == 0)
3584 		res = 1;
3585 	usecs = (uint32_t)res;
3586 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3587 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3588 	    (bbr->rc_use_google == 0) &&
3589 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3590 		/*
3591 		 * We cannot let the delay be more than 1/2 the srtt time.
3592 		 * Otherwise we cannot pace out or send properly.
3593 		 */
3594 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3595 		BBR_STAT_INC(bbr_hpts_min_time);
3596 	}
3597 	if (!nolog)
3598 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3599 	return (usecs);
3600 }
3601 
3602 static void
3603 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3604 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3605 {
3606 	uint64_t bw;
3607 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3608 	int32_t meth;
3609 
3610 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3611 
3612 #ifdef STATS
3613 	if ((tp->t_flags & TF_GPUTINPROG) &&
3614 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3615 		/*
3616 		 * Strech acks and compressed acks will cause this to
3617 		 * oscillate but we are doing it the same way as the main
3618 		 * stack so it will be compariable (though possibly not
3619 		 * ideal).
3620 		 */
3621 		int32_t cgput;
3622 		int64_t gput, time_stamp;
3623 
3624 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3625 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3626 		cgput = gput / time_stamp;
3627 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3628 					 cgput);
3629 		if (tp->t_stats_gput_prev > 0)
3630 			stats_voi_update_abs_s32(tp->t_stats,
3631 						 VOI_TCP_GPUT_ND,
3632 						 ((gput - tp->t_stats_gput_prev) * 100) /
3633 						 tp->t_stats_gput_prev);
3634 		tp->t_flags &= ~TF_GPUTINPROG;
3635 		tp->t_stats_gput_prev = cgput;
3636 	}
3637 #endif
3638 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3639 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3640 		/* We don't change anything in probe-rtt */
3641 		return;
3642 	}
3643 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3644 	saved_bytes = bytes_this_ack;
3645 	bytes_this_ack += sack_changed;
3646 	if (bytes_this_ack > prev_acked) {
3647 		bytes_this_ack -= prev_acked;
3648 		/*
3649 		 * A byte ack'd gives us a full mss
3650 		 * to be like linux i.e. they count packets.
3651 		 */
3652 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3653 			bytes_this_ack = maxseg;
3654 	} else {
3655 		/* Unlikely */
3656 		bytes_this_ack = 0;
3657 	}
3658 	cwnd = tp->snd_cwnd;
3659 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3660 	if (bw)
3661 		target_cwnd = bbr_get_target_cwnd(bbr,
3662 						  bw,
3663 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3664 	else
3665 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3666 	if (IN_RECOVERY(tp->t_flags) &&
3667 	    (bbr->bbr_prev_in_rec == 0)) {
3668 		/*
3669 		 * We are entering recovery and
3670 		 * thus packet conservation.
3671 		 */
3672 		bbr->pkt_conservation = 1;
3673 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3674 		cwnd = ctf_flight_size(tp,
3675 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3676 			bytes_this_ack;
3677 	}
3678 	if (IN_RECOVERY(tp->t_flags)) {
3679 		uint32_t flight;
3680 
3681 		bbr->bbr_prev_in_rec = 1;
3682 		if (cwnd > losses) {
3683 			cwnd -= losses;
3684 			if (cwnd < maxseg)
3685 				cwnd = maxseg;
3686 		} else
3687 			cwnd = maxseg;
3688 		flight = ctf_flight_size(tp,
3689 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3690 		bbr_log_type_cwndupd(bbr, flight, 0,
3691 				     losses, 10, 0, 0, line);
3692 		if (bbr->pkt_conservation) {
3693 			uint32_t time_in;
3694 
3695 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3696 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3697 			else
3698 				time_in = 0;
3699 
3700 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3701 				/* Clear packet conservation after an rttProp */
3702 				bbr->pkt_conservation = 0;
3703 			} else {
3704 				if ((flight + bytes_this_ack) > cwnd)
3705 					cwnd = flight + bytes_this_ack;
3706 				if (cwnd < get_min_cwnd(bbr))
3707 					cwnd = get_min_cwnd(bbr);
3708 				tp->snd_cwnd = cwnd;
3709 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3710 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3711 				return;
3712 			}
3713 		}
3714 	} else
3715 		bbr->bbr_prev_in_rec = 0;
3716 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3717 		bbr->r_ctl.restrict_growth--;
3718 		if (bytes_this_ack > maxseg)
3719 			bytes_this_ack = maxseg;
3720 	}
3721 	if (bbr->rc_filled_pipe) {
3722 		/*
3723 		 * Here we have exited startup and filled the pipe. We will
3724 		 * thus allow the cwnd to shrink to the target. We hit here
3725 		 * mostly.
3726 		 */
3727 		uint32_t s_cwnd;
3728 
3729 		meth = 2;
3730 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3731 		if (s_cwnd > cwnd)
3732 			cwnd = s_cwnd;
3733 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3734 			cwnd = s_cwnd;
3735 	} else {
3736 		/*
3737 		 * Here we are still in startup, we increase cwnd by what
3738 		 * has been acked.
3739 		 */
3740 		if ((cwnd < target_cwnd) ||
3741 		    (bbr->rc_past_init_win == 0)) {
3742 			meth = 3;
3743 			cwnd += bytes_this_ack;
3744 		} else {
3745 			/*
3746 			 * Method 4 means we are at target so no gain in
3747 			 * startup and past the initial window.
3748 			 */
3749 			meth = 4;
3750 		}
3751 	}
3752 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3753 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3754 }
3755 
3756 static void
3757 tcp_bbr_partialack(struct tcpcb *tp)
3758 {
3759 	struct tcp_bbr *bbr;
3760 
3761 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3762 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3763 	if (ctf_flight_size(tp,
3764 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3765 	    tp->snd_cwnd) {
3766 		bbr->r_wanted_output = 1;
3767 	}
3768 }
3769 
3770 static void
3771 bbr_post_recovery(struct tcpcb *tp)
3772 {
3773 	struct tcp_bbr *bbr;
3774 	uint32_t  flight;
3775 
3776 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3777 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3778 	/*
3779 	 * Here we just exit recovery.
3780 	 */
3781 	EXIT_RECOVERY(tp->t_flags);
3782 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3783 	bbr->r_recovery_bw = 0;
3784 	tp->snd_recover = tp->snd_una;
3785 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3786 	bbr->pkt_conservation = 0;
3787 	if (bbr->rc_use_google == 0) {
3788 		/*
3789 		 * For non-google mode lets
3790 		 * go ahead and make sure we clear
3791 		 * the recovery state so if we
3792 		 * bounce back in to recovery we
3793 		 * will do PC.
3794 		 */
3795 		bbr->bbr_prev_in_rec = 0;
3796 	}
3797 	bbr_log_type_exit_rec(bbr);
3798 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3799 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3800 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3801 	} else {
3802 		/* For probe-rtt case lets fix up its saved_cwnd */
3803 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3804 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3805 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3806 		}
3807 	}
3808 	flight = ctf_flight_size(tp,
3809 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3810 	if ((bbr->rc_use_google == 0) &&
3811 	    bbr_do_red) {
3812 		uint64_t val, lr2use;
3813 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3814 		uint32_t *cwnd_p;
3815 
3816 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3817 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3818 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3819 			ratio = (uint32_t)val;
3820 		} else
3821 			ratio = 1000;
3822 
3823 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3824 				     bbr->r_ctl.recovery_lr, 21,
3825 				     ratio,
3826 				     bbr->r_ctl.rc_red_cwnd_pe,
3827 				     __LINE__);
3828 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3829 			goto done;
3830 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3831 		     bbr_prtt_slam_cwnd) ||
3832 		    (bbr_sub_drain_slam_cwnd &&
3833 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3834 		     bbr->rc_hit_state_1 &&
3835 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3836 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3837 		     bbr_slam_cwnd_in_main_drain)) {
3838 			/*
3839 			 * Here we must poke at the saved cwnd
3840 			 * as well as the cwnd.
3841 			 */
3842 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3843 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3844 		} else {
3845  			cwnd = tp->snd_cwnd;
3846 			cwnd_p = &tp->snd_cwnd;
3847 		}
3848 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3849 		/* Add the overall lr with the recovery lr */
3850 		if (bbr->r_ctl.rc_lost == 0)
3851 			lr2use = 0;
3852 		else if (bbr->r_ctl.rc_delivered == 0)
3853 			lr2use = 1000;
3854 		else {
3855 			lr2use = bbr->r_ctl.rc_lost * 1000;
3856 			lr2use /= bbr->r_ctl.rc_delivered;
3857 		}
3858 		lr2use += bbr->r_ctl.recovery_lr;
3859 		acks_inflight = (flight / (maxseg * 2));
3860 		if (bbr_red_scale) {
3861 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3862 			lr2use /= bbr_red_scale;
3863 			if ((bbr_red_growth_restrict) &&
3864 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3865 			    bbr->r_ctl.restrict_growth += acks_inflight;
3866 		}
3867 		if (lr2use) {
3868 			val = (uint64_t)cwnd * lr2use;
3869 			val /= 1000;
3870 			if (cwnd > val)
3871 				newcwnd = roundup((cwnd - val), maxseg);
3872 			else
3873 				newcwnd = maxseg;
3874 		} else {
3875 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3876 			val /= (uint64_t)bbr_red_div;
3877 			newcwnd = roundup((uint32_t)val, maxseg);
3878 		}
3879 		/* with standard delayed acks how many acks can I expect? */
3880 		if (bbr_drop_limit == 0) {
3881 			/*
3882 			 * Anticpate how much we will
3883 			 * raise the cwnd based on the acks.
3884 			 */
3885 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3886 				/* We do enforce the min (with the acks) */
3887 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3888 			}
3889 		} else {
3890 			/*
3891 			 * A strict drop limit of N is inplace
3892 			 */
3893 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3894 				newcwnd = bbr_drop_limit * maxseg;
3895 			}
3896 		}
3897 		/* For the next N acks do we restrict the growth */
3898 		*cwnd_p = newcwnd;
3899 		if (tp->snd_cwnd > newcwnd)
3900 			tp->snd_cwnd = newcwnd;
3901 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3902 				     (uint32_t)lr2use,
3903 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3904 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3905 	}
3906 done:
3907 	bbr->r_ctl.recovery_lr = 0;
3908 	if (flight <= tp->snd_cwnd) {
3909 		bbr->r_wanted_output = 1;
3910 	}
3911 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3912 }
3913 
3914 static void
3915 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3916 {
3917 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3918 	/* Limit the drop in b/w to 1/2 our current filter. */
3919 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3920 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3921 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3922 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3923 	tcp_bbr_tso_size_check(bbr, cts);
3924 }
3925 
3926 static void
3927 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3928 {
3929 	struct tcp_bbr *bbr;
3930 
3931 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3932 #ifdef STATS
3933 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3934 #endif
3935 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3936 	switch (type) {
3937 	case CC_NDUPACK:
3938 		if (!IN_RECOVERY(tp->t_flags)) {
3939 			tp->snd_recover = tp->snd_max;
3940 			/* Start a new epoch */
3941 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3942 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3943 				/*
3944 				 * Move forward the lt epoch
3945 				 * so it won't count the truncated
3946 				 * epoch.
3947 				 */
3948 				bbr->r_ctl.rc_lt_epoch++;
3949 			}
3950 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3951 				/*
3952 				 * Just like the policer detection code
3953 				 * if we are in startup we must push
3954 				 * forward the last startup epoch
3955 				 * to hide the truncated PE.
3956 				 */
3957 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3958 			}
3959 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3960 			ENTER_RECOVERY(tp->t_flags);
3961 			bbr->rc_tlp_rtx_out = 0;
3962 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3963 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3964 			if (tcp_in_hpts(bbr->rc_inp) &&
3965 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3966 				/*
3967 				 * When we enter recovery, we need to restart
3968 				 * any timers. This may mean we gain an agg
3969 				 * early, which will be made up for at the last
3970 				 * rxt out.
3971 				 */
3972 				bbr->rc_timer_first = 1;
3973 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3974 			}
3975 			/*
3976 			 * Calculate a new cwnd based on to the current
3977 			 * delivery rate with no gain. We get the bdp
3978 			 * without gaining it up like we normally would and
3979 			 * we use the last cur_del_rate.
3980 			 */
3981 			if ((bbr->rc_use_google == 0) &&
3982 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3983 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3984 				tp->snd_cwnd = ctf_flight_size(tp,
3985 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3986 					(tp->t_maxseg - bbr->rc_last_options);
3987 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3988 					/* We always gate to min cwnd */
3989 					tp->snd_cwnd = get_min_cwnd(bbr);
3990 				}
3991 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3992 			}
3993 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3994 		}
3995 		break;
3996 	case CC_RTO_ERR:
3997 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
3998 		/* RTO was unnecessary, so reset everything. */
3999 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
4000 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
4001 			tp->snd_cwnd = tp->snd_cwnd_prev;
4002 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
4003 			tp->snd_recover = tp->snd_recover_prev;
4004 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
4005 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
4006 		}
4007 		tp->t_badrxtwin = 0;
4008 		break;
4009 	}
4010 }
4011 
4012 /*
4013  * Indicate whether this ack should be delayed.  We can delay the ack if
4014  * following conditions are met:
4015  *	- There is no delayed ack timer in progress.
4016  *	- Our last ack wasn't a 0-sized window. We never want to delay
4017  *	  the ack that opens up a 0-sized window.
4018  *	- LRO wasn't used for this segment. We make sure by checking that the
4019  *	  segment size is not larger than the MSS.
4020  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4021  *	  connection.
4022  *	- The data being acked is less than a full segment (a stretch ack
4023  *        of more than a segment we should ack.
4024  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4025  */
4026 #define DELAY_ACK(tp, bbr, nsegs)				\
4027 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4028 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4029 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4030 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4031 
4032 /*
4033  * Return the lowest RSM in the map of
4034  * packets still in flight that is not acked.
4035  * This should normally find on the first one
4036  * since we remove packets from the send
4037  * map after they are marked ACKED.
4038  */
4039 static struct bbr_sendmap *
4040 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4041 {
4042 	struct bbr_sendmap *rsm;
4043 
4044 	/*
4045 	 * Walk the time-order transmitted list looking for an rsm that is
4046 	 * not acked. This will be the one that was sent the longest time
4047 	 * ago that is still outstanding.
4048 	 */
4049 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4050 		if (rsm->r_flags & BBR_ACKED) {
4051 			continue;
4052 		}
4053 		goto finish;
4054 	}
4055 finish:
4056 	return (rsm);
4057 }
4058 
4059 static struct bbr_sendmap *
4060 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4061 {
4062 	struct bbr_sendmap *prsm;
4063 
4064 	/*
4065 	 * Walk the sequence order list backward until we hit and arrive at
4066 	 * the highest seq not acked. In theory when this is called it
4067 	 * should be the last segment (which it was not).
4068 	 */
4069 	prsm = rsm;
4070 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4071 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4072 			continue;
4073 		}
4074 		return (prsm);
4075 	}
4076 	return (NULL);
4077 }
4078 
4079 /*
4080  * Returns to the caller the number of microseconds that
4081  * the packet can be outstanding before we think we
4082  * should have had an ack returned.
4083  */
4084 static uint32_t
4085 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4086 {
4087 	/*
4088 	 * lro is the flag we use to determine if we have seen reordering.
4089 	 * If it gets set we have seen reordering. The reorder logic either
4090 	 * works in one of two ways:
4091 	 *
4092 	 * If reorder-fade is configured, then we track the last time we saw
4093 	 * re-ordering occur. If we reach the point where enough time as
4094 	 * passed we no longer consider reordering has occuring.
4095 	 *
4096 	 * Or if reorder-face is 0, then once we see reordering we consider
4097 	 * the connection to alway be subject to reordering and just set lro
4098 	 * to 1.
4099 	 *
4100 	 * In the end if lro is non-zero we add the extra time for
4101 	 * reordering in.
4102 	 */
4103 	int32_t lro;
4104 	uint32_t thresh, t_rxtcur;
4105 
4106 	if (srtt == 0)
4107 		srtt = 1;
4108 	if (bbr->r_ctl.rc_reorder_ts) {
4109 		if (bbr->r_ctl.rc_reorder_fade) {
4110 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4111 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4112 				if (lro == 0) {
4113 					/*
4114 					 * No time as passed since the last
4115 					 * reorder, mark it as reordering.
4116 					 */
4117 					lro = 1;
4118 				}
4119 			} else {
4120 				/* Negative time? */
4121 				lro = 0;
4122 			}
4123 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4124 				/* Turn off reordering seen too */
4125 				bbr->r_ctl.rc_reorder_ts = 0;
4126 				lro = 0;
4127 			}
4128 		} else {
4129 			/* Reodering does not fade */
4130 			lro = 1;
4131 		}
4132 	} else {
4133 		lro = 0;
4134 	}
4135 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4136 	if (lro) {
4137 		/* It must be set, if not you get 1/4 rtt */
4138 		if (bbr->r_ctl.rc_reorder_shift)
4139 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4140 		else
4141 			thresh += (srtt >> 2);
4142 	} else {
4143 		thresh += 1000;
4144 	}
4145 	/* We don't let the rack timeout be above a RTO */
4146 	if ((bbr->rc_tp)->t_srtt == 0)
4147 		t_rxtcur = BBR_INITIAL_RTO;
4148 	else
4149 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4150 	if (thresh > t_rxtcur) {
4151 		thresh = t_rxtcur;
4152 	}
4153 	/* And we don't want it above the RTO max either */
4154 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4155 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4156 	}
4157 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4158 	return (thresh);
4159 }
4160 
4161 /*
4162  * Return to the caller the amount of time in mico-seconds
4163  * that should be used for the TLP timer from the last
4164  * send time of this packet.
4165  */
4166 static uint32_t
4167 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4168     struct bbr_sendmap *rsm, uint32_t srtt,
4169     uint32_t cts)
4170 {
4171 	uint32_t thresh, len, maxseg, t_rxtcur;
4172 	struct bbr_sendmap *prsm;
4173 
4174 	if (srtt == 0)
4175 		srtt = 1;
4176 	if (bbr->rc_tlp_threshold)
4177 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4178 	else
4179 		thresh = (srtt * 2);
4180 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4181 	/* Get the previous sent packet, if any  */
4182 	len = rsm->r_end - rsm->r_start;
4183 
4184 	/* 2.1 behavior */
4185 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4186 	if (prsm && (len <= maxseg)) {
4187 		/*
4188 		 * Two packets outstanding, thresh should be (2*srtt) +
4189 		 * possible inter-packet delay (if any).
4190 		 */
4191 		uint32_t inter_gap = 0;
4192 		int idx, nidx;
4193 
4194 		idx = rsm->r_rtr_cnt - 1;
4195 		nidx = prsm->r_rtr_cnt - 1;
4196 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4197 			/* Yes it was sent later (or at the same time) */
4198 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4199 		}
4200 		thresh += inter_gap;
4201 	} else if (len <= maxseg) {
4202 		/*
4203 		 * Possibly compensate for delayed-ack.
4204 		 */
4205 		uint32_t alt_thresh;
4206 
4207 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4208 		if (alt_thresh > thresh)
4209 			thresh = alt_thresh;
4210 	}
4211 	/* Not above the current  RTO */
4212 	if (tp->t_srtt == 0)
4213 		t_rxtcur = BBR_INITIAL_RTO;
4214 	else
4215 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4216 
4217 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4218 	/* Not above an RTO */
4219 	if (thresh > t_rxtcur) {
4220 		thresh = t_rxtcur;
4221 	}
4222 	/* Not above a RTO max */
4223 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4224 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4225 	}
4226 	/* And now apply the user TLP min */
4227 	if (thresh < bbr_tlp_min) {
4228 		thresh = bbr_tlp_min;
4229 	}
4230 	return (thresh);
4231 }
4232 
4233 /*
4234  * Return one of three RTTs to use (in microseconds).
4235  */
4236 static __inline uint32_t
4237 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4238 {
4239 	uint32_t f_rtt;
4240 	uint32_t srtt;
4241 
4242 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4243 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4244 		/* We have no rtt at all */
4245 		if (bbr->rc_tp->t_srtt == 0)
4246 			f_rtt = BBR_INITIAL_RTO;
4247 		else
4248 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4249 		/*
4250 		 * Since we don't know how good the rtt is apply a
4251 		 * delayed-ack min
4252 		 */
4253 		if (f_rtt < bbr_delayed_ack_time) {
4254 			f_rtt = bbr_delayed_ack_time;
4255 		}
4256 	}
4257 	/* Take the filter version or last measured pkt-rtt */
4258 	if (rtt_type == BBR_RTT_PROP) {
4259 		srtt = f_rtt;
4260 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4261 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4262 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4263 		} else {
4264 			/* No pkt rtt yet */
4265 			srtt = f_rtt;
4266 		}
4267 	} else if (rtt_type == BBR_RTT_RACK) {
4268 		srtt = bbr->r_ctl.rc_last_rtt;
4269 		/* We need to add in any internal delay for our timer */
4270 		if (bbr->rc_ack_was_delayed)
4271 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4272 	} else if (rtt_type == BBR_SRTT) {
4273 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4274 	} else {
4275 		/* TSNH */
4276 		srtt = f_rtt;
4277 #ifdef BBR_INVARIANTS
4278 		panic("Unknown rtt request type %d", rtt_type);
4279 #endif
4280 	}
4281 	return (srtt);
4282 }
4283 
4284 static int
4285 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4286 {
4287 	uint32_t thresh;
4288 
4289 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4290 				      cts, rsm);
4291 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4292 		/* It is lost (past time) */
4293 		return (1);
4294 	}
4295 	return (0);
4296 }
4297 
4298 /*
4299  * Return a sendmap if we need to retransmit something.
4300  */
4301 static struct bbr_sendmap *
4302 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4303 {
4304 	/*
4305 	 * Check to see that we don't need to fall into recovery. We will
4306 	 * need to do so if our oldest transmit is past the time we should
4307 	 * have had an ack.
4308 	 */
4309 
4310 	struct bbr_sendmap *rsm;
4311 	int32_t idx;
4312 
4313 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4314 		/* Nothing outstanding that we know of */
4315 		return (NULL);
4316 	}
4317 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4318 	if (rsm == NULL) {
4319 		/* Nothing in the transmit map */
4320 		return (NULL);
4321 	}
4322 	if (tp->t_flags & TF_SENTFIN) {
4323 		/* Fin restricted, don't find anything once a fin is sent */
4324 		return (NULL);
4325 	}
4326 	if (rsm->r_flags & BBR_ACKED) {
4327 		/*
4328 		 * Ok the first one is acked (this really should not happen
4329 		 * since we remove the from the tmap once they are acked)
4330 		 */
4331 		rsm = bbr_find_lowest_rsm(bbr);
4332 		if (rsm == NULL)
4333 			return (NULL);
4334 	}
4335 	idx = rsm->r_rtr_cnt - 1;
4336 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4337 		/* Send timestamp is the same or less? can't be ready */
4338 		return (NULL);
4339 	}
4340 	/* Get our RTT time */
4341 	if (bbr_is_lost(bbr, rsm, cts) &&
4342 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4343 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4344 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4345 			rsm->r_flags |= BBR_MARKED_LOST;
4346 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4347 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4348 		}
4349 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4350 #ifdef BBR_INVARIANTS
4351 		if ((rsm->r_end - rsm->r_start) == 0)
4352 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4353 #endif
4354 		return (rsm);
4355 	}
4356 	return (NULL);
4357 }
4358 
4359 /*
4360  * RACK Timer, here we simply do logging and house keeping.
4361  * the normal bbr_output_wtime() function will call the
4362  * appropriate thing to check if we need to do a RACK retransmit.
4363  * We return 1, saying don't proceed with bbr_output_wtime only
4364  * when all timers have been stopped (destroyed PCB?).
4365  */
4366 static int
4367 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4368 {
4369 	/*
4370 	 * This timer simply provides an internal trigger to send out data.
4371 	 * The check_recovery_mode call will see if there are needed
4372 	 * retransmissions, if so we will enter fast-recovery. The output
4373 	 * call may or may not do the same thing depending on sysctl
4374 	 * settings.
4375 	 */
4376 	uint32_t lost;
4377 
4378 	if (bbr->rc_all_timers_stopped) {
4379 		return (1);
4380 	}
4381 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4382 		/* Its not time yet */
4383 		return (0);
4384 	}
4385 	BBR_STAT_INC(bbr_to_tot);
4386 	lost = bbr->r_ctl.rc_lost;
4387 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4388 		bbr_set_state(tp, bbr, 0);
4389 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4390 	if (bbr->r_ctl.rc_resend == NULL) {
4391 		/* Lets do the check here */
4392 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4393 	}
4394 	if (bbr_policer_call_from_rack_to)
4395 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4396 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4397 	return (0);
4398 }
4399 
4400 static __inline void
4401 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4402 {
4403 	int idx;
4404 
4405 	nrsm->r_start = start;
4406 	nrsm->r_end = rsm->r_end;
4407 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4408 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4409 	nrsm->r_flags = rsm->r_flags;
4410 	/* We don't transfer forward the SYN flag */
4411 	nrsm->r_flags &= ~BBR_HAS_SYN;
4412 	/* We move forward the FIN flag, not that this should happen */
4413 	rsm->r_flags &= ~BBR_HAS_FIN;
4414 	nrsm->r_dupack = rsm->r_dupack;
4415 	nrsm->r_rtr_bytes = 0;
4416 	nrsm->r_is_gain = rsm->r_is_gain;
4417 	nrsm->r_is_drain = rsm->r_is_drain;
4418 	nrsm->r_delivered = rsm->r_delivered;
4419 	nrsm->r_ts_valid = rsm->r_ts_valid;
4420 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4421 	nrsm->r_del_time = rsm->r_del_time;
4422 	nrsm->r_app_limited = rsm->r_app_limited;
4423 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4424 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4425 	/* We split a piece the lower section looses any just_ret flag. */
4426 	nrsm->r_bbr_state = rsm->r_bbr_state;
4427 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4428 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4429 	}
4430 	rsm->r_end = nrsm->r_start;
4431 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4432 	idx /= 8;
4433 	/* Check if we got too small */
4434 	if ((rsm->r_is_smallmap == 0) &&
4435 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4436 		bbr->r_ctl.rc_num_small_maps_alloced++;
4437 		rsm->r_is_smallmap = 1;
4438 	}
4439 	/* Check the new one as well */
4440 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4441 		bbr->r_ctl.rc_num_small_maps_alloced++;
4442 		nrsm->r_is_smallmap = 1;
4443 	}
4444 }
4445 
4446 static int
4447 bbr_sack_mergable(struct bbr_sendmap *at,
4448 		  uint32_t start, uint32_t end)
4449 {
4450 	/*
4451 	 * Given a sack block defined by
4452 	 * start and end, and a current position
4453 	 * at. Return 1 if either side of at
4454 	 * would show that the block is mergable
4455 	 * to that side. A block to be mergable
4456 	 * must have overlap with the start/end
4457 	 * and be in the SACK'd state.
4458 	 */
4459 	struct bbr_sendmap *l_rsm;
4460 	struct bbr_sendmap *r_rsm;
4461 
4462 	/* first get the either side blocks */
4463 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4464 	r_rsm = TAILQ_NEXT(at, r_next);
4465 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4466 		/* Potentially mergeable */
4467 		if ((l_rsm->r_end == start) ||
4468 		    (SEQ_LT(start, l_rsm->r_end) &&
4469 		     SEQ_GT(end, l_rsm->r_end))) {
4470 			    /*
4471 			     * map blk   |------|
4472 			     * sack blk         |------|
4473 			     * <or>
4474 			     * map blk   |------|
4475 			     * sack blk      |------|
4476 			     */
4477 			    return (1);
4478 		    }
4479 	}
4480 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4481 		/* Potentially mergeable */
4482 		if ((r_rsm->r_start == end) ||
4483 		    (SEQ_LT(start, r_rsm->r_start) &&
4484 		     SEQ_GT(end, r_rsm->r_start))) {
4485 			/*
4486 			 * map blk          |---------|
4487 			 * sack blk    |----|
4488 			 * <or>
4489 			 * map blk          |---------|
4490 			 * sack blk    |-------|
4491 			 */
4492 			return (1);
4493 		}
4494 	}
4495 	return (0);
4496 }
4497 
4498 static struct bbr_sendmap *
4499 bbr_merge_rsm(struct tcp_bbr *bbr,
4500 	      struct bbr_sendmap *l_rsm,
4501 	      struct bbr_sendmap *r_rsm)
4502 {
4503 	/*
4504 	 * We are merging two ack'd RSM's,
4505 	 * the l_rsm is on the left (lower seq
4506 	 * values) and the r_rsm is on the right
4507 	 * (higher seq value). The simplest way
4508 	 * to merge these is to move the right
4509 	 * one into the left. I don't think there
4510 	 * is any reason we need to try to find
4511 	 * the oldest (or last oldest retransmitted).
4512 	 */
4513 	l_rsm->r_end = r_rsm->r_end;
4514 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4515 		l_rsm->r_dupack = r_rsm->r_dupack;
4516 	if (r_rsm->r_rtr_bytes)
4517 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4518 	if (r_rsm->r_in_tmap) {
4519 		/* This really should not happen */
4520 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4521 	}
4522 	if (r_rsm->r_app_limited)
4523 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4524 	/* Now the flags */
4525 	if (r_rsm->r_flags & BBR_HAS_FIN)
4526 		l_rsm->r_flags |= BBR_HAS_FIN;
4527 	if (r_rsm->r_flags & BBR_TLP)
4528 		l_rsm->r_flags |= BBR_TLP;
4529 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4530 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4531 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4532 		/* This really should not happen */
4533 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4534 	}
4535 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4536 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4537 		/* Transfer the split limit to the map we free */
4538 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4539 		l_rsm->r_limit_type = 0;
4540 	}
4541 	bbr_free(bbr, r_rsm);
4542 	return(l_rsm);
4543 }
4544 
4545 /*
4546  * TLP Timer, here we simply setup what segment we want to
4547  * have the TLP expire on, the normal bbr_output_wtime() will then
4548  * send it out.
4549  *
4550  * We return 1, saying don't proceed with bbr_output_wtime only
4551  * when all timers have been stopped (destroyed PCB?).
4552  */
4553 static int
4554 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4555 {
4556 	/*
4557 	 * Tail Loss Probe.
4558 	 */
4559 	struct bbr_sendmap *rsm = NULL;
4560 	struct socket *so;
4561 	uint32_t amm;
4562 	uint32_t out, avail;
4563 	uint32_t maxseg;
4564 	int collapsed_win = 0;
4565 
4566 	if (bbr->rc_all_timers_stopped) {
4567 		return (1);
4568 	}
4569 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4570 		/* Its not time yet */
4571 		return (0);
4572 	}
4573 	if (ctf_progress_timeout_check(tp, true)) {
4574 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4575 		return (-ETIMEDOUT);	/* tcp_drop() */
4576 	}
4577 	/* Did we somehow get into persists? */
4578 	if (bbr->rc_in_persist) {
4579 		return (0);
4580 	}
4581 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4582 		bbr_set_state(tp, bbr, 0);
4583 	BBR_STAT_INC(bbr_tlp_tot);
4584 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4585 	/*
4586 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4587 	 * need to figure out how to force a full MSS segment out.
4588 	 */
4589 	so = tptosocket(tp);
4590 	avail = sbavail(&so->so_snd);
4591 	out = ctf_outstanding(tp);
4592 	if (out > tp->snd_wnd) {
4593 		/* special case, we need a retransmission */
4594 		collapsed_win = 1;
4595 		goto need_retran;
4596 	}
4597 	if (avail > out) {
4598 		/* New data is available */
4599 		amm = avail - out;
4600 		if (amm > maxseg) {
4601 			amm = maxseg;
4602 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4603 			/* not enough to fill a MTU and no-delay is off */
4604 			goto need_retran;
4605 		}
4606 		/* Set the send-new override */
4607 		if ((out + amm) <= tp->snd_wnd) {
4608 			bbr->rc_tlp_new_data = 1;
4609 		} else {
4610 			goto need_retran;
4611 		}
4612 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4613 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4614 		bbr->r_ctl.rc_tlp_send = NULL;
4615 		/* cap any slots */
4616 		BBR_STAT_INC(bbr_tlp_newdata);
4617 		goto send;
4618 	}
4619 need_retran:
4620 	/*
4621 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4622 	 * optionally the first un-acked segment.
4623 	 */
4624 	if (collapsed_win == 0) {
4625 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4626 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4627 			rsm = bbr_find_high_nonack(bbr, rsm);
4628 		}
4629 		if (rsm == NULL) {
4630 			goto restore;
4631 		}
4632 	} else {
4633 		/*
4634 		 * We must find the last segment
4635 		 * that was acceptable by the client.
4636 		 */
4637 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4638 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4639 				/* Found one */
4640 				break;
4641 			}
4642 		}
4643 		if (rsm == NULL) {
4644 			/* None? if so send the first */
4645 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4646 			if (rsm == NULL)
4647 				goto restore;
4648 		}
4649 	}
4650 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4651 		/*
4652 		 * We need to split this the last segment in two.
4653 		 */
4654 		struct bbr_sendmap *nrsm;
4655 
4656 		nrsm = bbr_alloc_full_limit(bbr);
4657 		if (nrsm == NULL) {
4658 			/*
4659 			 * We can't get memory to split, we can either just
4660 			 * not split it. Or retransmit the whole piece, lets
4661 			 * do the large send (BTLP :-) ).
4662 			 */
4663 			goto go_for_it;
4664 		}
4665 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4666 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4667 		if (rsm->r_in_tmap) {
4668 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4669 			nrsm->r_in_tmap = 1;
4670 		}
4671 		rsm->r_flags &= (~BBR_HAS_FIN);
4672 		rsm = nrsm;
4673 	}
4674 go_for_it:
4675 	bbr->r_ctl.rc_tlp_send = rsm;
4676 	bbr->rc_tlp_rtx_out = 1;
4677 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4678 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4679 		tp->t_rxtshift++;
4680 	} else {
4681 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4682 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4683 	}
4684 send:
4685 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4686 		/*
4687 		 * Can't [re]/transmit a segment we have retransmitted the
4688 		 * max times. We need the retransmit timer to take over.
4689 		 */
4690 restore:
4691 		bbr->rc_tlp_new_data = 0;
4692 		bbr->r_ctl.rc_tlp_send = NULL;
4693 		if (rsm)
4694 			rsm->r_flags &= ~BBR_TLP;
4695 		BBR_STAT_INC(bbr_tlp_retran_fail);
4696 		return (0);
4697 	} else if (rsm) {
4698 		rsm->r_flags |= BBR_TLP;
4699 	}
4700 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4701 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4702 		/*
4703 		 * We have retransmitted to many times for TLP. Switch to
4704 		 * the regular RTO timer
4705 		 */
4706 		goto restore;
4707 	}
4708 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4709 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4710 	return (0);
4711 }
4712 
4713 /*
4714  * Delayed ack Timer, here we simply need to setup the
4715  * ACK_NOW flag and remove the DELACK flag. From there
4716  * the output routine will send the ack out.
4717  *
4718  * We only return 1, saying don't proceed, if all timers
4719  * are stopped (destroyed PCB?).
4720  */
4721 static int
4722 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4723 {
4724 	if (bbr->rc_all_timers_stopped) {
4725 		return (1);
4726 	}
4727 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4728 	tp->t_flags &= ~TF_DELACK;
4729 	tp->t_flags |= TF_ACKNOW;
4730 	KMOD_TCPSTAT_INC(tcps_delack);
4731 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4732 	return (0);
4733 }
4734 
4735 /*
4736  * Here we send a KEEP-ALIVE like probe to the
4737  * peer, we do not send data.
4738  *
4739  * We only return 1, saying don't proceed, if all timers
4740  * are stopped (destroyed PCB?).
4741  */
4742 static int
4743 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4744 {
4745 	struct tcptemp *t_template;
4746 	int32_t retval = 1;
4747 
4748 	if (bbr->rc_all_timers_stopped) {
4749 		return (1);
4750 	}
4751 	if (bbr->rc_in_persist == 0)
4752 		return (0);
4753 
4754 	/*
4755 	 * Persistence timer into zero window. Force a byte to be output, if
4756 	 * possible.
4757 	 */
4758 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4759 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4760 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4761 	/*
4762 	 * Have we exceeded the user specified progress time?
4763 	 */
4764 	if (ctf_progress_timeout_check(tp, true)) {
4765 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4766 		return (-ETIMEDOUT);	/* tcp_drop() */
4767 	}
4768 	/*
4769 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4770 	 * window is closed.  After a full backoff, drop the connection if
4771 	 * the idle time (no responses to probes) reaches the maximum
4772 	 * backoff that we would use if retransmitting.
4773 	 */
4774 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4775 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4776 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4777 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4778 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4779 		return (-ETIMEDOUT);	/* tcp_drop() */
4780 	}
4781 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4782 	    tp->snd_una == tp->snd_max) {
4783 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4784 		retval = 0;
4785 		goto out;
4786 	}
4787 	/*
4788 	 * If the user has closed the socket then drop a persisting
4789 	 * connection after a much reduced timeout.
4790 	 */
4791 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4792 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4793 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4794 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4795 		return (-ETIMEDOUT);	/* tcp_drop() */
4796 	}
4797 	t_template = tcpip_maketemplate(bbr->rc_inp);
4798 	if (t_template) {
4799 		tcp_respond(tp, t_template->tt_ipgen,
4800 			    &t_template->tt_t, (struct mbuf *)NULL,
4801 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4802 		/* This sends an ack */
4803 		if (tp->t_flags & TF_DELACK)
4804 			tp->t_flags &= ~TF_DELACK;
4805 		free(t_template, M_TEMP);
4806 	}
4807 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4808 		tp->t_rxtshift++;
4809 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4810 out:
4811 	return (retval);
4812 }
4813 
4814 /*
4815  * If a keepalive goes off, we had no other timers
4816  * happening. We always return 1 here since this
4817  * routine either drops the connection or sends
4818  * out a segment with respond.
4819  */
4820 static int
4821 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4822 {
4823 	struct tcptemp *t_template;
4824 	struct inpcb *inp = tptoinpcb(tp);
4825 
4826 	if (bbr->rc_all_timers_stopped) {
4827 		return (1);
4828 	}
4829 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4830 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4831 	/*
4832 	 * Keep-alive timer went off; send something or drop connection if
4833 	 * idle for too long.
4834 	 */
4835 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4836 	if (tp->t_state < TCPS_ESTABLISHED)
4837 		goto dropit;
4838 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4839 	    tp->t_state <= TCPS_CLOSING) {
4840 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4841 			goto dropit;
4842 		/*
4843 		 * Send a packet designed to force a response if the peer is
4844 		 * up and reachable: either an ACK if the connection is
4845 		 * still alive, or an RST if the peer has closed the
4846 		 * connection due to timeout or reboot. Using sequence
4847 		 * number tp->snd_una-1 causes the transmitted zero-length
4848 		 * segment to lie outside the receive window; by the
4849 		 * protocol spec, this requires the correspondent TCP to
4850 		 * respond.
4851 		 */
4852 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4853 		t_template = tcpip_maketemplate(inp);
4854 		if (t_template) {
4855 			tcp_respond(tp, t_template->tt_ipgen,
4856 			    &t_template->tt_t, (struct mbuf *)NULL,
4857 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4858 			free(t_template, M_TEMP);
4859 		}
4860 	}
4861 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4862 	return (1);
4863 dropit:
4864 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4865 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4866 	return (-ETIMEDOUT);	/* tcp_drop() */
4867 }
4868 
4869 /*
4870  * Retransmit helper function, clear up all the ack
4871  * flags and take care of important book keeping.
4872  */
4873 static void
4874 bbr_remxt_tmr(struct tcpcb *tp)
4875 {
4876 	/*
4877 	 * The retransmit timer went off, all sack'd blocks must be
4878 	 * un-acked.
4879 	 */
4880 	struct bbr_sendmap *rsm, *trsm = NULL;
4881 	struct tcp_bbr *bbr;
4882 	uint32_t cts, lost;
4883 
4884 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4885 	cts = tcp_get_usecs(&bbr->rc_tv);
4886 	lost = bbr->r_ctl.rc_lost;
4887 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4888 		bbr_set_state(tp, bbr, 0);
4889 
4890 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4891 		if (rsm->r_flags & BBR_ACKED) {
4892 			uint32_t old_flags;
4893 
4894 			rsm->r_dupack = 0;
4895 			if (rsm->r_in_tmap == 0) {
4896 				/* We must re-add it back to the tlist */
4897 				if (trsm == NULL) {
4898 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4899 				} else {
4900 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4901 				}
4902 				rsm->r_in_tmap = 1;
4903 			}
4904 			old_flags = rsm->r_flags;
4905 			rsm->r_flags |= BBR_RXT_CLEARED;
4906 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4907 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4908 		} else {
4909 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4910 			    (rsm->r_start == tp->snd_una)) {
4911 				/*
4912 				 * Special case for TCP FO. Where
4913 				 * we sent more data beyond the snd_max.
4914 				 * We don't mark that as lost and stop here.
4915 				 */
4916 				break;
4917 			}
4918 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4919 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4920 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4921 			}
4922 			if (bbr_marks_rxt_sack_passed) {
4923 				/*
4924 				 * With this option, we will rack out
4925 				 * in 1ms increments the rest of the packets.
4926 				 */
4927 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4928 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4929 			} else {
4930 				/*
4931 				 * With this option we only mark them lost
4932 				 * and remove all sack'd markings. We will run
4933 				 * another RXT or a TLP. This will cause
4934 				 * us to eventually send more based on what
4935 				 * ack's come in.
4936 				 */
4937 				rsm->r_flags |= BBR_MARKED_LOST;
4938 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4939 				rsm->r_flags &= ~BBR_SACK_PASSED;
4940 			}
4941 		}
4942 		trsm = rsm;
4943 	}
4944 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4945 	/* Clear the count (we just un-acked them) */
4946 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4947 	bbr->rc_tlp_new_data = 0;
4948 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4949 	/* zap the behindness on a rxt */
4950 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4951 	bbr->r_agg_early_set = 0;
4952 	bbr->r_ctl.rc_agg_early = 0;
4953 	bbr->rc_tlp_rtx_out = 0;
4954 	bbr->r_ctl.rc_sacked = 0;
4955 	bbr->r_ctl.rc_sacklast = NULL;
4956 	bbr->r_timer_override = 1;
4957 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4958 }
4959 
4960 /*
4961  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4962  * we will setup to retransmit the lowest seq number outstanding.
4963  */
4964 static int
4965 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4966 {
4967 	struct inpcb *inp = tptoinpcb(tp);
4968 	int32_t rexmt;
4969 	int32_t retval = 0;
4970 	bool isipv6;
4971 
4972 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4973 	if (bbr->rc_all_timers_stopped) {
4974 		return (1);
4975 	}
4976 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4977 	    (tp->snd_una == tp->snd_max)) {
4978 		/* Nothing outstanding .. nothing to do */
4979 		return (0);
4980 	}
4981 	/*
4982 	 * Retransmission timer went off.  Message has not been acked within
4983 	 * retransmit interval.  Back off to a longer retransmit interval
4984 	 * and retransmit one segment.
4985 	 */
4986 	if (ctf_progress_timeout_check(tp, true)) {
4987 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4988 		return (-ETIMEDOUT);	/* tcp_drop() */
4989 	}
4990 	bbr_remxt_tmr(tp);
4991 	if ((bbr->r_ctl.rc_resend == NULL) ||
4992 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4993 		/*
4994 		 * If the rwnd collapsed on
4995 		 * the one we are retransmitting
4996 		 * it does not count against the
4997 		 * rxt count.
4998 		 */
4999 		tp->t_rxtshift++;
5000 	}
5001 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5002 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
5003 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
5004 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
5005 		/* XXXGL: previously t_softerror was casted to uint16_t */
5006 		MPASS(tp->t_softerror >= 0);
5007 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
5008 		return (retval);	/* tcp_drop() */
5009 	}
5010 	if (tp->t_state == TCPS_SYN_SENT) {
5011 		/*
5012 		 * If the SYN was retransmitted, indicate CWND to be limited
5013 		 * to 1 segment in cc_conn_init().
5014 		 */
5015 		tp->snd_cwnd = 1;
5016 	} else if (tp->t_rxtshift == 1) {
5017 		/*
5018 		 * first retransmit; record ssthresh and cwnd so they can be
5019 		 * recovered if this turns out to be a "bad" retransmit. A
5020 		 * retransmit is considered "bad" if an ACK for this segment
5021 		 * is received within RTT/2 interval; the assumption here is
5022 		 * that the ACK was already in flight.  See "On Estimating
5023 		 * End-to-End Network Path Properties" by Allman and Paxson
5024 		 * for more details.
5025 		 */
5026 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5027 		if (!IN_RECOVERY(tp->t_flags)) {
5028 			tp->snd_cwnd_prev = tp->snd_cwnd;
5029 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5030 			tp->snd_recover_prev = tp->snd_recover;
5031 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5032 			tp->t_flags |= TF_PREVVALID;
5033 		} else {
5034 			tp->t_flags &= ~TF_PREVVALID;
5035 		}
5036 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5037 	} else {
5038 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5039 		tp->t_flags &= ~TF_PREVVALID;
5040 	}
5041 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5042 	if ((tp->t_state == TCPS_SYN_SENT) ||
5043 	    (tp->t_state == TCPS_SYN_RECEIVED))
5044 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5045 	else
5046 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5047 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5048 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5049 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5050 	/*
5051 	 * We enter the path for PLMTUD if connection is established or, if
5052 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5053 	 * amount of data we send is very small, we could send it in couple
5054 	 * of packets and process straight to FIN. In that case we won't
5055 	 * catch ESTABLISHED state.
5056 	 */
5057 #ifdef INET6
5058 	isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
5059 #else
5060 	isipv6 = false;
5061 #endif
5062 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5063 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5064 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5065 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5066 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5067 		/*
5068 		 * Idea here is that at each stage of mtu probe (usually,
5069 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5070 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5071 		 * should take care of that.
5072 		 */
5073 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5074 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5075 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5076 		    tp->t_rxtshift % 2 == 0)) {
5077 			/*
5078 			 * Enter Path MTU Black-hole Detection mechanism: -
5079 			 * Disable Path MTU Discovery (IP "DF" bit). -
5080 			 * Reduce MTU to lower value than what we negotiated
5081 			 * with peer.
5082 			 */
5083 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5084 				/*
5085 				 * Record that we may have found a black
5086 				 * hole.
5087 				 */
5088 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5089 				/* Keep track of previous MSS. */
5090 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5091 			}
5092 			/*
5093 			 * Reduce the MSS to blackhole value or to the
5094 			 * default in an attempt to retransmit.
5095 			 */
5096 #ifdef INET6
5097 			isipv6 = bbr->r_is_v6;
5098 			if (isipv6 &&
5099 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5100 				/* Use the sysctl tuneable blackhole MSS. */
5101 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5102 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5103 			} else if (isipv6) {
5104 				/* Use the default MSS. */
5105 				tp->t_maxseg = V_tcp_v6mssdflt;
5106 				/*
5107 				 * Disable Path MTU Discovery when we switch
5108 				 * to minmss.
5109 				 */
5110 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5111 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5112 			}
5113 #endif
5114 #if defined(INET6) && defined(INET)
5115 			else
5116 #endif
5117 #ifdef INET
5118 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5119 				/* Use the sysctl tuneable blackhole MSS. */
5120 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5121 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5122 			} else {
5123 				/* Use the default MSS. */
5124 				tp->t_maxseg = V_tcp_mssdflt;
5125 				/*
5126 				 * Disable Path MTU Discovery when we switch
5127 				 * to minmss.
5128 				 */
5129 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5130 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5131 			}
5132 #endif
5133 		} else {
5134 			/*
5135 			 * If further retransmissions are still unsuccessful
5136 			 * with a lowered MTU, maybe this isn't a blackhole
5137 			 * and we restore the previous MSS and blackhole
5138 			 * detection flags. The limit '6' is determined by
5139 			 * giving each probe stage (1448, 1188, 524) 2
5140 			 * chances to recover.
5141 			 */
5142 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5143 			    (tp->t_rxtshift >= 6)) {
5144 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5145 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5146 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5147 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5148 			}
5149 		}
5150 	}
5151 	/*
5152 	 * Disable RFC1323 and SACK if we haven't got any response to our
5153 	 * third SYN to work-around some broken terminal servers (most of
5154 	 * which have hopefully been retired) that have bad VJ header
5155 	 * compression code which trashes TCP segments containing
5156 	 * unknown-to-them TCP options.
5157 	 */
5158 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5159 	    (tp->t_rxtshift == 3))
5160 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5161 	/*
5162 	 * If we backed off this far, our srtt estimate is probably bogus.
5163 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5164 	 * move the current srtt into rttvar to keep the current retransmit
5165 	 * times until then.
5166 	 */
5167 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5168 #ifdef INET6
5169 		if (bbr->r_is_v6)
5170 			in6_losing(inp);
5171 		else
5172 #endif
5173 			in_losing(inp);
5174 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5175 		tp->t_srtt = 0;
5176 	}
5177 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5178 	tp->snd_recover = tp->snd_max;
5179 	tp->t_flags |= TF_ACKNOW;
5180 	tp->t_rtttime = 0;
5181 
5182 	return (retval);
5183 }
5184 
5185 static int
5186 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5187 {
5188 	int32_t ret = 0;
5189 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5190 
5191 	if (timers == 0) {
5192 		return (0);
5193 	}
5194 	if (tp->t_state == TCPS_LISTEN) {
5195 		/* no timers on listen sockets */
5196 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5197 			return (0);
5198 		return (1);
5199 	}
5200 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5201 		uint32_t left;
5202 
5203 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5204 			ret = -1;
5205 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5206 			return (0);
5207 		}
5208 		if (hpts_calling == 0) {
5209 			ret = -2;
5210 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5211 			return (0);
5212 		}
5213 		/*
5214 		 * Ok our timer went off early and we are not paced false
5215 		 * alarm, go back to sleep.
5216 		 */
5217 		left = bbr->r_ctl.rc_timer_exp - cts;
5218 		ret = -3;
5219 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5220 		tcp_hpts_insert(tptoinpcb(tp), HPTS_USEC_TO_SLOTS(left));
5221 		return (1);
5222 	}
5223 	bbr->rc_tmr_stopped = 0;
5224 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5225 	if (timers & PACE_TMR_DELACK) {
5226 		ret = bbr_timeout_delack(tp, bbr, cts);
5227 	} else if (timers & PACE_TMR_PERSIT) {
5228 		ret = bbr_timeout_persist(tp, bbr, cts);
5229 	} else if (timers & PACE_TMR_RACK) {
5230 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5231 		ret = bbr_timeout_rack(tp, bbr, cts);
5232 	} else if (timers & PACE_TMR_TLP) {
5233 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5234 		ret = bbr_timeout_tlp(tp, bbr, cts);
5235 	} else if (timers & PACE_TMR_RXT) {
5236 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5237 		ret = bbr_timeout_rxt(tp, bbr, cts);
5238 	} else if (timers & PACE_TMR_KEEP) {
5239 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5240 	}
5241 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5242 	return (ret);
5243 }
5244 
5245 static void
5246 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5247 {
5248 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5249 		uint8_t hpts_removed = 0;
5250 
5251 		if (tcp_in_hpts(bbr->rc_inp) &&
5252 		    (bbr->rc_timer_first == 1)) {
5253 			/*
5254 			 * If we are canceling timer's when we have the
5255 			 * timer ahead of the output being paced. We also
5256 			 * must remove ourselves from the hpts.
5257 			 */
5258 			hpts_removed = 1;
5259 			tcp_hpts_remove(bbr->rc_inp);
5260 			if (bbr->r_ctl.rc_last_delay_val) {
5261 				/* Update the last hptsi delay too */
5262 				uint32_t time_since_send;
5263 
5264 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5265 					time_since_send = cts - bbr->rc_pacer_started;
5266 				else
5267 					time_since_send = 0;
5268 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5269 					/* Cut down our slot time */
5270 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5271 				} else {
5272 					bbr->r_ctl.rc_last_delay_val = 0;
5273 				}
5274 				bbr->rc_pacer_started = cts;
5275 			}
5276 		}
5277 		bbr->rc_timer_first = 0;
5278 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5279 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5280 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5281 	}
5282 }
5283 
5284 static int
5285 bbr_stopall(struct tcpcb *tp)
5286 {
5287 	struct tcp_bbr *bbr;
5288 
5289 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5290 	bbr->rc_all_timers_stopped = 1;
5291 	return (0);
5292 }
5293 
5294 static uint32_t
5295 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5296 {
5297 	struct bbr_sendmap *rsm;
5298 
5299 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5300 	if ((rsm == NULL) || (u_rsm == rsm))
5301 		return (cts);
5302 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5303 }
5304 
5305 static void
5306 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5307      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5308 {
5309 	int32_t idx;
5310 
5311 	rsm->r_rtr_cnt++;
5312 	rsm->r_dupack = 0;
5313 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5314 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5315 		rsm->r_flags |= BBR_OVERMAX;
5316 	}
5317 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5318 		/* Take off the collapsed flag at rxt */
5319 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5320 	}
5321 	if (rsm->r_flags & BBR_MARKED_LOST) {
5322 		/* We have retransmitted, its no longer lost */
5323 		rsm->r_flags &= ~BBR_MARKED_LOST;
5324 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5325 	}
5326 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5327 		/*
5328 		 * We hit a RXT timer on it and
5329 		 * we cleared the "acked" flag.
5330 		 * We now have it going back into
5331 		 * flight, we can remove the cleared
5332 		 * flag and possibly do accounting on
5333 		 * this piece.
5334 		 */
5335 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5336 	}
5337 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5338 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5339 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5340 	}
5341 	idx = rsm->r_rtr_cnt - 1;
5342 	rsm->r_tim_lastsent[idx] = cts;
5343 	rsm->r_pacing_delay = pacing_time;
5344 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5345 	rsm->r_ts_valid = bbr->rc_ts_valid;
5346 	if (bbr->rc_ts_valid)
5347 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5348 	if (bbr->r_ctl.r_app_limited_until)
5349 		rsm->r_app_limited = 1;
5350 	else
5351 		rsm->r_app_limited = 0;
5352 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5353 		rsm->r_bbr_state = bbr_state_val(bbr);
5354 	else
5355 		rsm->r_bbr_state = 8;
5356 	if (rsm->r_flags & BBR_ACKED) {
5357 		/* Problably MTU discovery messing with us */
5358 		uint32_t old_flags;
5359 
5360 		old_flags = rsm->r_flags;
5361 		rsm->r_flags &= ~BBR_ACKED;
5362 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5363 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5364 		if (bbr->r_ctl.rc_sacked == 0)
5365 			bbr->r_ctl.rc_sacklast = NULL;
5366 	}
5367 	if (rsm->r_in_tmap) {
5368 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5369 	}
5370 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5371 	rsm->r_in_tmap = 1;
5372 	if (rsm->r_flags & BBR_SACK_PASSED) {
5373 		/* We have retransmitted due to the SACK pass */
5374 		rsm->r_flags &= ~BBR_SACK_PASSED;
5375 		rsm->r_flags |= BBR_WAS_SACKPASS;
5376 	}
5377 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5378 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5379 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5380 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5381 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5382 		rsm->r_is_gain = 1;
5383 		rsm->r_is_drain = 0;
5384 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5385 		rsm->r_is_drain = 1;
5386 		rsm->r_is_gain = 0;
5387 	} else {
5388 		rsm->r_is_drain = 0;
5389 		rsm->r_is_gain = 0;
5390 	}
5391 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5392 }
5393 
5394 /*
5395  * Returns 0, or the sequence where we stopped
5396  * updating. We also update the lenp to be the amount
5397  * of data left.
5398  */
5399 
5400 static uint32_t
5401 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5402     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5403 {
5404 	/*
5405 	 * We (re-)transmitted starting at rsm->r_start for some length
5406 	 * (possibly less than r_end.
5407 	 */
5408 	struct bbr_sendmap *nrsm;
5409 	uint32_t c_end;
5410 	int32_t len;
5411 
5412 	len = *lenp;
5413 	c_end = rsm->r_start + len;
5414 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5415 		/*
5416 		 * We retransmitted the whole piece or more than the whole
5417 		 * slopping into the next rsm.
5418 		 */
5419 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5420 		if (c_end == rsm->r_end) {
5421 			*lenp = 0;
5422 			return (0);
5423 		} else {
5424 			int32_t act_len;
5425 
5426 			/* Hangs over the end return whats left */
5427 			act_len = rsm->r_end - rsm->r_start;
5428 			*lenp = (len - act_len);
5429 			return (rsm->r_end);
5430 		}
5431 		/* We don't get out of this block. */
5432 	}
5433 	/*
5434 	 * Here we retransmitted less than the whole thing which means we
5435 	 * have to split this into what was transmitted and what was not.
5436 	 */
5437 	nrsm = bbr_alloc_full_limit(bbr);
5438 	if (nrsm == NULL) {
5439 		*lenp = 0;
5440 		return (0);
5441 	}
5442 	/*
5443 	 * So here we are going to take the original rsm and make it what we
5444 	 * retransmitted. nrsm will be the tail portion we did not
5445 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5446 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5447 	 * 1, 6 and the new piece will be 6, 11.
5448 	 */
5449 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5450 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5451 	nrsm->r_dupack = 0;
5452 	if (rsm->r_in_tmap) {
5453 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5454 		nrsm->r_in_tmap = 1;
5455 	}
5456 	rsm->r_flags &= (~BBR_HAS_FIN);
5457 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5458 	*lenp = 0;
5459 	return (0);
5460 }
5461 
5462 static uint64_t
5463 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5464 {
5465 	uint64_t bw;
5466 
5467 	bw = bbr_get_bw(bbr);
5468 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5469 	bw /= (uint64_t)BBR_UNIT;
5470 	return(bw);
5471 }
5472 
5473 static void
5474 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5475 		       uint64_t act_rate, uint64_t rate_wanted)
5476 {
5477 	/*
5478 	 * We could not get a full gains worth
5479 	 * of rate.
5480 	 */
5481 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5482 		/* we can't even get the real rate */
5483 		uint64_t red;
5484 
5485 		bbr->skip_gain = 1;
5486 		bbr->gain_is_limited = 0;
5487 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5488 		if (red)
5489 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5490 	} else {
5491 		/* We can use a lower gain */
5492 		bbr->skip_gain = 0;
5493 		bbr->gain_is_limited = 1;
5494 	}
5495 }
5496 
5497 static void
5498 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5499 {
5500 	const struct tcp_hwrate_limit_table *nrte;
5501 	int error, rate = -1;
5502 
5503 	if (bbr->r_ctl.crte == NULL)
5504 		return;
5505 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5506 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5507 		/* Lost our routes? */
5508 		/* Clear the way for a re-attempt */
5509 		bbr->bbr_attempt_hdwr_pace = 0;
5510 lost_rate:
5511 		bbr->gain_is_limited = 0;
5512 		bbr->skip_gain = 0;
5513 		bbr->bbr_hdrw_pacing = 0;
5514 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5515 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5516 		tcp_bbr_tso_size_check(bbr, cts);
5517 		return;
5518 	}
5519 	rate = bbr_get_hardware_rate(bbr);
5520 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5521 				   bbr->rc_tp,
5522 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5523 				   rate,
5524 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5525 				   &error, NULL);
5526 	if (nrte == NULL) {
5527 		goto lost_rate;
5528 	}
5529 	if (nrte != bbr->r_ctl.crte) {
5530 		bbr->r_ctl.crte = nrte;
5531 		if (error == 0)  {
5532 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5533 			if (bbr->r_ctl.crte->rate < rate) {
5534 				/* We have a problem */
5535 				bbr_setup_less_of_rate(bbr, cts,
5536 						       bbr->r_ctl.crte->rate, rate);
5537 			} else {
5538 				/* We are good */
5539 				bbr->gain_is_limited = 0;
5540 				bbr->skip_gain = 0;
5541 			}
5542 		} else {
5543 			/* A failure should release the tag */
5544 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5545 			bbr->gain_is_limited = 0;
5546 			bbr->skip_gain = 0;
5547 			bbr->bbr_hdrw_pacing = 0;
5548 		}
5549 		bbr_type_log_hdwr_pacing(bbr,
5550 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5551 					 rate,
5552 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5553 					 __LINE__,
5554 					 cts,
5555 					 error);
5556 	}
5557 }
5558 
5559 static void
5560 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5561 {
5562 	/*
5563 	 * If we have hardware pacing support
5564 	 * we need to factor that in for our
5565 	 * TSO size.
5566 	 */
5567 	const struct tcp_hwrate_limit_table *rlp;
5568 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5569 
5570 	if ((bbr->bbr_hdrw_pacing == 0) ||
5571 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5572 	    (bbr->r_ctl.crte == NULL))
5573 		return;
5574 	if (bbr->hw_pacing_set == 0) {
5575 		/* Not yet by the hdwr pacing count delay */
5576 		return;
5577 	}
5578 	if (bbr_hdwr_pace_adjust == 0) {
5579 		/* No adjustment */
5580 		return;
5581 	}
5582 	rlp = bbr->r_ctl.crte;
5583 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5584 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5585 	else
5586 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5587 	/*
5588 	 * So lets first get the
5589 	 * time we will take between
5590 	 * TSO sized sends currently without
5591 	 * hardware help.
5592 	 */
5593 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5594 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5595 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5596 	hdwr_delay *= rlp->time_between;
5597 	if (cur_delay > hdwr_delay)
5598 		delta = cur_delay - hdwr_delay;
5599 	else
5600 		delta = 0;
5601 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5602 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5603 			     1);
5604 	if (delta &&
5605 	    (delta < (max(rlp->time_between,
5606 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5607 		/*
5608 		 * Now lets divide by the pacing
5609 		 * time between each segment the
5610 		 * hardware sends rounding up and
5611 		 * derive a bytes from that. We multiply
5612 		 * that by bbr_hdwr_pace_adjust to get
5613 		 * more bang for our buck.
5614 		 *
5615 		 * The goal is to have the software pacer
5616 		 * waiting no more than an additional
5617 		 * pacing delay if we can (without the
5618 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5619 		 */
5620 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5621 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5622 		seg_sz *= bbr_hdwr_pace_adjust;
5623 		if (bbr_hdwr_pace_floor &&
5624 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5625 			/* Currently hardware paces
5626 			 * out rs_min_seg segments at a time.
5627 			 * We need to make sure we always send at least
5628 			 * a full burst of bbr_hdwr_pace_floor down.
5629 			 */
5630 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5631 		}
5632 		seg_sz *= maxseg;
5633 	} else if (delta == 0) {
5634 		/*
5635 		 * The highest pacing rate is
5636 		 * above our b/w gained. This means
5637 		 * we probably are going quite fast at
5638 		 * the hardware highest rate. Lets just multiply
5639 		 * the calculated TSO size by the
5640 		 * multiplier factor (its probably
5641 		 * 4 segments in the default config for
5642 		 * mlx).
5643 		 */
5644 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5645 		if (bbr_hdwr_pace_floor &&
5646 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5647 			/* Currently hardware paces
5648 			 * out rs_min_seg segments at a time.
5649 			 * We need to make sure we always send at least
5650 			 * a full burst of bbr_hdwr_pace_floor down.
5651 			 */
5652 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5653 		}
5654 	} else {
5655 		/*
5656 		 * The pacing time difference is so
5657 		 * big that the hardware will
5658 		 * pace out more rapidly then we
5659 		 * really want and then we
5660 		 * will have a long delay. Lets just keep
5661 		 * the same TSO size so its as if
5662 		 * we were not using hdwr pacing (we
5663 		 * just gain a bit of spacing from the
5664 		 * hardware if seg_sz > 1).
5665 		 */
5666 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5667 	}
5668 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5669 		new_tso = seg_sz;
5670 	else
5671 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5672 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5673 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5674 
5675 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5676 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5677 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5678 	}
5679 }
5680 
5681 static void
5682 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5683 {
5684 	uint64_t bw;
5685 	uint32_t old_tso = 0, new_tso;
5686 	uint32_t maxseg, bytes;
5687 	uint32_t tls_seg=0;
5688 	/*
5689 	 * Google/linux uses the following algorithm to determine
5690 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5691 	 *
5692 	 *  bytes = bw_in_bytes_per_second / 1000
5693 	 *  bytes = min(bytes, 64k)
5694 	 *  tso_segs = bytes / MSS
5695 	 *  if (bw < 1.2Mbs)
5696 	 *      min_tso_segs = 1
5697 	 *  else
5698 	 *	min_tso_segs = 2
5699 	 * tso_segs = max(tso_segs, min_tso_segs)
5700 	 *
5701 	 * * Note apply a device specific limit (we apply this in the
5702 	 *   tcp_m_copym).
5703 	 * Note that before the initial measurement is made google bursts out
5704 	 * a full iwnd just like new-reno/cubic.
5705 	 *
5706 	 * We do not use this algorithm. Instead we
5707 	 * use a two phased approach:
5708 	 *
5709 	 *  if ( bw <= per-tcb-cross-over)
5710 	 *     goal_tso =  calculate how much with this bw we
5711 	 *                 can send in goal-time seconds.
5712 	 *     if (goal_tso > mss)
5713 	 *         seg = goal_tso / mss
5714 	 *         tso = seg * mss
5715 	 *     else
5716 	 *         tso = mss
5717 	 *     if (tso > per-tcb-max)
5718 	 *         tso = per-tcb-max
5719 	 *  else if ( bw > 512Mbps)
5720 	 *     tso = max-tso (64k/mss)
5721 	 *  else
5722 	 *     goal_tso = bw / per-tcb-divsor
5723 	 *     seg = (goal_tso + mss-1)/mss
5724 	 *     tso = seg * mss
5725 	 *
5726 	 * if (tso < per-tcb-floor)
5727 	 *    tso = per-tcb-floor
5728 	 * if (tso > per-tcb-utter_max)
5729 	 *    tso = per-tcb-utter_max
5730 	 *
5731 	 * Note the default per-tcb-divisor is 1000 (same as google).
5732 	 * the goal cross over is 30Mbps however. To recreate googles
5733 	 * algorithm you need to set:
5734 	 *
5735 	 * cross-over = 23,168,000 bps
5736 	 * goal-time = 18000
5737 	 * per-tcb-max = 2
5738 	 * per-tcb-divisor = 1000
5739 	 * per-tcb-floor = 1
5740 	 *
5741 	 * This will get you "google bbr" behavior with respect to tso size.
5742 	 *
5743 	 * Note we do set anything TSO size until we are past the initial
5744 	 * window. Before that we gnerally use either a single MSS
5745 	 * or we use the full IW size (so we burst a IW at a time)
5746 	 */
5747 
5748 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5749 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5750 	} else {
5751 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5752 	}
5753 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5754 	if (bbr->rc_past_init_win == 0) {
5755 		/*
5756 		 * Not enough data has been acknowledged to make a
5757 		 * judgement. Set up the initial TSO based on if we
5758 		 * are sending a full IW at once or not.
5759 		 */
5760 		if (bbr->rc_use_google)
5761 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5762 		else if (bbr->bbr_init_win_cheat)
5763 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5764 		else
5765 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5766 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5767 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5768 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5769 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5770 		}
5771 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5772 			bbr_adjust_for_hw_pacing(bbr, cts);
5773 		return;
5774 	}
5775 	/**
5776 	 * Now lets set the TSO goal based on our delivery rate in
5777 	 * bytes per second. Note we only do this if
5778 	 * we have acked at least the initial cwnd worth of data.
5779 	 */
5780 	bw = bbr_get_bw(bbr);
5781 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5782 	     (bbr->rc_use_google == 0)) {
5783 		/* We clamp to one MSS in recovery */
5784 		new_tso = maxseg;
5785 	} else if (bbr->rc_use_google) {
5786 		int min_tso_segs;
5787 
5788 		/* Google considers the gain too */
5789 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5790 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5791 			bw /= BBR_UNIT;
5792 		}
5793 		bytes = bw / 1024;
5794 		if (bytes > (64 * 1024))
5795 			bytes = 64 * 1024;
5796 		new_tso = bytes / maxseg;
5797 		if (bw < ONE_POINT_TWO_MEG)
5798 			min_tso_segs = 1;
5799 		else
5800 			min_tso_segs = 2;
5801 		if (new_tso < min_tso_segs)
5802 			new_tso = min_tso_segs;
5803 		new_tso *= maxseg;
5804 	} else if (bbr->rc_no_pacing) {
5805 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5806 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5807 		/*
5808 		 * Calculate the worse case b/w TSO if we are inserting no
5809 		 * more than a delay_target number of TSO's.
5810 		 */
5811 		uint32_t tso_len, min_tso;
5812 
5813 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5814 		if (tso_len > maxseg) {
5815 			new_tso = tso_len / maxseg;
5816 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5817 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5818 			new_tso *= maxseg;
5819 		} else {
5820 			/*
5821 			 * less than a full sized frame yikes.. long rtt or
5822 			 * low bw?
5823 			 */
5824 			min_tso = bbr_minseg(bbr);
5825 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5826 				new_tso = rounddown(tso_len, min_tso);
5827 			else
5828 				new_tso = min_tso;
5829 		}
5830 	} else if (bw > FIVETWELVE_MBPS) {
5831 		/*
5832 		 * This guy is so fast b/w wise that we can TSO as large as
5833 		 * possible of segments that the NIC will allow.
5834 		 */
5835 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5836 	} else {
5837 		/*
5838 		 * This formula is based on attempting to send a segment or
5839 		 * more every bbr_hptsi_per_second. The default is 1000
5840 		 * which means you are targeting what you can send every 1ms
5841 		 * based on the peers bw.
5842 		 *
5843 		 * If the number drops to say 500, then you are looking more
5844 		 * at 2ms and you will raise how much we send in a single
5845 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5846 		 * trade off of course is you will send more at once and
5847 		 * thus tend to clump up the sends into larger "bursts"
5848 		 * building a queue.
5849 		 */
5850 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5851 		new_tso = roundup(bw, (uint64_t)maxseg);
5852 		/*
5853 		 * Gate the floor to match what our lower than 48Mbps
5854 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5855 		 * becomes the floor for this calculation.
5856 		 */
5857 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5858 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5859 	}
5860 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5861 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5862 	if (new_tso > PACE_MAX_IP_BYTES)
5863 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5864 	/* Enforce an utter maximum. */
5865 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5866 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5867 	}
5868 	if (old_tso != new_tso) {
5869 		/* Only log changes */
5870 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5871 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5872 	}
5873 	/* We have hardware pacing! */
5874 	bbr_adjust_for_hw_pacing(bbr, cts);
5875 }
5876 
5877 static void
5878 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5879     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5880     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5881     struct sockbuf *sb)
5882 {
5883 
5884 	struct bbr_sendmap *rsm, *nrsm;
5885 	register uint32_t snd_max, snd_una;
5886 	uint32_t pacing_time;
5887 	/*
5888 	 * Add to the RACK log of packets in flight or retransmitted. If
5889 	 * there is a TS option we will use the TS echoed, if not we will
5890 	 * grab a TS.
5891 	 *
5892 	 * Retransmissions will increment the count and move the ts to its
5893 	 * proper place. Note that if options do not include TS's then we
5894 	 * won't be able to effectively use the ACK for an RTT on a retran.
5895 	 *
5896 	 * Notes about r_start and r_end. Lets consider a send starting at
5897 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5898 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5899 	 * This means that r_end is actually the first sequence for the next
5900 	 * slot (11).
5901 	 *
5902 	 */
5903 	INP_WLOCK_ASSERT(tptoinpcb(tp));
5904 	if (err) {
5905 		/*
5906 		 * We don't log errors -- we could but snd_max does not
5907 		 * advance in this case either.
5908 		 */
5909 		return;
5910 	}
5911 	if (th_flags & TH_RST) {
5912 		/*
5913 		 * We don't log resets and we return immediately from
5914 		 * sending
5915 		 */
5916 		*abandon = 1;
5917 		return;
5918 	}
5919 	snd_una = tp->snd_una;
5920 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5921 		/*
5922 		 * The call to bbr_log_output is made before bumping
5923 		 * snd_max. This means we can record one extra byte on a SYN
5924 		 * or FIN if seq_out is adding more on and a FIN is present
5925 		 * (and we are not resending).
5926 		 */
5927 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5928 			len++;
5929 		if (th_flags & TH_FIN)
5930 			len++;
5931 	}
5932 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5933 		/* Are sending an old segment to induce an ack (keep-alive)? */
5934 		return;
5935 	}
5936 	if (SEQ_LT(seq_out, snd_una)) {
5937 		/* huh? should we panic? */
5938 		uint32_t end;
5939 
5940 		end = seq_out + len;
5941 		seq_out = snd_una;
5942 		len = end - seq_out;
5943 	}
5944 	snd_max = tp->snd_max;
5945 	if (len == 0) {
5946 		/* We don't log zero window probes */
5947 		return;
5948 	}
5949 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5950 	/* First question is it a retransmission? */
5951 	if (seq_out == snd_max) {
5952 again:
5953 		rsm = bbr_alloc(bbr);
5954 		if (rsm == NULL) {
5955 			return;
5956 		}
5957 		rsm->r_flags = 0;
5958 		if (th_flags & TH_SYN)
5959 			rsm->r_flags |= BBR_HAS_SYN;
5960 		if (th_flags & TH_FIN)
5961 			rsm->r_flags |= BBR_HAS_FIN;
5962 		rsm->r_tim_lastsent[0] = cts;
5963 		rsm->r_rtr_cnt = 1;
5964 		rsm->r_rtr_bytes = 0;
5965 		rsm->r_start = seq_out;
5966 		rsm->r_end = rsm->r_start + len;
5967 		rsm->r_dupack = 0;
5968 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5969 		rsm->r_pacing_delay = pacing_time;
5970 		rsm->r_ts_valid = bbr->rc_ts_valid;
5971 		if (bbr->rc_ts_valid)
5972 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5973 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
5974 		if (bbr->r_ctl.r_app_limited_until)
5975 			rsm->r_app_limited = 1;
5976 		else
5977 			rsm->r_app_limited = 0;
5978 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5979 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5980 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5981 		/*
5982 		 * Here we must also add in this rsm since snd_max
5983 		 * is updated after we return from a new send.
5984 		 */
5985 		rsm->r_flight_at_send += len;
5986 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
5987 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5988 		rsm->r_in_tmap = 1;
5989 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5990 			rsm->r_bbr_state = bbr_state_val(bbr);
5991 		else
5992 			rsm->r_bbr_state = 8;
5993 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5994 			rsm->r_is_gain = 1;
5995 			rsm->r_is_drain = 0;
5996 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5997 			rsm->r_is_drain = 1;
5998 			rsm->r_is_gain = 0;
5999 		} else {
6000 			rsm->r_is_drain = 0;
6001 			rsm->r_is_gain = 0;
6002 		}
6003 		return;
6004 	}
6005 	/*
6006 	 * If we reach here its a retransmission and we need to find it.
6007 	 */
6008 more:
6009 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6010 		rsm = hintrsm;
6011 		hintrsm = NULL;
6012 	} else if (bbr->r_ctl.rc_next) {
6013 		/* We have a hint from a previous run */
6014 		rsm = bbr->r_ctl.rc_next;
6015 	} else {
6016 		/* No hints sorry */
6017 		rsm = NULL;
6018 	}
6019 	if ((rsm) && (rsm->r_start == seq_out)) {
6020 		/*
6021 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6022 		 * likely case.
6023 		 */
6024 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6025 		if (len == 0) {
6026 			return;
6027 		} else {
6028 			goto more;
6029 		}
6030 	}
6031 	/* Ok it was not the last pointer go through it the hard way. */
6032 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6033 		if (rsm->r_start == seq_out) {
6034 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6035 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6036 			if (len == 0) {
6037 				return;
6038 			} else {
6039 				continue;
6040 			}
6041 		}
6042 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6043 			/* Transmitted within this piece */
6044 			/*
6045 			 * Ok we must split off the front and then let the
6046 			 * update do the rest
6047 			 */
6048 			nrsm = bbr_alloc_full_limit(bbr);
6049 			if (nrsm == NULL) {
6050 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6051 				return;
6052 			}
6053 			/*
6054 			 * copy rsm to nrsm and then trim the front of rsm
6055 			 * to not include this part.
6056 			 */
6057 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6058 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6059 			if (rsm->r_in_tmap) {
6060 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6061 				nrsm->r_in_tmap = 1;
6062 			}
6063 			rsm->r_flags &= (~BBR_HAS_FIN);
6064 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6065 			if (len == 0) {
6066 				return;
6067 			}
6068 		}
6069 	}
6070 	/*
6071 	 * Hmm not found in map did they retransmit both old and on into the
6072 	 * new?
6073 	 */
6074 	if (seq_out == tp->snd_max) {
6075 		goto again;
6076 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6077 #ifdef BBR_INVARIANTS
6078 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6079 		    seq_out, len, tp->snd_una, tp->snd_max);
6080 		printf("Starting Dump of all rack entries\n");
6081 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6082 			printf("rsm:%p start:%u end:%u\n",
6083 			    rsm, rsm->r_start, rsm->r_end);
6084 		}
6085 		printf("Dump complete\n");
6086 		panic("seq_out not found rack:%p tp:%p",
6087 		    bbr, tp);
6088 #endif
6089 	} else {
6090 #ifdef BBR_INVARIANTS
6091 		/*
6092 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6093 		 * flag)
6094 		 */
6095 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6096 		    seq_out, len, tp->snd_max, tp);
6097 #endif
6098 	}
6099 }
6100 
6101 static void
6102 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6103 {
6104 	/*
6105 	 * Collapse timeout back the cum-ack moved.
6106 	 */
6107 	tp->t_rxtshift = 0;
6108 	tp->t_softerror = 0;
6109 }
6110 
6111 static void
6112 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6113 {
6114 	bbr->rtt_valid = 1;
6115 	bbr->r_ctl.cur_rtt = rtt_usecs;
6116 	bbr->r_ctl.ts_in = tsin;
6117 	if (rsm_send_time)
6118 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6119 }
6120 
6121 static void
6122 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6123 {
6124 	/**
6125 	 * We have in our bbr control:
6126 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6127 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6128 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6129 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6130 	 *
6131 	 * Now we can calculate the time between the sends by doing:
6132 	 *
6133 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6134 	 *
6135 	 * And the peer's time between receiving them by doing:
6136 	 *
6137 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6138 	 *
6139 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6140 	 * We also may find that we can't use the timestamps if say we see
6141 	 * that the peer_delta indicates that though we may have taken 10ms to
6142 	 * pace out the data, it only saw 1ms between the two packets. This would
6143 	 * indicate that somewhere on the path is a batching entity that is giving
6144 	 * out time-slices of the actual b/w. This would mean we could not use
6145 	 * reliably the peers timestamps.
6146 	 *
6147 	 * We expect delta > peer_delta initially. Until we figure out the
6148 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6149 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6150 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6151 	 * put a 1 there. If the value is faster then ours, we will disable the
6152 	 * use of timestamps (though we could revist this later if we find it to be not
6153 	 * just an isolated one or two flows)).
6154 	 *
6155 	 * To detect the batching middle boxes we will come up with our compensation and
6156 	 * if with it in place, we find the peer is drastically off (by some margin) in
6157 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6158 	 *
6159 	 */
6160 	uint64_t delta, peer_delta, delta_up;
6161 
6162 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6163 	if (delta < bbr_min_usec_delta) {
6164 		/*
6165 		 * Have not seen a min amount of time
6166 		 * between our send times so we can
6167 		 * make a determination of the timestamp
6168 		 * yet.
6169 		 */
6170 		return;
6171 	}
6172 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6173 	if (peer_delta < bbr_min_peer_delta) {
6174 		/*
6175 		 * We may have enough in the form of
6176 		 * our delta but the peers number
6177 		 * has not changed that much. It could
6178 		 * be its clock ratio is such that
6179 		 * we need more data (10ms tick) or
6180 		 * there may be other compression scenarios
6181 		 * going on. In any event we need the
6182 		 * spread to be larger.
6183 		 */
6184 		return;
6185 	}
6186 	/* Ok lets first see which way our delta is going */
6187 	if (peer_delta > delta) {
6188 		/* Very unlikely, the peer without
6189 		 * compensation shows that it saw
6190 		 * the two sends arrive further apart
6191 		 * then we saw then in micro-seconds.
6192 		 */
6193 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6194 			/* well it looks like the peer is a micro-second clock. */
6195 			bbr->rc_ts_clock_set = 1;
6196 			bbr->r_ctl.bbr_peer_tsratio = 1;
6197 		} else {
6198 			bbr->rc_ts_cant_be_used = 1;
6199 			bbr->rc_ts_clock_set = 1;
6200 		}
6201 		return;
6202 	}
6203 	/* Ok we know that the peer_delta is smaller than our send distance */
6204 	bbr->rc_ts_clock_set = 1;
6205 	/* First question is it within the percentage that they are using usec time? */
6206 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6207 	if ((peer_delta + delta_up) >= delta) {
6208 		/* Its a usec clock */
6209 		bbr->r_ctl.bbr_peer_tsratio = 1;
6210 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6211 		return;
6212 	}
6213 	/* Ok if not usec, what about 10usec (though unlikely)? */
6214 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6215 	if (((peer_delta * 10) + delta_up) >= delta) {
6216 		bbr->r_ctl.bbr_peer_tsratio = 10;
6217 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6218 		return;
6219 	}
6220 	/* And what about 100usec (though again unlikely)? */
6221 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6222 	if (((peer_delta * 100) + delta_up) >= delta) {
6223 		bbr->r_ctl.bbr_peer_tsratio = 100;
6224 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6225 		return;
6226 	}
6227 	/* And how about 1 msec (the most likely one)? */
6228 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6229 	if (((peer_delta * 1000) + delta_up) >= delta) {
6230 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6231 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6232 		return;
6233 	}
6234 	/* Ok if not msec could it be 10 msec? */
6235 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6236 	if (((peer_delta * 10000) + delta_up) >= delta) {
6237 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6238 		return;
6239 	}
6240 	/* If we fall down here the clock tick so slowly we can't use it */
6241 	bbr->rc_ts_cant_be_used = 1;
6242 	bbr->r_ctl.bbr_peer_tsratio = 0;
6243 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6244 }
6245 
6246 /*
6247  * Collect new round-trip time estimate
6248  * and update averages and current timeout.
6249  */
6250 static void
6251 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6252 {
6253 	int32_t delta;
6254 	uint32_t rtt, tsin;
6255 	int32_t rtt_ticks;
6256 
6257 	if (bbr->rtt_valid == 0)
6258 		/* No valid sample */
6259 		return;
6260 
6261 	rtt = bbr->r_ctl.cur_rtt;
6262 	tsin = bbr->r_ctl.ts_in;
6263 	if (bbr->rc_prtt_set_ts) {
6264 		/*
6265 		 * We are to force feed the rttProp filter due
6266 		 * to an entry into PROBE_RTT. This assures
6267 		 * that the times are sync'd between when we
6268 		 * go into PROBE_RTT and the filter expiration.
6269 		 *
6270 		 * Google does not use a true filter, so they do
6271 		 * this implicitly since they only keep one value
6272 		 * and when they enter probe-rtt they update the
6273 		 * value to the newest rtt.
6274 		 */
6275 		uint32_t rtt_prop;
6276 
6277 		bbr->rc_prtt_set_ts = 0;
6278 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6279 		if (rtt > rtt_prop)
6280 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6281 		else
6282 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6283 	}
6284 	if (bbr->rc_ack_was_delayed)
6285 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6286 
6287 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6288 		bbr->r_ctl.rc_lowest_rtt = rtt;
6289 	bbr_log_rtt_sample(bbr, rtt, tsin);
6290 	if (bbr->r_init_rtt) {
6291 		/*
6292 		 * The initial rtt is not-trusted, nuke it and lets get
6293 		 * our first valid measurement in.
6294 		 */
6295 		bbr->r_init_rtt = 0;
6296 		tp->t_srtt = 0;
6297 	}
6298 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6299 		/*
6300 		 * So we have not yet figured out
6301 		 * what the peers TSTMP value is
6302 		 * in (most likely ms). We need a
6303 		 * series of cum-ack's to determine
6304 		 * this reliably.
6305 		 */
6306 		if (bbr->rc_ack_is_cumack) {
6307 			if (bbr->rc_ts_data_set) {
6308 				/* Lets attempt to determine the timestamp granularity. */
6309 				bbr_make_timestamp_determination(bbr);
6310 			} else {
6311 				bbr->rc_ts_data_set = 1;
6312 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6313 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6314 			}
6315 		} else {
6316 			/*
6317 			 * We have to have consecutive acks
6318 			 * reset any "filled" state to none.
6319 			 */
6320 			bbr->rc_ts_data_set = 0;
6321 		}
6322 	}
6323 	/* Round it up */
6324 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6325 	if (rtt_ticks == 0)
6326 		rtt_ticks = 1;
6327 	if (tp->t_srtt != 0) {
6328 		/*
6329 		 * srtt is stored as fixed point with 5 bits after the
6330 		 * binary point (i.e., scaled by 8).  The following magic is
6331 		 * equivalent to the smoothing algorithm in rfc793 with an
6332 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6333 		 * Adjust rtt to origin 0.
6334 		 */
6335 
6336 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6337 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6338 
6339 		tp->t_srtt += delta;
6340 		if (tp->t_srtt <= 0)
6341 			tp->t_srtt = 1;
6342 
6343 		/*
6344 		 * We accumulate a smoothed rtt variance (actually, a
6345 		 * smoothed mean difference), then set the retransmit timer
6346 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6347 		 * is stored as fixed point with 4 bits after the binary
6348 		 * point (scaled by 16).  The following is equivalent to
6349 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6350 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6351 		 * wired-in beta.
6352 		 */
6353 		if (delta < 0)
6354 			delta = -delta;
6355 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6356 		tp->t_rttvar += delta;
6357 		if (tp->t_rttvar <= 0)
6358 			tp->t_rttvar = 1;
6359 	} else {
6360 		/*
6361 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6362 		 * variance to half the rtt (so our first retransmit happens
6363 		 * at 3*rtt).
6364 		 */
6365 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6366 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6367 	}
6368 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6369 	tp->t_rttupdated++;
6370 #ifdef STATS
6371 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6372 #endif
6373 	/*
6374 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6375 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6376 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6377 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6378 	 * uncertainty in the firing of the timer.  The bias will give us
6379 	 * exactly the 1.5 tick we need.  But, because the bias is
6380 	 * statistical, we have to test that we don't drop below the minimum
6381 	 * feasible timer (which is 2 ticks).
6382 	 */
6383 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6384 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6385 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6386 
6387 	/*
6388 	 * We received an ack for a packet that wasn't retransmitted; it is
6389 	 * probably safe to discard any error indications we've received
6390 	 * recently.  This isn't quite right, but close enough for now (a
6391 	 * route might have failed after we sent a segment, and the return
6392 	 * path might not be symmetrical).
6393 	 */
6394 	tp->t_softerror = 0;
6395 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6396 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6397 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6398 }
6399 
6400 static void
6401 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6402 {
6403 	bbr->r_ctl.rc_rtt_shrinks = cts;
6404 	if (bbr_can_force_probertt &&
6405 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6406 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6407 		/*
6408 		 * We should enter probe-rtt its been too long
6409 		 * since we have been there.
6410 		 */
6411 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6412 	} else
6413 		bbr_check_probe_rtt_limits(bbr, cts);
6414 }
6415 
6416 static void
6417 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6418 {
6419 	uint64_t orig_bw;
6420 
6421 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6422 		/* We never apply a zero measurement */
6423 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6424 				    0, 0, 0, 0, 0, 0);
6425 		return;
6426 	}
6427 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6428 		bbr->r_ctl.r_measurement_count++;
6429 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6430 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6431 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6432 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6433 			    0, 0, 0, 0, 0, 0);
6434 	if (orig_bw &&
6435 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6436 		if (bbr->bbr_hdrw_pacing) {
6437 			/*
6438 			 * Apply a new rate to the hardware
6439 			 * possibly.
6440 			 */
6441 			bbr_update_hardware_pacing_rate(bbr, cts);
6442 		}
6443 		bbr_set_state_target(bbr, __LINE__);
6444 		tcp_bbr_tso_size_check(bbr, cts);
6445 		if (bbr->r_recovery_bw)  {
6446 			bbr_setup_red_bw(bbr, cts);
6447 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6448 		}
6449 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6450 		tcp_bbr_tso_size_check(bbr, cts);
6451 }
6452 
6453 static void
6454 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6455 {
6456 	if (bbr->rc_in_persist == 0) {
6457 		/* We log only when not in persist */
6458 		/* Translate to a Bytes Per Second */
6459 		uint64_t tim, bw, ts_diff, ts_bw;
6460 		uint32_t delivered;
6461 
6462 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6463 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6464 		else
6465 			tim = 1;
6466 		/*
6467 		 * Now that we have processed the tim (skipping the sample
6468 		 * or possibly updating the time, go ahead and
6469 		 * calculate the cdr.
6470 		 */
6471 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6472 		bw = (uint64_t)delivered;
6473 		bw *= (uint64_t)USECS_IN_SECOND;
6474 		bw /= tim;
6475 		if (bw == 0) {
6476 			/* We must have a calculatable amount */
6477 			return;
6478 		}
6479 		/*
6480 		 * If we are using this b/w shove it in now so we
6481 		 * can see in the trace viewer if it gets over-ridden.
6482 		 */
6483 		if (rsm->r_ts_valid &&
6484 		    bbr->rc_ts_valid &&
6485 		    bbr->rc_ts_clock_set &&
6486 		    (bbr->rc_ts_cant_be_used == 0) &&
6487 		    bbr->rc_use_ts_limit) {
6488 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6489 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6490 			if ((delivered == 0) ||
6491 			    (rtt < 1000)) {
6492 				/* Can't use the ts */
6493 				bbr_log_type_bbrupd(bbr, 61, cts,
6494 						    ts_diff,
6495 						    bbr->r_ctl.last_inbound_ts,
6496 						    rsm->r_del_ack_ts, 0,
6497 						    0, 0, 0, delivered);
6498 			} else {
6499 				ts_bw = (uint64_t)delivered;
6500 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6501 				ts_bw /= ts_diff;
6502 				bbr_log_type_bbrupd(bbr, 62, cts,
6503 						    (ts_bw >> 32),
6504 						    (ts_bw & 0xffffffff), 0, 0,
6505 						    0, 0, ts_diff, delivered);
6506 				if ((bbr->ts_can_raise) &&
6507 				    (ts_bw > bw)) {
6508 					bbr_log_type_bbrupd(bbr, 8, cts,
6509 							    delivered,
6510 							    ts_diff,
6511 							    (bw >> 32),
6512 							    (bw & 0x00000000ffffffff),
6513 							    0, 0, 0, 0);
6514 					bw = ts_bw;
6515 				} else if (ts_bw && (ts_bw < bw)) {
6516 					bbr_log_type_bbrupd(bbr, 7, cts,
6517 							    delivered,
6518 							    ts_diff,
6519 							    (bw >> 32),
6520 							    (bw & 0x00000000ffffffff),
6521 							    0, 0, 0, 0);
6522 					bw = ts_bw;
6523 				}
6524 			}
6525 		}
6526 		if (rsm->r_first_sent_time &&
6527 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6528 			uint64_t sbw, sti;
6529 			/*
6530 			 * We use what was in flight at the time of our
6531 			 * send  and the size of this send to figure
6532 			 * out what we have been sending at (amount).
6533 			 * For the time we take from the time of
6534 			 * the send of the first send outstanding
6535 			 * until this send plus this sends pacing
6536 			 * time. This gives us a good calculation
6537 			 * as to the rate we have been sending at.
6538 			 */
6539 
6540 			sbw = (uint64_t)(rsm->r_flight_at_send);
6541 			sbw *= (uint64_t)USECS_IN_SECOND;
6542 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6543 			sti += rsm->r_pacing_delay;
6544 			sbw /= sti;
6545 			if (sbw < bw) {
6546 				bbr_log_type_bbrupd(bbr, 6, cts,
6547 						    delivered,
6548 						    (uint32_t)sti,
6549 						    (bw >> 32),
6550 						    (uint32_t)bw,
6551 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6552 						    (uint32_t)sbw);
6553 				bw = sbw;
6554 			}
6555 		}
6556 		/* Use the google algorithm for b/w measurements */
6557 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6558 		if ((rsm->r_app_limited == 0) ||
6559 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6560 			tcp_bbr_commit_bw(bbr, cts);
6561 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6562 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6563 		}
6564 	}
6565 }
6566 
6567 static void
6568 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6569 {
6570 	if (bbr->rc_in_persist == 0) {
6571 		/* We log only when not in persist */
6572 		/* Translate to a Bytes Per Second */
6573 		uint64_t tim, bw;
6574 		uint32_t delivered;
6575 		int no_apply = 0;
6576 
6577 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6578 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6579 		else
6580 			tim = 1;
6581 		/*
6582 		 * Now that we have processed the tim (skipping the sample
6583 		 * or possibly updating the time, go ahead and
6584 		 * calculate the cdr.
6585 		 */
6586 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6587 		bw = (uint64_t)delivered;
6588 		bw *= (uint64_t)USECS_IN_SECOND;
6589 		bw /= tim;
6590 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6591 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6592 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6593 
6594 			no_apply = 1;
6595 		}
6596 		/*
6597 		 * If we are using this b/w shove it in now so we
6598 		 * can see in the trace viewer if it gets over-ridden.
6599 		 */
6600 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6601 		/* Gate by the sending rate */
6602 		if (rsm->r_first_sent_time &&
6603 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6604 			uint64_t sbw, sti;
6605 			/*
6606 			 * We use what was in flight at the time of our
6607 			 * send  and the size of this send to figure
6608 			 * out what we have been sending at (amount).
6609 			 * For the time we take from the time of
6610 			 * the send of the first send outstanding
6611 			 * until this send plus this sends pacing
6612 			 * time. This gives us a good calculation
6613 			 * as to the rate we have been sending at.
6614 			 */
6615 
6616 			sbw = (uint64_t)(rsm->r_flight_at_send);
6617 			sbw *= (uint64_t)USECS_IN_SECOND;
6618 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6619 			sti += rsm->r_pacing_delay;
6620 			sbw /= sti;
6621 			if (sbw < bw) {
6622 				bbr_log_type_bbrupd(bbr, 6, cts,
6623 						    delivered,
6624 						    (uint32_t)sti,
6625 						    (bw >> 32),
6626 						    (uint32_t)bw,
6627 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6628 						    (uint32_t)sbw);
6629 				bw = sbw;
6630 			}
6631 			if ((sti > tim) &&
6632 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6633 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6634 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6635 				no_apply = 1;
6636 			} else
6637 				no_apply = 0;
6638 		}
6639 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6640 		if ((no_apply == 0) &&
6641 		    ((rsm->r_app_limited == 0) ||
6642 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6643 			tcp_bbr_commit_bw(bbr, cts);
6644 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6645 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6646 		}
6647 	}
6648 }
6649 
6650 static void
6651 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6652     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6653 {
6654 	uint64_t old_rttprop;
6655 
6656 	/* Update our delivery time and amount */
6657 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6658 	bbr->r_ctl.rc_del_time = cts;
6659 	if (rtt == 0) {
6660 		/*
6661 		 * 0 means its a retransmit, for now we don't use these for
6662 		 * the rest of BBR.
6663 		 */
6664 		return;
6665 	}
6666 	if ((bbr->rc_use_google == 0) &&
6667 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6668 	    (match != BBR_RTT_BY_TIMESTAMP)){
6669 		/*
6670 		 * We get a lot of rtt updates, lets not pay attention to
6671 		 * any that are not an exact match. That way we don't have
6672 		 * to worry about timestamps and the whole nonsense of
6673 		 * unsure if its a retransmission etc (if we ever had the
6674 		 * timestamp fixed to always have the last thing sent this
6675 		 * would not be a issue).
6676 		 */
6677 		return;
6678 	}
6679 	if ((bbr_no_retran && bbr->rc_use_google) &&
6680 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6681 	    (match != BBR_RTT_BY_TIMESTAMP)){
6682 		/*
6683 		 * We only do measurements in google mode
6684 		 * with bbr_no_retran on for sure things.
6685 		 */
6686 		return;
6687 	}
6688 	/* Only update srtt if we know by exact match */
6689 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6690 	if (ack_type == BBR_CUM_ACKED)
6691 		bbr->rc_ack_is_cumack = 1;
6692 	else
6693 		bbr->rc_ack_is_cumack = 0;
6694 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6695 	/*
6696 	 * Note the following code differs to the original
6697 	 * BBR spec. It calls for <= not <. However after a
6698 	 * long discussion in email with Neal, he acknowledged
6699 	 * that it should be < than so that we will have flows
6700 	 * going into probe-rtt (we were seeing cases where that
6701 	 * did not happen and caused ugly things to occur). We
6702 	 * have added this agreed upon fix to our code base.
6703 	 */
6704 	if (rtt < old_rttprop) {
6705 		/* Update when we last saw a rtt drop */
6706 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6707 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6708 	}
6709 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6710 	    match, rsm->r_start, rsm->r_flags);
6711 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6712 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6713 		/*
6714 		 * The RTT-prop moved, reset the target (may be a
6715 		 * nop for some states).
6716 		 */
6717 		bbr_set_state_target(bbr, __LINE__);
6718 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6719 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6720 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6721 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6722 			/* It went up */
6723 			bbr_check_probe_rtt_limits(bbr, cts);
6724 	}
6725 	if ((bbr->rc_use_google == 0) &&
6726 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6727 		/*
6728 		 * We don't do b/w update with
6729 		 * these since they are not really
6730 		 * reliable.
6731 		 */
6732 		return;
6733 	}
6734 	if (bbr->r_ctl.r_app_limited_until &&
6735 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6736 		/* We are no longer app-limited */
6737 		bbr->r_ctl.r_app_limited_until = 0;
6738 	}
6739 	if (bbr->rc_use_google) {
6740 		bbr_google_measurement(bbr, rsm, rtt, cts);
6741 	} else {
6742 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6743 	}
6744 }
6745 
6746 /*
6747  * Convert a timestamp that the main stack
6748  * uses (milliseconds) into one that bbr uses
6749  * (microseconds). Return that converted timestamp.
6750  */
6751 static uint32_t
6752 bbr_ts_convert(uint32_t cts) {
6753 	uint32_t sec, msec;
6754 
6755 	sec = cts / MS_IN_USEC;
6756 	msec = cts - (MS_IN_USEC * sec);
6757 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6758 }
6759 
6760 /*
6761  * Return 0 if we did not update the RTT time, return
6762  * 1 if we did.
6763  */
6764 static int
6765 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6766     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6767 {
6768 	int32_t i;
6769 	uint32_t t, uts = 0;
6770 
6771 	if ((rsm->r_flags & BBR_ACKED) ||
6772 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6773 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6774 		/* Already done */
6775 		return (0);
6776 	}
6777 	if (rsm->r_rtt_not_allowed) {
6778 		/* Not allowed */
6779 		return (0);
6780 	}
6781 	if (rsm->r_rtr_cnt == 1) {
6782 		/*
6783 		 * Only one transmit. Hopefully the normal case.
6784 		 */
6785 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6786 			t = cts - rsm->r_tim_lastsent[0];
6787 		else
6788 			t = 1;
6789 		if ((int)t <= 0)
6790 			t = 1;
6791 		bbr->r_ctl.rc_last_rtt = t;
6792 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6793 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6794 		return (1);
6795 	}
6796 	/* Convert to usecs */
6797 	if ((bbr_can_use_ts_for_rtt == 1) &&
6798 	    (bbr->rc_use_google == 1) &&
6799 	    (ack_type == BBR_CUM_ACKED) &&
6800 	    (to->to_flags & TOF_TS) &&
6801 	    (to->to_tsecr != 0)) {
6802 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6803 		if (t < 1)
6804 			t = 1;
6805 		t *= MS_IN_USEC;
6806 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6807 				    BBR_RTT_BY_TIMESTAMP,
6808 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6809 				    ack_type, to);
6810 		return (1);
6811 	}
6812 	uts = bbr_ts_convert(to->to_tsecr);
6813 	if ((to->to_flags & TOF_TS) &&
6814 	    (to->to_tsecr != 0) &&
6815 	    (ack_type == BBR_CUM_ACKED) &&
6816 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6817 		/*
6818 		 * Now which timestamp does it match? In this block the ACK
6819 		 * may be coming from a previous transmission.
6820 		 */
6821 		uint32_t fudge;
6822 
6823 		fudge = BBR_TIMER_FUDGE;
6824 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6825 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6826 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6827 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6828 					t = cts - rsm->r_tim_lastsent[i];
6829 				else
6830 					t = 1;
6831 				if ((int)t <= 0)
6832 					t = 1;
6833 				bbr->r_ctl.rc_last_rtt = t;
6834 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6835 						    rsm->r_tim_lastsent[i], ack_type, to);
6836 				if ((i + 1) < rsm->r_rtr_cnt) {
6837 					/* Likely */
6838 					return (0);
6839 				} else if (rsm->r_flags & BBR_TLP) {
6840 					bbr->rc_tlp_rtx_out = 0;
6841 				}
6842 				return (1);
6843 			}
6844 		}
6845 		/* Fall through if we can't find a matching timestamp */
6846 	}
6847 	/*
6848 	 * Ok its a SACK block that we retransmitted. or a windows
6849 	 * machine without timestamps. We can tell nothing from the
6850 	 * time-stamp since its not there or the time the peer last
6851 	 * recieved a segment that moved forward its cum-ack point.
6852 	 *
6853 	 * Lets look at the last retransmit and see what we can tell
6854 	 * (with BBR for space we only keep 2 note we have to keep
6855 	 * at least 2 so the map can not be condensed more).
6856 	 */
6857 	i = rsm->r_rtr_cnt - 1;
6858 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6859 		t = cts - rsm->r_tim_lastsent[i];
6860 	else
6861 		goto not_sure;
6862 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6863 		/*
6864 		 * We retransmitted and the ack came back in less
6865 		 * than the smallest rtt we have observed in the
6866 		 * windowed rtt. We most likey did an improper
6867 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6868 		 * the rack-draft.
6869 		 *
6870 		 * Use the prior transmission to update all the
6871 		 * information as long as there is only one prior
6872 		 * transmission.
6873 		 */
6874 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6875 #ifdef BBR_INVARIANTS
6876 			if (rsm->r_rtr_cnt == 1)
6877 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6878 #endif
6879 			i = rsm->r_rtr_cnt - 2;
6880 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6881 				t = cts - rsm->r_tim_lastsent[i];
6882 			else
6883 				t = 1;
6884 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6885 					    rsm->r_tim_lastsent[i], ack_type, to);
6886 			return (0);
6887 		} else {
6888 			/*
6889 			 * Too many prior transmissions, just
6890 			 * updated BBR delivered
6891 			 */
6892 not_sure:
6893 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6894 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6895 		}
6896 	} else {
6897 		/*
6898 		 * We retransmitted it and the retransmit did the
6899 		 * job.
6900 		 */
6901 		if (rsm->r_flags & BBR_TLP)
6902 			bbr->rc_tlp_rtx_out = 0;
6903 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6904 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6905 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6906 		else
6907 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6908 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6909 		return (1);
6910 	}
6911 	return (0);
6912 }
6913 
6914 /*
6915  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6916  */
6917 static void
6918 bbr_log_sack_passed(struct tcpcb *tp,
6919     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6920 {
6921 	struct bbr_sendmap *nrsm;
6922 
6923 	nrsm = rsm;
6924 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6925 	    bbr_head, r_tnext) {
6926 		if (nrsm == rsm) {
6927 			/* Skip orginal segment he is acked */
6928 			continue;
6929 		}
6930 		if (nrsm->r_flags & BBR_ACKED) {
6931 			/* Skip ack'd segments */
6932 			continue;
6933 		}
6934 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6935 			/*
6936 			 * We found one that is already marked
6937 			 * passed, we have been here before and
6938 			 * so all others below this are marked.
6939 			 */
6940 			break;
6941 		}
6942 		BBR_STAT_INC(bbr_sack_passed);
6943 		nrsm->r_flags |= BBR_SACK_PASSED;
6944 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6945 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6946 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6947 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6948 			nrsm->r_flags |= BBR_MARKED_LOST;
6949 		}
6950 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6951 	}
6952 }
6953 
6954 /*
6955  * Returns the number of bytes that were
6956  * newly ack'd by sack blocks.
6957  */
6958 static uint32_t
6959 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6960     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6961 {
6962 	int32_t times = 0;
6963 	uint32_t start, end, changed = 0;
6964 	struct bbr_sendmap *rsm, *nrsm;
6965 	int32_t used_ref = 1;
6966 	uint8_t went_back = 0, went_fwd = 0;
6967 
6968 	start = sack->start;
6969 	end = sack->end;
6970 	rsm = *prsm;
6971 	if (rsm == NULL)
6972 		used_ref = 0;
6973 
6974 	/* Do we locate the block behind where we last were? */
6975 	if (rsm && SEQ_LT(start, rsm->r_start)) {
6976 		went_back = 1;
6977 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
6978 			if (SEQ_GEQ(start, rsm->r_start) &&
6979 			    SEQ_LT(start, rsm->r_end)) {
6980 				goto do_rest_ofb;
6981 			}
6982 		}
6983 	}
6984 start_at_beginning:
6985 	went_fwd = 1;
6986 	/*
6987 	 * Ok lets locate the block where this guy is fwd from rsm (if its
6988 	 * set)
6989 	 */
6990 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
6991 		if (SEQ_GEQ(start, rsm->r_start) &&
6992 		    SEQ_LT(start, rsm->r_end)) {
6993 			break;
6994 		}
6995 	}
6996 do_rest_ofb:
6997 	if (rsm == NULL) {
6998 		/*
6999 		 * This happens when we get duplicate sack blocks with the
7000 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7001 		 * will not change there location so we would just start at
7002 		 * the end of the first one and get lost.
7003 		 */
7004 		if (tp->t_flags & TF_SENTFIN) {
7005 			/*
7006 			 * Check to see if we have not logged the FIN that
7007 			 * went out.
7008 			 */
7009 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7010 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7011 				/*
7012 				 * Ok we did not get the FIN logged.
7013 				 */
7014 				nrsm->r_end++;
7015 				rsm = nrsm;
7016 				goto do_rest_ofb;
7017 			}
7018 		}
7019 		if (times == 1) {
7020 #ifdef BBR_INVARIANTS
7021 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7022 			    tp, bbr, sack, to, prsm);
7023 #else
7024 			goto out;
7025 #endif
7026 		}
7027 		times++;
7028 		BBR_STAT_INC(bbr_sack_proc_restart);
7029 		rsm = NULL;
7030 		goto start_at_beginning;
7031 	}
7032 	/* Ok we have an ACK for some piece of rsm */
7033 	if (rsm->r_start != start) {
7034 		/*
7035 		 * Need to split this in two pieces the before and after.
7036 		 */
7037 		if (bbr_sack_mergable(rsm, start, end))
7038 			nrsm = bbr_alloc_full_limit(bbr);
7039 		else
7040 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7041 		if (nrsm == NULL) {
7042 			/* We could not allocate ignore the sack */
7043 			struct sackblk blk;
7044 
7045 			blk.start = start;
7046 			blk.end = end;
7047 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7048 			goto out;
7049 		}
7050 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7051 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7052 		if (rsm->r_in_tmap) {
7053 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7054 			nrsm->r_in_tmap = 1;
7055 		}
7056 		rsm->r_flags &= (~BBR_HAS_FIN);
7057 		rsm = nrsm;
7058 	}
7059 	if (SEQ_GEQ(end, rsm->r_end)) {
7060 		/*
7061 		 * The end of this block is either beyond this guy or right
7062 		 * at this guy.
7063 		 */
7064 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7065 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7066 			changed += (rsm->r_end - rsm->r_start);
7067 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7068 			bbr_log_sack_passed(tp, bbr, rsm);
7069 			if (rsm->r_flags & BBR_MARKED_LOST) {
7070 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7071 			}
7072 			/* Is Reordering occuring? */
7073 			if (rsm->r_flags & BBR_SACK_PASSED) {
7074 				BBR_STAT_INC(bbr_reorder_seen);
7075 				bbr->r_ctl.rc_reorder_ts = cts;
7076 				if (rsm->r_flags & BBR_MARKED_LOST) {
7077 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7078 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7079 						/* LT sampling also needs adjustment */
7080 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7081 				}
7082 			}
7083 			rsm->r_flags |= BBR_ACKED;
7084 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7085 			if (rsm->r_in_tmap) {
7086 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7087 				rsm->r_in_tmap = 0;
7088 			}
7089 		}
7090 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7091 		if (end == rsm->r_end) {
7092 			/* This block only - done */
7093 			goto out;
7094 		}
7095 		/* There is more not coverend by this rsm move on */
7096 		start = rsm->r_end;
7097 		nrsm = TAILQ_NEXT(rsm, r_next);
7098 		rsm = nrsm;
7099 		times = 0;
7100 		goto do_rest_ofb;
7101 	}
7102 	if (rsm->r_flags & BBR_ACKED) {
7103 		/* Been here done that */
7104 		goto out;
7105 	}
7106 	/* Ok we need to split off this one at the tail */
7107 	if (bbr_sack_mergable(rsm, start, end))
7108 		nrsm = bbr_alloc_full_limit(bbr);
7109 	else
7110 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7111 	if (nrsm == NULL) {
7112 		/* failed XXXrrs what can we do but loose the sack info? */
7113 		struct sackblk blk;
7114 
7115 		blk.start = start;
7116 		blk.end = end;
7117 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7118 		goto out;
7119 	}
7120 	/* Clone it */
7121 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7122 	/* The sack block does not cover this guy fully */
7123 	rsm->r_flags &= (~BBR_HAS_FIN);
7124 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7125 	if (rsm->r_in_tmap) {
7126 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7127 		nrsm->r_in_tmap = 1;
7128 	}
7129 	nrsm->r_dupack = 0;
7130 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7131 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7132 	changed += (rsm->r_end - rsm->r_start);
7133 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7134 	bbr_log_sack_passed(tp, bbr, rsm);
7135 	/* Is Reordering occuring? */
7136 	if (rsm->r_flags & BBR_MARKED_LOST) {
7137 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7138 	}
7139 	if (rsm->r_flags & BBR_SACK_PASSED) {
7140 		BBR_STAT_INC(bbr_reorder_seen);
7141 		bbr->r_ctl.rc_reorder_ts = cts;
7142 		if (rsm->r_flags & BBR_MARKED_LOST) {
7143 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7144 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7145 				/* LT sampling also needs adjustment */
7146 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7147 		}
7148 	}
7149 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7150 	rsm->r_flags |= BBR_ACKED;
7151 	if (rsm->r_in_tmap) {
7152 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7153 		rsm->r_in_tmap = 0;
7154 	}
7155 out:
7156 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7157 		/*
7158 		 * Now can we merge this newly acked
7159 		 * block with either the previous or
7160 		 * next block?
7161 		 */
7162 		nrsm = TAILQ_NEXT(rsm, r_next);
7163 		if (nrsm &&
7164 		    (nrsm->r_flags & BBR_ACKED)) {
7165 			/* yep this and next can be merged */
7166 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7167 		}
7168 		/* Now what about the previous? */
7169 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7170 		if (nrsm &&
7171 		    (nrsm->r_flags & BBR_ACKED)) {
7172 			/* yep the previous and this can be merged */
7173 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7174 		}
7175 	}
7176 	if (used_ref == 0) {
7177 		BBR_STAT_INC(bbr_sack_proc_all);
7178 	} else {
7179 		BBR_STAT_INC(bbr_sack_proc_short);
7180 	}
7181 	if (went_fwd && went_back) {
7182 		BBR_STAT_INC(bbr_sack_search_both);
7183 	} else if (went_fwd) {
7184 		BBR_STAT_INC(bbr_sack_search_fwd);
7185 	} else if (went_back) {
7186 		BBR_STAT_INC(bbr_sack_search_back);
7187 	}
7188 	/* Save off where the next seq is */
7189 	if (rsm)
7190 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7191 	else
7192 		bbr->r_ctl.rc_sacklast = NULL;
7193 	*prsm = rsm;
7194 	return (changed);
7195 }
7196 
7197 static void inline
7198 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7199 {
7200 	struct bbr_sendmap *tmap;
7201 
7202 	BBR_STAT_INC(bbr_reneges_seen);
7203 	tmap = NULL;
7204 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7205 		/* Its no longer sacked, mark it so */
7206 		uint32_t oflags;
7207 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7208 #ifdef BBR_INVARIANTS
7209 		if (rsm->r_in_tmap) {
7210 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7211 			    bbr, rsm, rsm->r_flags);
7212 		}
7213 #endif
7214 		oflags = rsm->r_flags;
7215 		if (rsm->r_flags & BBR_MARKED_LOST) {
7216 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7217 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7218 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7219 				/* LT sampling also needs adjustment */
7220 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7221 		}
7222 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7223 		rsm->r_flags |= BBR_WAS_RENEGED;
7224 		rsm->r_flags |= BBR_RXT_CLEARED;
7225 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7226 		/* Rebuild it into our tmap */
7227 		if (tmap == NULL) {
7228 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7229 			tmap = rsm;
7230 		} else {
7231 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7232 			tmap = rsm;
7233 		}
7234 		tmap->r_in_tmap = 1;
7235 		/*
7236 		 * XXXrrs Delivered? Should we do anything here?
7237 		 *
7238 		 * Of course we don't on a rxt timeout so maybe its ok that
7239 		 * we don't?
7240 		 *
7241 		 * For now lets not.
7242 		 */
7243 		rsm = TAILQ_NEXT(rsm, r_next);
7244 	}
7245 	/*
7246 	 * Now lets possibly clear the sack filter so we start recognizing
7247 	 * sacks that cover this area.
7248 	 */
7249 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7250 }
7251 
7252 static void
7253 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7254 {
7255 	struct tcp_bbr *bbr;
7256 	struct bbr_sendmap *rsm;
7257 	uint32_t cts;
7258 
7259 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7260 	cts = bbr->r_ctl.rc_rcvtime;
7261 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7262 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7263 		if ((rsm->r_end - rsm->r_start) <= 1) {
7264 			/* Log out the SYN completely */
7265 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7266 			rsm->r_rtr_bytes = 0;
7267 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7268 			if (rsm->r_in_tmap) {
7269 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7270 				rsm->r_in_tmap = 0;
7271 			}
7272 			if (bbr->r_ctl.rc_next == rsm) {
7273 				/* scoot along the marker */
7274 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7275 			}
7276 			if (to != NULL)
7277 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7278 			bbr_free(bbr, rsm);
7279 		} else {
7280 			/* There is more (Fast open)? strip out SYN. */
7281 			rsm->r_flags &= ~BBR_HAS_SYN;
7282 			rsm->r_start++;
7283 		}
7284 	}
7285 }
7286 
7287 /*
7288  * Returns the number of bytes that were
7289  * acknowledged by SACK blocks.
7290  */
7291 
7292 static uint32_t
7293 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7294     uint32_t *prev_acked)
7295 {
7296 	uint32_t changed, last_seq, entered_recovery = 0;
7297 	struct tcp_bbr *bbr;
7298 	struct bbr_sendmap *rsm;
7299 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7300 	register uint32_t th_ack;
7301 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7302 	uint32_t cts, acked, ack_point, sack_changed = 0;
7303 	uint32_t p_maxseg, maxseg, p_acked = 0;
7304 
7305 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7306 	if (tcp_get_flags(th) & TH_RST) {
7307 		/* We don't log resets */
7308 		return (0);
7309 	}
7310 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7311 	cts = bbr->r_ctl.rc_rcvtime;
7312 
7313 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7314 	changed = 0;
7315 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7316 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7317 	th_ack = th->th_ack;
7318 	if (SEQ_GT(th_ack, tp->snd_una)) {
7319 		acked = th_ack - tp->snd_una;
7320 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7321 		bbr->rc_tp->t_acktime = ticks;
7322 	} else
7323 		acked = 0;
7324 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7325 		/* Only sent here for sack processing */
7326 		goto proc_sack;
7327 	}
7328 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7329 		changed = th_ack - rsm->r_start;
7330 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7331 		/*
7332 		 * For the SYN incoming case we will not have called
7333 		 * tcp_output for the sending of the SYN, so there will be
7334 		 * no map. All other cases should probably be a panic.
7335 		 */
7336 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7337 			/*
7338 			 * We have a timestamp that can be used to generate
7339 			 * an initial RTT.
7340 			 */
7341 			uint32_t ts, now, rtt;
7342 
7343 			ts = bbr_ts_convert(to->to_tsecr);
7344 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7345 			rtt = now - ts;
7346 			if (rtt < 1)
7347 				rtt = 1;
7348 			bbr_log_type_bbrrttprop(bbr, rtt,
7349 						tp->iss, 0, cts,
7350 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7351 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7352 			changed = 1;
7353 			bbr->r_wanted_output = 1;
7354 			goto out;
7355 		}
7356 		goto proc_sack;
7357 	} else if (rsm == NULL) {
7358 		goto out;
7359 	}
7360 	if (changed) {
7361 		/*
7362 		 * The ACK point is advancing to th_ack, we must drop off
7363 		 * the packets in the rack log and calculate any eligble
7364 		 * RTT's.
7365 		 */
7366 		bbr->r_wanted_output = 1;
7367 more:
7368 		if (rsm == NULL) {
7369 			if (tp->t_flags & TF_SENTFIN) {
7370 				/* if we send a FIN we will not hav a map */
7371 				goto proc_sack;
7372 			}
7373 #ifdef BBR_INVARIANTS
7374 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7375 			    tp,
7376 			    th, tp->t_state, bbr,
7377 			    tp->snd_una, tp->snd_max, changed);
7378 #endif
7379 			goto proc_sack;
7380 		}
7381 	}
7382 	if (SEQ_LT(th_ack, rsm->r_start)) {
7383 		/* Huh map is missing this */
7384 #ifdef BBR_INVARIANTS
7385 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7386 		    rsm->r_start,
7387 		    th_ack, tp->t_state,
7388 		    bbr->r_state, bbr);
7389 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7390 #endif
7391 		goto proc_sack;
7392 	} else if (th_ack == rsm->r_start) {
7393 		/* None here to ack */
7394 		goto proc_sack;
7395 	}
7396 	/*
7397 	 * Clear the dup ack counter, it will
7398 	 * either be freed or if there is some
7399 	 * remaining we need to start it at zero.
7400 	 */
7401 	rsm->r_dupack = 0;
7402 	/* Now do we consume the whole thing? */
7403 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7404 		/* Its all consumed. */
7405 		uint32_t left;
7406 
7407 		if (rsm->r_flags & BBR_ACKED) {
7408 			/*
7409 			 * It was acked on the scoreboard -- remove it from
7410 			 * total
7411 			 */
7412 			p_acked += (rsm->r_end - rsm->r_start);
7413 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7414 			if (bbr->r_ctl.rc_sacked == 0)
7415 				bbr->r_ctl.rc_sacklast = NULL;
7416 		} else {
7417 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7418 			if (rsm->r_flags & BBR_MARKED_LOST) {
7419 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7420 			}
7421 			if (rsm->r_flags & BBR_SACK_PASSED) {
7422 				/*
7423 				 * There are acked segments ACKED on the
7424 				 * scoreboard further up. We are seeing
7425 				 * reordering.
7426 				 */
7427 				BBR_STAT_INC(bbr_reorder_seen);
7428 				bbr->r_ctl.rc_reorder_ts = cts;
7429 				if (rsm->r_flags & BBR_MARKED_LOST) {
7430 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7431 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7432 						/* LT sampling also needs adjustment */
7433 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7434 				}
7435 			}
7436 			rsm->r_flags &= ~BBR_MARKED_LOST;
7437 		}
7438 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7439 		rsm->r_rtr_bytes = 0;
7440 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7441 		if (rsm->r_in_tmap) {
7442 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7443 			rsm->r_in_tmap = 0;
7444 		}
7445 		if (bbr->r_ctl.rc_next == rsm) {
7446 			/* scoot along the marker */
7447 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7448 		}
7449 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7450 		/* Adjust the packet counts */
7451 		left = th_ack - rsm->r_end;
7452 		/* Free back to zone */
7453 		bbr_free(bbr, rsm);
7454 		if (left) {
7455 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7456 			goto more;
7457 		}
7458 		goto proc_sack;
7459 	}
7460 	if (rsm->r_flags & BBR_ACKED) {
7461 		/*
7462 		 * It was acked on the scoreboard -- remove it from total
7463 		 * for the part being cum-acked.
7464 		 */
7465 		p_acked += (rsm->r_end - rsm->r_start);
7466 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7467 		if (bbr->r_ctl.rc_sacked == 0)
7468 			bbr->r_ctl.rc_sacklast = NULL;
7469 	} else {
7470 		/*
7471 		 * It was acked up to th_ack point for the first time
7472 		 */
7473 		struct bbr_sendmap lrsm;
7474 
7475 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7476 		lrsm.r_end = th_ack;
7477 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7478 	}
7479 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7480 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7481 		/*
7482 		 * It was marked lost and partly ack'd now
7483 		 * for the first time. We lower the rc_lost_bytes
7484 		 * and still leave it MARKED.
7485 		 */
7486 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7487 	}
7488 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7489 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7490 	rsm->r_rtr_bytes = 0;
7491 	/* adjust packet count */
7492 	rsm->r_start = th_ack;
7493 proc_sack:
7494 	/* Check for reneging */
7495 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7496 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7497 		/*
7498 		 * The peer has moved snd_una up to the edge of this send,
7499 		 * i.e. one that it had previously acked. The only way that
7500 		 * can be true if the peer threw away data (space issues)
7501 		 * that it had previously sacked (else it would have given
7502 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7503 		 * markings here.
7504 		 *
7505 		 * Note we have to look to make sure th_ack is our
7506 		 * rsm->r_start in case we get an old ack where th_ack is
7507 		 * behind snd_una.
7508 		 */
7509 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7510 	}
7511 	if ((to->to_flags & TOF_SACK) == 0) {
7512 		/* We are done nothing left to log */
7513 		goto out;
7514 	}
7515 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7516 	if (rsm) {
7517 		last_seq = rsm->r_end;
7518 	} else {
7519 		last_seq = tp->snd_max;
7520 	}
7521 	/* Sack block processing */
7522 	if (SEQ_GT(th_ack, tp->snd_una))
7523 		ack_point = th_ack;
7524 	else
7525 		ack_point = tp->snd_una;
7526 	for (i = 0; i < to->to_nsacks; i++) {
7527 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7528 		    &sack, sizeof(sack));
7529 		sack.start = ntohl(sack.start);
7530 		sack.end = ntohl(sack.end);
7531 		if (SEQ_GT(sack.end, sack.start) &&
7532 		    SEQ_GT(sack.start, ack_point) &&
7533 		    SEQ_LT(sack.start, tp->snd_max) &&
7534 		    SEQ_GT(sack.end, ack_point) &&
7535 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7536 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7537 			    (SEQ_LT(sack.end, last_seq)) &&
7538 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7539 				/*
7540 				 * Not the last piece and its smaller than
7541 				 * 1/8th of a p_maxseg. We ignore this.
7542 				 */
7543 				BBR_STAT_INC(bbr_runt_sacks);
7544 				continue;
7545 			}
7546 			sack_blocks[num_sack_blks] = sack;
7547 			num_sack_blks++;
7548 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7549 		    SEQ_LEQ(sack.end, th_ack)) {
7550 			/*
7551 			 * Its a D-SACK block.
7552 			 */
7553 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7554 		}
7555 	}
7556 	if (num_sack_blks == 0)
7557 		goto out;
7558 	/*
7559 	 * Sort the SACK blocks so we can update the rack scoreboard with
7560 	 * just one pass.
7561 	 */
7562 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7563 				  num_sack_blks, th->th_ack);
7564 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7565 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7566 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7567 	num_sack_blks = new_sb;
7568 	if (num_sack_blks < 2) {
7569 		goto do_sack_work;
7570 	}
7571 	/* Sort the sacks */
7572 	for (i = 0; i < num_sack_blks; i++) {
7573 		for (j = i + 1; j < num_sack_blks; j++) {
7574 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7575 				sack = sack_blocks[i];
7576 				sack_blocks[i] = sack_blocks[j];
7577 				sack_blocks[j] = sack;
7578 			}
7579 		}
7580 	}
7581 	/*
7582 	 * Now are any of the sack block ends the same (yes some
7583 	 * implememtations send these)?
7584 	 */
7585 again:
7586 	if (num_sack_blks > 1) {
7587 		for (i = 0; i < num_sack_blks; i++) {
7588 			for (j = i + 1; j < num_sack_blks; j++) {
7589 				if (sack_blocks[i].end == sack_blocks[j].end) {
7590 					/*
7591 					 * Ok these two have the same end we
7592 					 * want the smallest end and then
7593 					 * throw away the larger and start
7594 					 * again.
7595 					 */
7596 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7597 						/*
7598 						 * The second block covers
7599 						 * more area use that
7600 						 */
7601 						sack_blocks[i].start = sack_blocks[j].start;
7602 					}
7603 					/*
7604 					 * Now collapse out the dup-sack and
7605 					 * lower the count
7606 					 */
7607 					for (k = (j + 1); k < num_sack_blks; k++) {
7608 						sack_blocks[j].start = sack_blocks[k].start;
7609 						sack_blocks[j].end = sack_blocks[k].end;
7610 						j++;
7611 					}
7612 					num_sack_blks--;
7613 					goto again;
7614 				}
7615 			}
7616 		}
7617 	}
7618 do_sack_work:
7619 	rsm = bbr->r_ctl.rc_sacklast;
7620 	for (i = 0; i < num_sack_blks; i++) {
7621 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7622 		if (acked) {
7623 			bbr->r_wanted_output = 1;
7624 			changed += acked;
7625 			sack_changed += acked;
7626 		}
7627 	}
7628 out:
7629 	*prev_acked = p_acked;
7630 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7631 		/*
7632 		 * Ok we have a high probability that we need to go in to
7633 		 * recovery since we have data sack'd
7634 		 */
7635 		struct bbr_sendmap *rsm;
7636 
7637 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7638 		if (rsm) {
7639 			/* Enter recovery */
7640 			entered_recovery = 1;
7641 			bbr->r_wanted_output = 1;
7642 			/*
7643 			 * When we enter recovery we need to assure we send
7644 			 * one packet.
7645 			 */
7646 			if (bbr->r_ctl.rc_resend == NULL) {
7647 				bbr->r_ctl.rc_resend = rsm;
7648 			}
7649 		}
7650 	}
7651 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7652 		/*
7653 		 * See if we need to rack-retransmit anything if so set it
7654 		 * up as the thing to resend assuming something else is not
7655 		 * already in that position.
7656 		 */
7657 		if (bbr->r_ctl.rc_resend == NULL) {
7658 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7659 		}
7660 	}
7661 	/*
7662 	 * We return the amount that changed via sack, this is used by the
7663 	 * ack-received code to augment what was changed between th_ack <->
7664 	 * snd_una.
7665 	 */
7666 	return (sack_changed);
7667 }
7668 
7669 static void
7670 bbr_strike_dupack(struct tcp_bbr *bbr)
7671 {
7672 	struct bbr_sendmap *rsm;
7673 
7674 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7675 	if (rsm && (rsm->r_dupack < 0xff)) {
7676 		rsm->r_dupack++;
7677 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7678 			bbr->r_wanted_output = 1;
7679 	}
7680 }
7681 
7682 /*
7683  * Return value of 1, we do not need to call bbr_process_data().
7684  * return value of 0, bbr_process_data can be called.
7685  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7686  * its unlocked and probably unsafe to touch the TCB.
7687  */
7688 static int
7689 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7690     struct tcpcb *tp, struct tcpopt *to,
7691     uint32_t tiwin, int32_t tlen,
7692     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7693 {
7694 	int32_t ourfinisacked = 0;
7695 	int32_t acked_amount;
7696 	uint16_t nsegs;
7697 	int32_t acked;
7698 	uint32_t lost, sack_changed = 0;
7699 	struct mbuf *mfree;
7700 	struct tcp_bbr *bbr;
7701 	uint32_t prev_acked = 0;
7702 
7703 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7704 	lost = bbr->r_ctl.rc_lost;
7705 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7706 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7707 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7708 		bbr->r_wanted_output = 1;
7709 		return (1);
7710 	}
7711 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7712 		/* Process the ack */
7713 		if (bbr->rc_in_persist)
7714 			tp->t_rxtshift = 0;
7715 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7716 			bbr_strike_dupack(bbr);
7717 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7718 	}
7719 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7720 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7721 		/*
7722 		 * Old ack, behind the last one rcv'd or a duplicate ack
7723 		 * with SACK info.
7724 		 */
7725 		if (th->th_ack == tp->snd_una) {
7726 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7727 			if (bbr->r_state == TCPS_SYN_SENT) {
7728 				/*
7729 				 * Special case on where we sent SYN. When
7730 				 * the SYN-ACK is processed in syn_sent
7731 				 * state it bumps the snd_una. This causes
7732 				 * us to hit here even though we did ack 1
7733 				 * byte.
7734 				 *
7735 				 * Go through the nothing left case so we
7736 				 * send data.
7737 				 */
7738 				goto nothing_left;
7739 			}
7740 		}
7741 		return (0);
7742 	}
7743 	/*
7744 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7745 	 * something we sent.
7746 	 */
7747 	if (tp->t_flags & TF_NEEDSYN) {
7748 		/*
7749 		 * T/TCP: Connection was half-synchronized, and our SYN has
7750 		 * been ACK'd (so connection is now fully synchronized).  Go
7751 		 * to non-starred state, increment snd_una for ACK of SYN,
7752 		 * and check if we can do window scaling.
7753 		 */
7754 		tp->t_flags &= ~TF_NEEDSYN;
7755 		tp->snd_una++;
7756 		/* Do window scaling? */
7757 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7758 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7759 			tp->rcv_scale = tp->request_r_scale;
7760 			/* Send window already scaled. */
7761 		}
7762 	}
7763 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7764 
7765 	acked = BYTES_THIS_ACK(tp, th);
7766 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7767 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7768 
7769 	/*
7770 	 * If we just performed our first retransmit, and the ACK arrives
7771 	 * within our recovery window, then it was a mistake to do the
7772 	 * retransmit in the first place.  Recover our original cwnd and
7773 	 * ssthresh, and proceed to transmit where we left off.
7774 	 */
7775 	if (tp->t_flags & TF_PREVVALID) {
7776 		tp->t_flags &= ~TF_PREVVALID;
7777 		if (tp->t_rxtshift == 1 &&
7778 		    (int)(ticks - tp->t_badrxtwin) < 0)
7779 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7780 	}
7781 	SOCKBUF_LOCK(&so->so_snd);
7782 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7783 	tp->snd_wnd -= acked_amount;
7784 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7785 	/* NB: sowwakeup_locked() does an implicit unlock. */
7786 	sowwakeup_locked(so);
7787 	m_freem(mfree);
7788 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7789 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7790 	}
7791 	tp->snd_una = th->th_ack;
7792 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7793 	if (IN_RECOVERY(tp->t_flags)) {
7794 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7795 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7796 			tcp_bbr_partialack(tp);
7797 		} else {
7798 			bbr_post_recovery(tp);
7799 		}
7800 	}
7801 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7802 		tp->snd_recover = tp->snd_una;
7803 	}
7804 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7805 		tp->snd_nxt = tp->snd_max;
7806 	}
7807 	if (tp->snd_una == tp->snd_max) {
7808 		/* Nothing left outstanding */
7809 nothing_left:
7810 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7811 		if (sbavail(&so->so_snd) == 0)
7812 			bbr->rc_tp->t_acktime = 0;
7813 		if ((sbused(&so->so_snd) == 0) &&
7814 		    (tp->t_flags & TF_SENTFIN)) {
7815 			ourfinisacked = 1;
7816 		}
7817 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7818 		if (bbr->rc_in_persist == 0) {
7819 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7820 		}
7821 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7822 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7823 		/*
7824 		 * We invalidate the last ack here since we
7825 		 * don't want to transfer forward the time
7826 		 * for our sum's calculations.
7827 		 */
7828 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7829 		    (sbavail(&so->so_snd) == 0) &&
7830 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7831 			/*
7832 			 * The socket was gone and the peer sent data, time
7833 			 * to reset him.
7834 			 */
7835 			*ret_val = 1;
7836 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7837 			/* tcp_close will kill the inp pre-log the Reset */
7838 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7839 			tp = tcp_close(tp);
7840 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7841 			BBR_STAT_INC(bbr_dropped_af_data);
7842 			return (1);
7843 		}
7844 		/* Set need output so persist might get set */
7845 		bbr->r_wanted_output = 1;
7846 	}
7847 	if (ofia)
7848 		*ofia = ourfinisacked;
7849 	return (0);
7850 }
7851 
7852 static void
7853 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7854 {
7855 	if (bbr->rc_in_persist == 0) {
7856 		bbr_timer_cancel(bbr, __LINE__, cts);
7857 		bbr->r_ctl.rc_last_delay_val = 0;
7858 		tp->t_rxtshift = 0;
7859 		bbr->rc_in_persist = 1;
7860 		bbr->r_ctl.rc_went_idle_time = cts;
7861 		/* We should be capped when rw went to 0 but just in case */
7862 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7863 		/* Time freezes for the state, so do the accounting now */
7864 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7865 			uint32_t time_in;
7866 
7867 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7868 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7869 				int32_t idx;
7870 
7871 				idx = bbr_state_val(bbr);
7872 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7873 			} else {
7874 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7875 			}
7876 		}
7877 		bbr->r_ctl.rc_bbr_state_time = cts;
7878 	}
7879 }
7880 
7881 static void
7882 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7883 {
7884 	/*
7885 	 * Note that if idle time does not exceed our
7886 	 * threshold, we do nothing continuing the state
7887 	 * transitions we were last walking through.
7888 	 */
7889 	if (idle_time >= bbr_idle_restart_threshold) {
7890 		if (bbr->rc_use_idle_restart) {
7891 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7892 			/*
7893 			 * Set our target using BBR_UNIT, so
7894 			 * we increase at a dramatic rate but
7895 			 * we stop when we get the pipe
7896 			 * full again for our current b/w estimate.
7897 			 */
7898 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7899 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7900 			bbr_set_state_target(bbr, __LINE__);
7901 			/* Now setup our gains to ramp up */
7902 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7903 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7904 			bbr_log_type_statechange(bbr, cts, __LINE__);
7905 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7906 			bbr_substate_change(bbr, cts, __LINE__, 1);
7907 		}
7908 	}
7909 }
7910 
7911 static void
7912 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7913 {
7914 	uint32_t idle_time;
7915 
7916 	if (bbr->rc_in_persist == 0)
7917 		return;
7918 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7919 	bbr->rc_in_persist = 0;
7920 	bbr->rc_hit_state_1 = 0;
7921 	bbr->r_ctl.rc_del_time = cts;
7922 	/*
7923 	 * We invalidate the last ack here since we
7924 	 * don't want to transfer forward the time
7925 	 * for our sum's calculations.
7926 	 */
7927 	if (tcp_in_hpts(bbr->rc_inp)) {
7928 		tcp_hpts_remove(bbr->rc_inp);
7929 		bbr->rc_timer_first = 0;
7930 		bbr->r_ctl.rc_hpts_flags = 0;
7931 		bbr->r_ctl.rc_last_delay_val = 0;
7932 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7933 		bbr->r_agg_early_set = 0;
7934 		bbr->r_ctl.rc_agg_early = 0;
7935 	}
7936 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7937 	if (idle_time >= bbr_rtt_probe_time) {
7938 		/*
7939 		 * This qualifies as a RTT_PROBE session since we drop the
7940 		 * data outstanding to nothing and waited more than
7941 		 * bbr_rtt_probe_time.
7942 		 */
7943 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7944 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7945 	}
7946 	tp->t_rxtshift = 0;
7947 	/*
7948 	 * If in probeBW and we have persisted more than an RTT lets do
7949 	 * special handling.
7950 	 */
7951 	/* Force a time based epoch */
7952 	bbr_set_epoch(bbr, cts, __LINE__);
7953 	/*
7954 	 * Setup the lost so we don't count anything against the guy
7955 	 * we have been stuck with during persists.
7956 	 */
7957 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7958 	/* Time un-freezes for the state */
7959 	bbr->r_ctl.rc_bbr_state_time = cts;
7960 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7961 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7962 		/*
7963 		 * If we are going back to probe-bw
7964 		 * or probe_rtt, we may need to possibly
7965 		 * do a fast restart.
7966 		 */
7967 		bbr_restart_after_idle(bbr, cts, idle_time);
7968 	}
7969 }
7970 
7971 static void
7972 bbr_collapsed_window(struct tcp_bbr *bbr)
7973 {
7974 	/*
7975 	 * Now we must walk the
7976 	 * send map and divide the
7977 	 * ones left stranded. These
7978 	 * guys can't cause us to abort
7979 	 * the connection and are really
7980 	 * "unsent". However if a buggy
7981 	 * client actually did keep some
7982 	 * of the data i.e. collapsed the win
7983 	 * and refused to ack and then opened
7984 	 * the win and acked that data. We would
7985 	 * get into an ack war, the simplier
7986 	 * method then of just pretending we
7987 	 * did not send those segments something
7988 	 * won't work.
7989 	 */
7990 	struct bbr_sendmap *rsm, *nrsm;
7991 	tcp_seq max_seq;
7992 	uint32_t maxseg;
7993 	int can_split = 0;
7994 	int fnd = 0;
7995 
7996 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
7997 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
7998 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
7999 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8000 		/* Find the first seq past or at maxseq */
8001 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8002 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8003 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8004 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8005 			fnd = 1;
8006 			break;
8007 		}
8008 	}
8009 	bbr->rc_has_collapsed = 0;
8010 	if (!fnd) {
8011 		/* Nothing to do strange */
8012 		return;
8013 	}
8014 	/*
8015 	 * Now can we split?
8016 	 *
8017 	 * We don't want to split if splitting
8018 	 * would generate too many small segments
8019 	 * less we let an attacker fragment our
8020 	 * send_map and leave us out of memory.
8021 	 */
8022 	if ((max_seq != rsm->r_start) &&
8023 	    (max_seq != rsm->r_end)){
8024 		/* can we split? */
8025 		int res1, res2;
8026 
8027 		res1 = max_seq - rsm->r_start;
8028 		res2 = rsm->r_end - max_seq;
8029 		if ((res1 >= (maxseg/8)) &&
8030 		    (res2 >= (maxseg/8))) {
8031 			/* No small pieces here */
8032 			can_split = 1;
8033 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8034 			/* We are under the limit */
8035 			can_split = 1;
8036 		}
8037 	}
8038 	/* Ok do we need to split this rsm? */
8039 	if (max_seq == rsm->r_start) {
8040 		/* It's this guy no split required */
8041 		nrsm = rsm;
8042 	} else if (max_seq == rsm->r_end) {
8043 		/* It's the next one no split required. */
8044 		nrsm = TAILQ_NEXT(rsm, r_next);
8045 		if (nrsm == NULL) {
8046 			/* Huh? */
8047 			return;
8048 		}
8049 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8050 		/* yep we need to split it */
8051 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8052 		if (nrsm == NULL) {
8053 			/* failed XXXrrs what can we do mark the whole? */
8054 			nrsm = rsm;
8055 			goto no_split;
8056 		}
8057 		/* Clone it */
8058 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8059 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8060 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8061 		if (rsm->r_in_tmap) {
8062 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8063 			nrsm->r_in_tmap = 1;
8064 		}
8065 	} else {
8066 		/*
8067 		 * Split not allowed just start here just
8068 		 * use this guy.
8069 		 */
8070 		nrsm = rsm;
8071 	}
8072 no_split:
8073 	BBR_STAT_INC(bbr_collapsed_win);
8074 	/* reuse fnd as a count */
8075 	fnd = 0;
8076 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8077 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8078 		fnd++;
8079 		bbr->rc_has_collapsed = 1;
8080 	}
8081 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8082 }
8083 
8084 static void
8085 bbr_un_collapse_window(struct tcp_bbr *bbr)
8086 {
8087 	struct bbr_sendmap *rsm;
8088 	int cleared = 0;
8089 
8090 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8091 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8092 			/* Clear the flag */
8093 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8094 			cleared++;
8095 		} else
8096 			break;
8097 	}
8098 	bbr_log_type_rwnd_collapse(bbr,
8099 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8100 	bbr->rc_has_collapsed = 0;
8101 }
8102 
8103 /*
8104  * Return value of 1, the TCB is unlocked and most
8105  * likely gone, return value of 0, the TCB is still
8106  * locked.
8107  */
8108 static int
8109 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8110     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8111     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8112 {
8113 	/*
8114 	 * Update window information. Don't look at window if no ACK: TAC's
8115 	 * send garbage on first SYN.
8116 	 */
8117 	uint16_t nsegs;
8118 	int32_t tfo_syn;
8119 	struct tcp_bbr *bbr;
8120 
8121 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8122 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8123 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8124 	if ((thflags & TH_ACK) &&
8125 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8126 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8127 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8128 		/* keep track of pure window updates */
8129 		if (tlen == 0 &&
8130 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8131 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8132 		tp->snd_wnd = tiwin;
8133 		tp->snd_wl1 = th->th_seq;
8134 		tp->snd_wl2 = th->th_ack;
8135 		if (tp->snd_wnd > tp->max_sndwnd)
8136 			tp->max_sndwnd = tp->snd_wnd;
8137 		bbr->r_wanted_output = 1;
8138 	} else if (thflags & TH_ACK) {
8139 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8140 			tp->snd_wnd = tiwin;
8141 			tp->snd_wl1 = th->th_seq;
8142 			tp->snd_wl2 = th->th_ack;
8143 		}
8144 	}
8145 	if (tp->snd_wnd < ctf_outstanding(tp))
8146 		/* The peer collapsed its window on us */
8147 		bbr_collapsed_window(bbr);
8148  	else if (bbr->rc_has_collapsed)
8149 		bbr_un_collapse_window(bbr);
8150 	/* Was persist timer active and now we have window space? */
8151 	if ((bbr->rc_in_persist != 0) &&
8152 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8153 				bbr_minseg(bbr)))) {
8154 		/*
8155 		 * Make the rate persist at end of persist mode if idle long
8156 		 * enough
8157 		 */
8158 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8159 
8160 		/* Make sure we output to start the timer */
8161 		bbr->r_wanted_output = 1;
8162 	}
8163 	/* Do we need to enter persist? */
8164 	if ((bbr->rc_in_persist == 0) &&
8165 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8166 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8167 	    (tp->snd_max == tp->snd_una) &&
8168 	    sbavail(&so->so_snd) &&
8169 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8170 		/* No send window.. we must enter persist */
8171 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8172 	}
8173 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8174 		m_freem(m);
8175 		return (0);
8176 	}
8177 	/*
8178 	 * We don't support urgent data but
8179 	 * drag along the up just to make sure
8180 	 * if there is a stack switch no one
8181 	 * is surprised.
8182 	 */
8183 	tp->rcv_up = tp->rcv_nxt;
8184 
8185 	/*
8186 	 * Process the segment text, merging it into the TCP sequencing
8187 	 * queue, and arranging for acknowledgment of receipt if necessary.
8188 	 * This process logically involves adjusting tp->rcv_wnd as data is
8189 	 * presented to the user (this happens in tcp_usrreq.c, case
8190 	 * PRU_RCVD).  If a FIN has already been received on this connection
8191 	 * then we just ignore the text.
8192 	 */
8193 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8194 		   IS_FASTOPEN(tp->t_flags));
8195 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8196 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8197 		tcp_seq save_start = th->th_seq;
8198 		tcp_seq save_rnxt  = tp->rcv_nxt;
8199 		int     save_tlen  = tlen;
8200 
8201 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8202 		/*
8203 		 * Insert segment which includes th into TCP reassembly
8204 		 * queue with control block tp.  Set thflags to whether
8205 		 * reassembly now includes a segment with FIN.  This handles
8206 		 * the common case inline (segment is the next to be
8207 		 * received on an established connection, and the queue is
8208 		 * empty), avoiding linkage into and removal from the queue
8209 		 * and repetition of various conversions. Set DELACK for
8210 		 * segments received in order, but ack immediately when
8211 		 * segments are out of order (so fast retransmit can work).
8212 		 */
8213 		if (th->th_seq == tp->rcv_nxt &&
8214 		    SEGQ_EMPTY(tp) &&
8215 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8216 		    tfo_syn)) {
8217 #ifdef NETFLIX_SB_LIMITS
8218 			u_int mcnt, appended;
8219 
8220 			if (so->so_rcv.sb_shlim) {
8221 				mcnt = m_memcnt(m);
8222 				appended = 0;
8223 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8224 				    CFO_NOSLEEP, NULL) == false) {
8225 					counter_u64_add(tcp_sb_shlim_fails, 1);
8226 					m_freem(m);
8227 					return (0);
8228 				}
8229 			}
8230 
8231 #endif
8232 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8233 				bbr->bbr_segs_rcvd += max(1, nsegs);
8234 				tp->t_flags |= TF_DELACK;
8235 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8236 			} else {
8237 				bbr->r_wanted_output = 1;
8238 				tp->t_flags |= TF_ACKNOW;
8239 			}
8240 			tp->rcv_nxt += tlen;
8241 			if (tlen &&
8242 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8243 			    (tp->t_fbyte_in == 0)) {
8244 				tp->t_fbyte_in = ticks;
8245 				if (tp->t_fbyte_in == 0)
8246 					tp->t_fbyte_in = 1;
8247 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8248 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8249 			}
8250 			thflags = tcp_get_flags(th) & TH_FIN;
8251 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8252 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8253 			SOCKBUF_LOCK(&so->so_rcv);
8254 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8255 				m_freem(m);
8256 			else
8257 #ifdef NETFLIX_SB_LIMITS
8258 				appended =
8259 #endif
8260 					sbappendstream_locked(&so->so_rcv, m, 0);
8261 			/* NB: sorwakeup_locked() does an implicit unlock. */
8262 			sorwakeup_locked(so);
8263 #ifdef NETFLIX_SB_LIMITS
8264 			if (so->so_rcv.sb_shlim && appended != mcnt)
8265 				counter_fo_release(so->so_rcv.sb_shlim,
8266 				    mcnt - appended);
8267 #endif
8268 
8269 		} else {
8270 			/*
8271 			 * XXX: Due to the header drop above "th" is
8272 			 * theoretically invalid by now.  Fortunately
8273 			 * m_adj() doesn't actually frees any mbufs when
8274 			 * trimming from the head.
8275 			 */
8276 			tcp_seq temp = save_start;
8277 
8278 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8279 			tp->t_flags |= TF_ACKNOW;
8280 			if (tp->t_flags & TF_WAKESOR) {
8281 				tp->t_flags &= ~TF_WAKESOR;
8282 				/* NB: sorwakeup_locked() does an implicit unlock. */
8283 				sorwakeup_locked(so);
8284 			}
8285 		}
8286 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8287 		    (save_tlen > 0) &&
8288 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8289 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8290 				/*
8291 				 * DSACK actually handled in the fastpath
8292 				 * above.
8293 				 */
8294 				tcp_update_sack_list(tp, save_start,
8295 				    save_start + save_tlen);
8296 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8297 				if ((tp->rcv_numsacks >= 1) &&
8298 				    (tp->sackblks[0].end == save_start)) {
8299 					/*
8300 					 * Partial overlap, recorded at todrop
8301 					 * above.
8302 					 */
8303 					tcp_update_sack_list(tp,
8304 					    tp->sackblks[0].start,
8305 					    tp->sackblks[0].end);
8306 				} else {
8307 					tcp_update_dsack_list(tp, save_start,
8308 					    save_start + save_tlen);
8309 				}
8310 			} else if (tlen >= save_tlen) {
8311 				/* Update of sackblks. */
8312 				tcp_update_dsack_list(tp, save_start,
8313 				    save_start + save_tlen);
8314 			} else if (tlen > 0) {
8315 				tcp_update_dsack_list(tp, save_start,
8316 				    save_start + tlen);
8317 			}
8318 		}
8319 	} else {
8320 		m_freem(m);
8321 		thflags &= ~TH_FIN;
8322 	}
8323 
8324 	/*
8325 	 * If FIN is received ACK the FIN and let the user know that the
8326 	 * connection is closing.
8327 	 */
8328 	if (thflags & TH_FIN) {
8329 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8330 			/* The socket upcall is handled by socantrcvmore. */
8331 			socantrcvmore(so);
8332 			/*
8333 			 * If connection is half-synchronized (ie NEEDSYN
8334 			 * flag on) then delay ACK, so it may be piggybacked
8335 			 * when SYN is sent. Otherwise, since we received a
8336 			 * FIN then no more input can be expected, send ACK
8337 			 * now.
8338 			 */
8339 			if (tp->t_flags & TF_NEEDSYN) {
8340 				tp->t_flags |= TF_DELACK;
8341 				bbr_timer_cancel(bbr,
8342 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8343 			} else {
8344 				tp->t_flags |= TF_ACKNOW;
8345 			}
8346 			tp->rcv_nxt++;
8347 		}
8348 		switch (tp->t_state) {
8349 			/*
8350 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8351 			 * CLOSE_WAIT state.
8352 			 */
8353 		case TCPS_SYN_RECEIVED:
8354 			tp->t_starttime = ticks;
8355 			/* FALLTHROUGH */
8356 		case TCPS_ESTABLISHED:
8357 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8358 			break;
8359 
8360 			/*
8361 			 * If still in FIN_WAIT_1 STATE FIN has not been
8362 			 * acked so enter the CLOSING state.
8363 			 */
8364 		case TCPS_FIN_WAIT_1:
8365 			tcp_state_change(tp, TCPS_CLOSING);
8366 			break;
8367 
8368 			/*
8369 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8370 			 * starting the time-wait timer, turning off the
8371 			 * other standard timers.
8372 			 */
8373 		case TCPS_FIN_WAIT_2:
8374 			bbr->rc_timer_first = 1;
8375 			bbr_timer_cancel(bbr,
8376 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8377 			tcp_twstart(tp);
8378 			return (1);
8379 		}
8380 	}
8381 	/*
8382 	 * Return any desired output.
8383 	 */
8384 	if ((tp->t_flags & TF_ACKNOW) ||
8385 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8386 		bbr->r_wanted_output = 1;
8387 	}
8388 	return (0);
8389 }
8390 
8391 /*
8392  * Here nothing is really faster, its just that we
8393  * have broken out the fast-data path also just like
8394  * the fast-ack. Return 1 if we processed the packet
8395  * return 0 if you need to take the "slow-path".
8396  */
8397 static int
8398 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8399     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8400     uint32_t tiwin, int32_t nxt_pkt)
8401 {
8402 	uint16_t nsegs;
8403 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8404 	struct tcp_bbr *bbr;
8405 #ifdef NETFLIX_SB_LIMITS
8406 	u_int mcnt, appended;
8407 #endif
8408 
8409 	/* On the hpts and we would have called output */
8410 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8411 
8412 	/*
8413 	 * If last ACK falls within this segment's sequence numbers, record
8414 	 * the timestamp. NOTE that the test is modified according to the
8415 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8416 	 */
8417 	if (bbr->r_ctl.rc_resend != NULL) {
8418 		return (0);
8419 	}
8420 	if (tiwin && tiwin != tp->snd_wnd) {
8421 		return (0);
8422 	}
8423 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8424 		return (0);
8425 	}
8426 	if (__predict_false((to->to_flags & TOF_TS) &&
8427 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8428 		return (0);
8429 	}
8430 	if (__predict_false((th->th_ack != tp->snd_una))) {
8431 		return (0);
8432 	}
8433 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8434 		return (0);
8435 	}
8436 	if ((to->to_flags & TOF_TS) != 0 &&
8437 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8438 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8439 		tp->ts_recent = to->to_tsval;
8440 	}
8441 	/*
8442 	 * This is a pure, in-sequence data packet with nothing on the
8443 	 * reassembly queue and we have enough buffer space to take it.
8444 	 */
8445 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8446 
8447 #ifdef NETFLIX_SB_LIMITS
8448 	if (so->so_rcv.sb_shlim) {
8449 		mcnt = m_memcnt(m);
8450 		appended = 0;
8451 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8452 		    CFO_NOSLEEP, NULL) == false) {
8453 			counter_u64_add(tcp_sb_shlim_fails, 1);
8454 			m_freem(m);
8455 			return (1);
8456 		}
8457 	}
8458 #endif
8459 	/* Clean receiver SACK report if present */
8460 	if (tp->rcv_numsacks)
8461 		tcp_clean_sackreport(tp);
8462 	KMOD_TCPSTAT_INC(tcps_preddat);
8463 	tp->rcv_nxt += tlen;
8464 	if (tlen &&
8465 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8466 	    (tp->t_fbyte_in == 0)) {
8467 		tp->t_fbyte_in = ticks;
8468 		if (tp->t_fbyte_in == 0)
8469 			tp->t_fbyte_in = 1;
8470 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8471 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8472 	}
8473 	/*
8474 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8475 	 */
8476 	tp->snd_wl1 = th->th_seq;
8477 	/*
8478 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8479 	 */
8480 	tp->rcv_up = tp->rcv_nxt;
8481 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8482 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8483 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8484 
8485 	/* Add data to socket buffer. */
8486 	SOCKBUF_LOCK(&so->so_rcv);
8487 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8488 		m_freem(m);
8489 	} else {
8490 		/*
8491 		 * Set new socket buffer size. Give up when limit is
8492 		 * reached.
8493 		 */
8494 		if (newsize)
8495 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8496 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8497 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8498 
8499 #ifdef NETFLIX_SB_LIMITS
8500 		appended =
8501 #endif
8502 			sbappendstream_locked(&so->so_rcv, m, 0);
8503 		ctf_calc_rwin(so, tp);
8504 	}
8505 	/* NB: sorwakeup_locked() does an implicit unlock. */
8506 	sorwakeup_locked(so);
8507 #ifdef NETFLIX_SB_LIMITS
8508 	if (so->so_rcv.sb_shlim && mcnt != appended)
8509 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8510 #endif
8511 	if (DELAY_ACK(tp, bbr, nsegs)) {
8512 		bbr->bbr_segs_rcvd += max(1, nsegs);
8513 		tp->t_flags |= TF_DELACK;
8514 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8515 	} else {
8516 		bbr->r_wanted_output = 1;
8517 		tp->t_flags |= TF_ACKNOW;
8518 	}
8519 	return (1);
8520 }
8521 
8522 /*
8523  * This subfunction is used to try to highly optimize the
8524  * fast path. We again allow window updates that are
8525  * in sequence to remain in the fast-path. We also add
8526  * in the __predict's to attempt to help the compiler.
8527  * Note that if we return a 0, then we can *not* process
8528  * it and the caller should push the packet into the
8529  * slow-path. If we return 1, then all is well and
8530  * the packet is fully processed.
8531  */
8532 static int
8533 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8534     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8535     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8536 {
8537 	int32_t acked;
8538 	uint16_t nsegs;
8539 	uint32_t sack_changed;
8540 	uint32_t prev_acked = 0;
8541 	struct tcp_bbr *bbr;
8542 
8543 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8544 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8545 		return (0);
8546 	}
8547 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8548 		/* Above what we have sent? */
8549 		return (0);
8550 	}
8551 	if (__predict_false(tiwin == 0)) {
8552 		/* zero window */
8553 		return (0);
8554 	}
8555 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8556 		/* We need a SYN or a FIN, unlikely.. */
8557 		return (0);
8558 	}
8559 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8560 		/* Timestamp is behind .. old ack with seq wrap? */
8561 		return (0);
8562 	}
8563 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8564 		/* Still recovering */
8565 		return (0);
8566 	}
8567 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8568 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8569 		/* We are retransmitting */
8570 		return (0);
8571 	}
8572 	if (__predict_false(bbr->rc_in_persist != 0)) {
8573 		/* In persist mode */
8574 		return (0);
8575 	}
8576 	if (bbr->r_ctl.rc_sacked) {
8577 		/* We have sack holes on our scoreboard */
8578 		return (0);
8579 	}
8580 	/* Ok if we reach here, we can process a fast-ack */
8581 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8582 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8583 	/*
8584 	 * We never detect loss in fast ack [we can't
8585 	 * have a sack and can't be in recovery so
8586 	 * we always pass 0 (nothing detected)].
8587 	 */
8588 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8589 	/* Did the window get updated? */
8590 	if (tiwin != tp->snd_wnd) {
8591 		tp->snd_wnd = tiwin;
8592 		tp->snd_wl1 = th->th_seq;
8593 		if (tp->snd_wnd > tp->max_sndwnd)
8594 			tp->max_sndwnd = tp->snd_wnd;
8595 	}
8596 	/* Do we need to exit persists? */
8597 	if ((bbr->rc_in_persist != 0) &&
8598 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8599 			       bbr_minseg(bbr)))) {
8600 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8601 		bbr->r_wanted_output = 1;
8602 	}
8603 	/* Do we need to enter persists? */
8604 	if ((bbr->rc_in_persist == 0) &&
8605 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8606 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8607 	    (tp->snd_max == tp->snd_una) &&
8608 	    sbavail(&so->so_snd) &&
8609 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8610 		/* No send window.. we must enter persist */
8611 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8612 	}
8613 	/*
8614 	 * If last ACK falls within this segment's sequence numbers, record
8615 	 * the timestamp. NOTE that the test is modified according to the
8616 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8617 	 */
8618 	if ((to->to_flags & TOF_TS) != 0 &&
8619 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8620 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8621 		tp->ts_recent = to->to_tsval;
8622 	}
8623 	/*
8624 	 * This is a pure ack for outstanding data.
8625 	 */
8626 	KMOD_TCPSTAT_INC(tcps_predack);
8627 
8628 	/*
8629 	 * "bad retransmit" recovery.
8630 	 */
8631 	if (tp->t_flags & TF_PREVVALID) {
8632 		tp->t_flags &= ~TF_PREVVALID;
8633 		if (tp->t_rxtshift == 1 &&
8634 		    (int)(ticks - tp->t_badrxtwin) < 0)
8635 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8636 	}
8637 	/*
8638 	 * Recalculate the transmit timer / rtt.
8639 	 *
8640 	 * Some boxes send broken timestamp replies during the SYN+ACK
8641 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8642 	 * and blow up the retransmit timer.
8643 	 */
8644 	acked = BYTES_THIS_ACK(tp, th);
8645 
8646 #ifdef TCP_HHOOK
8647 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8648 	hhook_run_tcp_est_in(tp, th, to);
8649 #endif
8650 
8651 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8652 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8653 	sbdrop(&so->so_snd, acked);
8654 
8655 	if (SEQ_GT(th->th_ack, tp->snd_una))
8656 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8657 	tp->snd_una = th->th_ack;
8658 	if (tp->snd_wnd < ctf_outstanding(tp))
8659 		/* The peer collapsed its window on us */
8660 		bbr_collapsed_window(bbr);
8661 	else if (bbr->rc_has_collapsed)
8662 		bbr_un_collapse_window(bbr);
8663 
8664 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8665 		tp->snd_recover = tp->snd_una;
8666 	}
8667 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8668 	/*
8669 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8670 	 */
8671 	tp->snd_wl2 = th->th_ack;
8672 	m_freem(m);
8673 	/*
8674 	 * If all outstanding data are acked, stop retransmit timer,
8675 	 * otherwise restart timer using current (possibly backed-off)
8676 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8677 	 * If data are ready to send, let tcp_output decide between more
8678 	 * output or persist.
8679 	 * Wake up the socket if we have room to write more.
8680 	 */
8681 	sowwakeup(so);
8682 	if (tp->snd_una == tp->snd_max) {
8683 		/* Nothing left outstanding */
8684 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8685 		if (sbavail(&so->so_snd) == 0)
8686 			bbr->rc_tp->t_acktime = 0;
8687 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8688 		if (bbr->rc_in_persist == 0) {
8689 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8690 		}
8691 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8692 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8693 		/*
8694 		 * We invalidate the last ack here since we
8695 		 * don't want to transfer forward the time
8696 		 * for our sum's calculations.
8697 		 */
8698 		bbr->r_wanted_output = 1;
8699 	}
8700 	if (sbavail(&so->so_snd)) {
8701 		bbr->r_wanted_output = 1;
8702 	}
8703 	return (1);
8704 }
8705 
8706 /*
8707  * Return value of 1, the TCB is unlocked and most
8708  * likely gone, return value of 0, the TCB is still
8709  * locked.
8710  */
8711 static int
8712 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8713     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8714     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8715 {
8716 	int32_t todrop;
8717 	int32_t ourfinisacked = 0;
8718 	struct tcp_bbr *bbr;
8719 	int32_t ret_val = 0;
8720 
8721 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8722 
8723 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8724 	ctf_calc_rwin(so, tp);
8725 	/*
8726 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8727 	 * SYN, drop the input. if seg contains a RST, then drop the
8728 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8729 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8730 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8731 	 * not support ECN so we will not say we are capable. if SYN has
8732 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8733 	 * segment to be acked (eventually) continue processing rest of
8734 	 * data/controls, beginning with URG
8735 	 */
8736 	if ((thflags & TH_ACK) &&
8737 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8738 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8739 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8740 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8741 		return (1);
8742 	}
8743 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8744 		TCP_PROBE5(connect__refused, NULL, tp,
8745 		    mtod(m, const char *), tp, th);
8746 		tp = tcp_drop(tp, ECONNREFUSED);
8747 		ctf_do_drop(m, tp);
8748 		return (1);
8749 	}
8750 	if (thflags & TH_RST) {
8751 		ctf_do_drop(m, tp);
8752 		return (1);
8753 	}
8754 	if (!(thflags & TH_SYN)) {
8755 		ctf_do_drop(m, tp);
8756 		return (1);
8757 	}
8758 	tp->irs = th->th_seq;
8759 	tcp_rcvseqinit(tp);
8760 	if (thflags & TH_ACK) {
8761 		int tfo_partial = 0;
8762 
8763 		KMOD_TCPSTAT_INC(tcps_connects);
8764 		soisconnected(so);
8765 #ifdef MAC
8766 		mac_socketpeer_set_from_mbuf(m, so);
8767 #endif
8768 		/* Do window scaling on this connection? */
8769 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8770 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8771 			tp->rcv_scale = tp->request_r_scale;
8772 		}
8773 		tp->rcv_adv += min(tp->rcv_wnd,
8774 		    TCP_MAXWIN << tp->rcv_scale);
8775 		/*
8776 		 * If not all the data that was sent in the TFO SYN
8777 		 * has been acked, resend the remainder right away.
8778 		 */
8779 		if (IS_FASTOPEN(tp->t_flags) &&
8780 		    (tp->snd_una != tp->snd_max)) {
8781 			tp->snd_nxt = th->th_ack;
8782 			tfo_partial = 1;
8783 		}
8784 		/*
8785 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8786 		 * will be turned on later.
8787 		 */
8788 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8789 			bbr->bbr_segs_rcvd += 1;
8790 			tp->t_flags |= TF_DELACK;
8791 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8792 		} else {
8793 			bbr->r_wanted_output = 1;
8794 			tp->t_flags |= TF_ACKNOW;
8795 		}
8796 		if (SEQ_GT(th->th_ack, tp->iss)) {
8797 			/*
8798 			 * The SYN is acked
8799 			 * handle it specially.
8800 			 */
8801 			bbr_log_syn(tp, to);
8802 		}
8803 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8804 			/*
8805 			 * We advance snd_una for the
8806 			 * fast open case. If th_ack is
8807 			 * acknowledging data beyond
8808 			 * snd_una we can't just call
8809 			 * ack-processing since the
8810 			 * data stream in our send-map
8811 			 * will start at snd_una + 1 (one
8812 			 * beyond the SYN). If its just
8813 			 * equal we don't need to do that
8814 			 * and there is no send_map.
8815 			 */
8816 			tp->snd_una++;
8817 		}
8818 		/*
8819 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8820 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8821 		 */
8822 		tp->t_starttime = ticks;
8823 		if (tp->t_flags & TF_NEEDFIN) {
8824 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8825 			tp->t_flags &= ~TF_NEEDFIN;
8826 			thflags &= ~TH_SYN;
8827 		} else {
8828 			tcp_state_change(tp, TCPS_ESTABLISHED);
8829 			TCP_PROBE5(connect__established, NULL, tp,
8830 			    mtod(m, const char *), tp, th);
8831 			cc_conn_init(tp);
8832 		}
8833 	} else {
8834 		/*
8835 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8836 		 * open.  If segment contains CC option and there is a
8837 		 * cached CC, apply TAO test. If it succeeds, connection is *
8838 		 * half-synchronized. Otherwise, do 3-way handshake:
8839 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8840 		 * there was no CC option, clear cached CC value.
8841 		 */
8842 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
8843 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8844 	}
8845 	/*
8846 	 * Advance th->th_seq to correspond to first data byte. If data,
8847 	 * trim to stay within window, dropping FIN if necessary.
8848 	 */
8849 	th->th_seq++;
8850 	if (tlen > tp->rcv_wnd) {
8851 		todrop = tlen - tp->rcv_wnd;
8852 		m_adj(m, -todrop);
8853 		tlen = tp->rcv_wnd;
8854 		thflags &= ~TH_FIN;
8855 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8856 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8857 	}
8858 	tp->snd_wl1 = th->th_seq - 1;
8859 	tp->rcv_up = th->th_seq;
8860 	/*
8861 	 * Client side of transaction: already sent SYN and data. If the
8862 	 * remote host used T/TCP to validate the SYN, our data will be
8863 	 * ACK'd; if so, enter normal data segment processing in the middle
8864 	 * of step 5, ack processing. Otherwise, goto step 6.
8865 	 */
8866 	if (thflags & TH_ACK) {
8867 		if ((to->to_flags & TOF_TS) != 0) {
8868 			uint32_t t, rtt;
8869 
8870 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8871 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8872 				rtt = t - to->to_tsecr;
8873 				if (rtt == 0) {
8874 					rtt = 1;
8875 				}
8876 				rtt *= MS_IN_USEC;
8877 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8878 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8879 						       rtt, bbr->r_ctl.rc_rcvtime);
8880 			}
8881 		}
8882 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8883 			return (ret_val);
8884 		/* We may have changed to FIN_WAIT_1 above */
8885 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8886 			/*
8887 			 * In FIN_WAIT_1 STATE in addition to the processing
8888 			 * for the ESTABLISHED state if our FIN is now
8889 			 * acknowledged then enter FIN_WAIT_2.
8890 			 */
8891 			if (ourfinisacked) {
8892 				/*
8893 				 * If we can't receive any more data, then
8894 				 * closing user can proceed. Starting the
8895 				 * timer is contrary to the specification,
8896 				 * but if we don't get a FIN we'll hang
8897 				 * forever.
8898 				 *
8899 				 * XXXjl: we should release the tp also, and
8900 				 * use a compressed state.
8901 				 */
8902 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8903 					soisdisconnected(so);
8904 					tcp_timer_activate(tp, TT_2MSL,
8905 					    (tcp_fast_finwait2_recycle ?
8906 					    tcp_finwait2_timeout :
8907 					    TP_MAXIDLE(tp)));
8908 				}
8909 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8910 			}
8911 		}
8912 	}
8913 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8914 	    tiwin, thflags, nxt_pkt));
8915 }
8916 
8917 /*
8918  * Return value of 1, the TCB is unlocked and most
8919  * likely gone, return value of 0, the TCB is still
8920  * locked.
8921  */
8922 static int
8923 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8924 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8925 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8926 {
8927 	int32_t ourfinisacked = 0;
8928 	int32_t ret_val;
8929 	struct tcp_bbr *bbr;
8930 
8931 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8932 
8933 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8934 	ctf_calc_rwin(so, tp);
8935 	if ((thflags & TH_ACK) &&
8936 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8937 	     SEQ_GT(th->th_ack, tp->snd_max))) {
8938 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8939 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8940 		return (1);
8941 	}
8942 	if (IS_FASTOPEN(tp->t_flags)) {
8943 		/*
8944 		 * When a TFO connection is in SYN_RECEIVED, the only valid
8945 		 * packets are the initial SYN, a retransmit/copy of the
8946 		 * initial SYN (possibly with a subset of the original
8947 		 * data), a valid ACK, a FIN, or a RST.
8948 		 */
8949 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
8950 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8951 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8952 			return (1);
8953 		} else if (thflags & TH_SYN) {
8954 			/* non-initial SYN is ignored */
8955 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
8956 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
8957 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
8958 				ctf_do_drop(m, NULL);
8959 				return (0);
8960 			}
8961 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
8962 			ctf_do_drop(m, NULL);
8963 			return (0);
8964 		}
8965 	}
8966 	if ((thflags & TH_RST) ||
8967 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
8968 		return (ctf_process_rst(m, th, so, tp));
8969 	/*
8970 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
8971 	 * it's less than ts_recent, drop it.
8972 	 */
8973 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
8974 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
8975 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
8976 			return (ret_val);
8977 	}
8978 	/*
8979 	 * In the SYN-RECEIVED state, validate that the packet belongs to
8980 	 * this connection before trimming the data to fit the receive
8981 	 * window.  Check the sequence number versus IRS since we know the
8982 	 * sequence numbers haven't wrapped.  This is a partial fix for the
8983 	 * "LAND" DoS attack.
8984 	 */
8985 	if (SEQ_LT(th->th_seq, tp->irs)) {
8986 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8987 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8988 		return (1);
8989 	}
8990 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
8991 		return (ret_val);
8992 	}
8993 	/*
8994 	 * If last ACK falls within this segment's sequence numbers, record
8995 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
8996 	 * from the latest proposal of the tcplw@cray.com list (Braden
8997 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
8998 	 * with our earlier PAWS tests, so this check should be solely
8999 	 * predicated on the sequence space of this segment. 3) That we
9000 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9001 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9002 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9003 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9004 	 * p.869. In such cases, we can still calculate the RTT correctly
9005 	 * when RCV.NXT == Last.ACK.Sent.
9006 	 */
9007 	if ((to->to_flags & TOF_TS) != 0 &&
9008 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9009 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9010 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9011 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9012 		tp->ts_recent = to->to_tsval;
9013 	}
9014 	tp->snd_wnd = tiwin;
9015 	/*
9016 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9017 	 * is on (half-synchronized state), then queue data for later
9018 	 * processing; else drop segment and return.
9019 	 */
9020 	if ((thflags & TH_ACK) == 0) {
9021 		if (IS_FASTOPEN(tp->t_flags)) {
9022 			cc_conn_init(tp);
9023 		}
9024 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9025 					 tiwin, thflags, nxt_pkt));
9026 	}
9027 	KMOD_TCPSTAT_INC(tcps_connects);
9028 	if (tp->t_flags & TF_SONOTCONN) {
9029 		tp->t_flags &= ~TF_SONOTCONN;
9030 		soisconnected(so);
9031 	}
9032 	/* Do window scaling? */
9033 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9034 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9035 		tp->rcv_scale = tp->request_r_scale;
9036 	}
9037 	/*
9038 	 * ok for the first time in lets see if we can use the ts to figure
9039 	 * out what the initial RTT was.
9040 	 */
9041 	if ((to->to_flags & TOF_TS) != 0) {
9042 		uint32_t t, rtt;
9043 
9044 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9045 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9046 			rtt = t - to->to_tsecr;
9047 			if (rtt == 0) {
9048 				rtt = 1;
9049 			}
9050 			rtt *= MS_IN_USEC;
9051 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9052 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9053 		}
9054 	}
9055 	/* Drop off any SYN in the send map (probably not there)  */
9056 	if (thflags & TH_ACK)
9057 		bbr_log_syn(tp, to);
9058 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9059 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9060 		tp->t_tfo_pending = NULL;
9061 	}
9062 	/*
9063 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9064 	 * FIN-WAIT-1
9065 	 */
9066 	tp->t_starttime = ticks;
9067 	if (tp->t_flags & TF_NEEDFIN) {
9068 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9069 		tp->t_flags &= ~TF_NEEDFIN;
9070 	} else {
9071 		tcp_state_change(tp, TCPS_ESTABLISHED);
9072 		TCP_PROBE5(accept__established, NULL, tp,
9073 			   mtod(m, const char *), tp, th);
9074 		/*
9075 		 * TFO connections call cc_conn_init() during SYN
9076 		 * processing.  Calling it again here for such connections
9077 		 * is not harmless as it would undo the snd_cwnd reduction
9078 		 * that occurs when a TFO SYN|ACK is retransmitted.
9079 		 */
9080 		if (!IS_FASTOPEN(tp->t_flags))
9081 			cc_conn_init(tp);
9082 	}
9083 	/*
9084 	 * Account for the ACK of our SYN prior to
9085 	 * regular ACK processing below, except for
9086 	 * simultaneous SYN, which is handled later.
9087 	 */
9088 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9089 		tp->snd_una++;
9090 	/*
9091 	 * If segment contains data or ACK, will call tcp_reass() later; if
9092 	 * not, do so now to pass queued data to user.
9093 	 */
9094 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9095 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9096 			(struct mbuf *)0);
9097 		if (tp->t_flags & TF_WAKESOR) {
9098 			tp->t_flags &= ~TF_WAKESOR;
9099 			/* NB: sorwakeup_locked() does an implicit unlock. */
9100 			sorwakeup_locked(so);
9101 		}
9102 	}
9103 	tp->snd_wl1 = th->th_seq - 1;
9104 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9105 		return (ret_val);
9106 	}
9107 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9108 		/* We could have went to FIN_WAIT_1 (or EST) above */
9109 		/*
9110 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9111 		 * ESTABLISHED state if our FIN is now acknowledged then
9112 		 * enter FIN_WAIT_2.
9113 		 */
9114 		if (ourfinisacked) {
9115 			/*
9116 			 * If we can't receive any more data, then closing
9117 			 * user can proceed. Starting the timer is contrary
9118 			 * to the specification, but if we don't get a FIN
9119 			 * we'll hang forever.
9120 			 *
9121 			 * XXXjl: we should release the tp also, and use a
9122 			 * compressed state.
9123 			 */
9124 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9125 				soisdisconnected(so);
9126 				tcp_timer_activate(tp, TT_2MSL,
9127 						   (tcp_fast_finwait2_recycle ?
9128 						    tcp_finwait2_timeout :
9129 						    TP_MAXIDLE(tp)));
9130 			}
9131 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9132 		}
9133 	}
9134 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9135 				 tiwin, thflags, nxt_pkt));
9136 }
9137 
9138 /*
9139  * Return value of 1, the TCB is unlocked and most
9140  * likely gone, return value of 0, the TCB is still
9141  * locked.
9142  */
9143 static int
9144 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9145     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9146     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9147 {
9148 	struct tcp_bbr *bbr;
9149 	int32_t ret_val;
9150 
9151 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9152 
9153 	/*
9154 	 * Header prediction: check for the two common cases of a
9155 	 * uni-directional data xfer.  If the packet has no control flags,
9156 	 * is in-sequence, the window didn't change and we're not
9157 	 * retransmitting, it's a candidate.  If the length is zero and the
9158 	 * ack moved forward, we're the sender side of the xfer.  Just free
9159 	 * the data acked & wake any higher level process that was blocked
9160 	 * waiting for space.  If the length is non-zero and the ack didn't
9161 	 * move, we're the receiver side.  If we're getting packets in-order
9162 	 * (the reassembly queue is empty), add the data toc The socket
9163 	 * buffer and note that we need a delayed ack. Make sure that the
9164 	 * hidden state-flags are also off. Since we check for
9165 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9166 	 */
9167 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9168 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9169 		/*
9170 		 * If we have delived under 4 segments increase the initial
9171 		 * window if raised by the peer. We use this to determine
9172 		 * dynamic and static rwnd's at the end of a connection.
9173 		 */
9174 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9175 	}
9176 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9177 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9178 	    __predict_true(SEGQ_EMPTY(tp)) &&
9179 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9180 		if (tlen == 0) {
9181 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9182 			    tiwin, nxt_pkt, iptos)) {
9183 				return (0);
9184 			}
9185 		} else {
9186 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9187 			    tiwin, nxt_pkt)) {
9188 				return (0);
9189 			}
9190 		}
9191 	}
9192 	ctf_calc_rwin(so, tp);
9193 
9194 	if ((thflags & TH_RST) ||
9195 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9196 		return (ctf_process_rst(m, th, so, tp));
9197 	/*
9198 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9199 	 * synchronized state.
9200 	 */
9201 	if (thflags & TH_SYN) {
9202 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9203 		return (ret_val);
9204 	}
9205 	/*
9206 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9207 	 * it's less than ts_recent, drop it.
9208 	 */
9209 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9210 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9211 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9212 			return (ret_val);
9213 	}
9214 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9215 		return (ret_val);
9216 	}
9217 	/*
9218 	 * If last ACK falls within this segment's sequence numbers, record
9219 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9220 	 * from the latest proposal of the tcplw@cray.com list (Braden
9221 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9222 	 * with our earlier PAWS tests, so this check should be solely
9223 	 * predicated on the sequence space of this segment. 3) That we
9224 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9225 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9226 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9227 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9228 	 * p.869. In such cases, we can still calculate the RTT correctly
9229 	 * when RCV.NXT == Last.ACK.Sent.
9230 	 */
9231 	if ((to->to_flags & TOF_TS) != 0 &&
9232 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9233 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9234 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9235 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9236 		tp->ts_recent = to->to_tsval;
9237 	}
9238 	/*
9239 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9240 	 * is on (half-synchronized state), then queue data for later
9241 	 * processing; else drop segment and return.
9242 	 */
9243 	if ((thflags & TH_ACK) == 0) {
9244 		if (tp->t_flags & TF_NEEDSYN) {
9245 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9246 			    tiwin, thflags, nxt_pkt));
9247 		} else if (tp->t_flags & TF_ACKNOW) {
9248 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9249 			bbr->r_wanted_output = 1;
9250 			return (ret_val);
9251 		} else {
9252 			ctf_do_drop(m, NULL);
9253 			return (0);
9254 		}
9255 	}
9256 	/*
9257 	 * Ack processing.
9258 	 */
9259 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9260 		return (ret_val);
9261 	}
9262 	if (sbavail(&so->so_snd)) {
9263 		if (ctf_progress_timeout_check(tp, true)) {
9264 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9265 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9266 			return (1);
9267 		}
9268 	}
9269 	/* State changes only happen in bbr_process_data() */
9270 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9271 	    tiwin, thflags, nxt_pkt));
9272 }
9273 
9274 /*
9275  * Return value of 1, the TCB is unlocked and most
9276  * likely gone, return value of 0, the TCB is still
9277  * locked.
9278  */
9279 static int
9280 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9281     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9282     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9283 {
9284 	struct tcp_bbr *bbr;
9285 	int32_t ret_val;
9286 
9287 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9288 
9289 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9290 	ctf_calc_rwin(so, tp);
9291 	if ((thflags & TH_RST) ||
9292 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9293 		return (ctf_process_rst(m, th, so, tp));
9294 	/*
9295 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9296 	 * synchronized state.
9297 	 */
9298 	if (thflags & TH_SYN) {
9299 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9300 		return (ret_val);
9301 	}
9302 	/*
9303 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9304 	 * it's less than ts_recent, drop it.
9305 	 */
9306 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9307 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9308 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9309 			return (ret_val);
9310 	}
9311 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9312 		return (ret_val);
9313 	}
9314 	/*
9315 	 * If last ACK falls within this segment's sequence numbers, record
9316 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9317 	 * from the latest proposal of the tcplw@cray.com list (Braden
9318 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9319 	 * with our earlier PAWS tests, so this check should be solely
9320 	 * predicated on the sequence space of this segment. 3) That we
9321 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9322 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9323 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9324 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9325 	 * p.869. In such cases, we can still calculate the RTT correctly
9326 	 * when RCV.NXT == Last.ACK.Sent.
9327 	 */
9328 	if ((to->to_flags & TOF_TS) != 0 &&
9329 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9330 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9331 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9332 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9333 		tp->ts_recent = to->to_tsval;
9334 	}
9335 	/*
9336 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9337 	 * is on (half-synchronized state), then queue data for later
9338 	 * processing; else drop segment and return.
9339 	 */
9340 	if ((thflags & TH_ACK) == 0) {
9341 		if (tp->t_flags & TF_NEEDSYN) {
9342 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9343 			    tiwin, thflags, nxt_pkt));
9344 		} else if (tp->t_flags & TF_ACKNOW) {
9345 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9346 			bbr->r_wanted_output = 1;
9347 			return (ret_val);
9348 		} else {
9349 			ctf_do_drop(m, NULL);
9350 			return (0);
9351 		}
9352 	}
9353 	/*
9354 	 * Ack processing.
9355 	 */
9356 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9357 		return (ret_val);
9358 	}
9359 	if (sbavail(&so->so_snd)) {
9360 		if (ctf_progress_timeout_check(tp, true)) {
9361 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9362 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9363 			return (1);
9364 		}
9365 	}
9366 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9367 	    tiwin, thflags, nxt_pkt));
9368 }
9369 
9370 static int
9371 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9372     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9373 {
9374 
9375 	if (bbr->rc_allow_data_af_clo == 0) {
9376 close_now:
9377 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9378 		/* tcp_close will kill the inp pre-log the Reset */
9379 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9380 		tp = tcp_close(tp);
9381 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9382 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9383 		return (1);
9384 	}
9385 	if (sbavail(&so->so_snd) == 0)
9386 		goto close_now;
9387 	/* Ok we allow data that is ignored and a followup reset */
9388 	tp->rcv_nxt = th->th_seq + *tlen;
9389 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9390 	bbr->r_wanted_output = 1;
9391 	*tlen = 0;
9392 	return (0);
9393 }
9394 
9395 /*
9396  * Return value of 1, the TCB is unlocked and most
9397  * likely gone, return value of 0, the TCB is still
9398  * locked.
9399  */
9400 static int
9401 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9402     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9403     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9404 {
9405 	int32_t ourfinisacked = 0;
9406 	int32_t ret_val;
9407 	struct tcp_bbr *bbr;
9408 
9409 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9410 
9411 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9412 	ctf_calc_rwin(so, tp);
9413 	if ((thflags & TH_RST) ||
9414 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9415 		return (ctf_process_rst(m, th, so, tp));
9416 	/*
9417 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9418 	 * synchronized state.
9419 	 */
9420 	if (thflags & TH_SYN) {
9421 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9422 		return (ret_val);
9423 	}
9424 	/*
9425 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9426 	 * it's less than ts_recent, drop it.
9427 	 */
9428 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9429 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9430 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9431 			return (ret_val);
9432 	}
9433 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9434 		return (ret_val);
9435 	}
9436 	/*
9437 	 * If new data are received on a connection after the user processes
9438 	 * are gone, then RST the other end.
9439 	 * We call a new function now so we might continue and setup
9440 	 * to reset at all data being ack'd.
9441 	 */
9442 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9443 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9444 		return (1);
9445 	/*
9446 	 * If last ACK falls within this segment's sequence numbers, record
9447 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9448 	 * from the latest proposal of the tcplw@cray.com list (Braden
9449 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9450 	 * with our earlier PAWS tests, so this check should be solely
9451 	 * predicated on the sequence space of this segment. 3) That we
9452 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9453 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9454 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9455 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9456 	 * p.869. In such cases, we can still calculate the RTT correctly
9457 	 * when RCV.NXT == Last.ACK.Sent.
9458 	 */
9459 	if ((to->to_flags & TOF_TS) != 0 &&
9460 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9461 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9462 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9463 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9464 		tp->ts_recent = to->to_tsval;
9465 	}
9466 	/*
9467 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9468 	 * is on (half-synchronized state), then queue data for later
9469 	 * processing; else drop segment and return.
9470 	 */
9471 	if ((thflags & TH_ACK) == 0) {
9472 		if (tp->t_flags & TF_NEEDSYN) {
9473 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9474 			    tiwin, thflags, nxt_pkt));
9475 		} else if (tp->t_flags & TF_ACKNOW) {
9476 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9477 			bbr->r_wanted_output = 1;
9478 			return (ret_val);
9479 		} else {
9480 			ctf_do_drop(m, NULL);
9481 			return (0);
9482 		}
9483 	}
9484 	/*
9485 	 * Ack processing.
9486 	 */
9487 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9488 		return (ret_val);
9489 	}
9490 	if (ourfinisacked) {
9491 		/*
9492 		 * If we can't receive any more data, then closing user can
9493 		 * proceed. Starting the timer is contrary to the
9494 		 * specification, but if we don't get a FIN we'll hang
9495 		 * forever.
9496 		 *
9497 		 * XXXjl: we should release the tp also, and use a
9498 		 * compressed state.
9499 		 */
9500 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9501 			soisdisconnected(so);
9502 			tcp_timer_activate(tp, TT_2MSL,
9503 			    (tcp_fast_finwait2_recycle ?
9504 			    tcp_finwait2_timeout :
9505 			    TP_MAXIDLE(tp)));
9506 		}
9507 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9508 	}
9509 	if (sbavail(&so->so_snd)) {
9510 		if (ctf_progress_timeout_check(tp, true)) {
9511 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9512 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9513 			return (1);
9514 		}
9515 	}
9516 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9517 	    tiwin, thflags, nxt_pkt));
9518 }
9519 
9520 /*
9521  * Return value of 1, the TCB is unlocked and most
9522  * likely gone, return value of 0, the TCB is still
9523  * locked.
9524  */
9525 static int
9526 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9527     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9528     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9529 {
9530 	int32_t ourfinisacked = 0;
9531 	int32_t ret_val;
9532 	struct tcp_bbr *bbr;
9533 
9534 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9535 
9536 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9537 	ctf_calc_rwin(so, tp);
9538 	if ((thflags & TH_RST) ||
9539 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9540 		return (ctf_process_rst(m, th, so, tp));
9541 	/*
9542 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9543 	 * synchronized state.
9544 	 */
9545 	if (thflags & TH_SYN) {
9546 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9547 		return (ret_val);
9548 	}
9549 	/*
9550 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9551 	 * it's less than ts_recent, drop it.
9552 	 */
9553 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9554 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9555 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9556 			return (ret_val);
9557 	}
9558 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9559 		return (ret_val);
9560 	}
9561 	/*
9562 	 * If new data are received on a connection after the user processes
9563 	 * are gone, then RST the other end.
9564 	 * We call a new function now so we might continue and setup
9565 	 * to reset at all data being ack'd.
9566 	 */
9567 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9568 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9569 		return (1);
9570 	/*
9571 	 * If last ACK falls within this segment's sequence numbers, record
9572 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9573 	 * from the latest proposal of the tcplw@cray.com list (Braden
9574 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9575 	 * with our earlier PAWS tests, so this check should be solely
9576 	 * predicated on the sequence space of this segment. 3) That we
9577 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9578 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9579 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9580 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9581 	 * p.869. In such cases, we can still calculate the RTT correctly
9582 	 * when RCV.NXT == Last.ACK.Sent.
9583 	 */
9584 	if ((to->to_flags & TOF_TS) != 0 &&
9585 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9586 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9587 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9588 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9589 		tp->ts_recent = to->to_tsval;
9590 	}
9591 	/*
9592 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9593 	 * is on (half-synchronized state), then queue data for later
9594 	 * processing; else drop segment and return.
9595 	 */
9596 	if ((thflags & TH_ACK) == 0) {
9597 		if (tp->t_flags & TF_NEEDSYN) {
9598 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9599 			    tiwin, thflags, nxt_pkt));
9600 		} else if (tp->t_flags & TF_ACKNOW) {
9601 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9602 			bbr->r_wanted_output = 1;
9603 			return (ret_val);
9604 		} else {
9605 			ctf_do_drop(m, NULL);
9606 			return (0);
9607 		}
9608 	}
9609 	/*
9610 	 * Ack processing.
9611 	 */
9612 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9613 		return (ret_val);
9614 	}
9615 	if (ourfinisacked) {
9616 		tcp_twstart(tp);
9617 		m_freem(m);
9618 		return (1);
9619 	}
9620 	if (sbavail(&so->so_snd)) {
9621 		if (ctf_progress_timeout_check(tp, true)) {
9622 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9623 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9624 			return (1);
9625 		}
9626 	}
9627 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9628 	    tiwin, thflags, nxt_pkt));
9629 }
9630 
9631 /*
9632  * Return value of 1, the TCB is unlocked and most
9633  * likely gone, return value of 0, the TCB is still
9634  * locked.
9635  */
9636 static int
9637 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9638     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9639     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9640 {
9641 	int32_t ourfinisacked = 0;
9642 	int32_t ret_val;
9643 	struct tcp_bbr *bbr;
9644 
9645 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9646 
9647 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9648 	ctf_calc_rwin(so, tp);
9649 	if ((thflags & TH_RST) ||
9650 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9651 		return (ctf_process_rst(m, th, so, tp));
9652 	/*
9653 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9654 	 * synchronized state.
9655 	 */
9656 	if (thflags & TH_SYN) {
9657 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9658 		return (ret_val);
9659 	}
9660 	/*
9661 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9662 	 * it's less than ts_recent, drop it.
9663 	 */
9664 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9665 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9666 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9667 			return (ret_val);
9668 	}
9669 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9670 		return (ret_val);
9671 	}
9672 	/*
9673 	 * If new data are received on a connection after the user processes
9674 	 * are gone, then RST the other end.
9675 	 * We call a new function now so we might continue and setup
9676 	 * to reset at all data being ack'd.
9677 	 */
9678 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9679 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9680 		return (1);
9681 	/*
9682 	 * If last ACK falls within this segment's sequence numbers, record
9683 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9684 	 * from the latest proposal of the tcplw@cray.com list (Braden
9685 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9686 	 * with our earlier PAWS tests, so this check should be solely
9687 	 * predicated on the sequence space of this segment. 3) That we
9688 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9689 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9690 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9691 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9692 	 * p.869. In such cases, we can still calculate the RTT correctly
9693 	 * when RCV.NXT == Last.ACK.Sent.
9694 	 */
9695 	if ((to->to_flags & TOF_TS) != 0 &&
9696 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9697 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9698 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9699 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9700 		tp->ts_recent = to->to_tsval;
9701 	}
9702 	/*
9703 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9704 	 * is on (half-synchronized state), then queue data for later
9705 	 * processing; else drop segment and return.
9706 	 */
9707 	if ((thflags & TH_ACK) == 0) {
9708 		if (tp->t_flags & TF_NEEDSYN) {
9709 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9710 			    tiwin, thflags, nxt_pkt));
9711 		} else if (tp->t_flags & TF_ACKNOW) {
9712 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9713 			bbr->r_wanted_output = 1;
9714 			return (ret_val);
9715 		} else {
9716 			ctf_do_drop(m, NULL);
9717 			return (0);
9718 		}
9719 	}
9720 	/*
9721 	 * case TCPS_LAST_ACK: Ack processing.
9722 	 */
9723 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9724 		return (ret_val);
9725 	}
9726 	if (ourfinisacked) {
9727 		tp = tcp_close(tp);
9728 		ctf_do_drop(m, tp);
9729 		return (1);
9730 	}
9731 	if (sbavail(&so->so_snd)) {
9732 		if (ctf_progress_timeout_check(tp, true)) {
9733 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9734 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9735 			return (1);
9736 		}
9737 	}
9738 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9739 	    tiwin, thflags, nxt_pkt));
9740 }
9741 
9742 /*
9743  * Return value of 1, the TCB is unlocked and most
9744  * likely gone, return value of 0, the TCB is still
9745  * locked.
9746  */
9747 static int
9748 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9749     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9750     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9751 {
9752 	int32_t ourfinisacked = 0;
9753 	int32_t ret_val;
9754 	struct tcp_bbr *bbr;
9755 
9756 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9757 
9758 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9759 	ctf_calc_rwin(so, tp);
9760 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9761 	if ((thflags & TH_RST) ||
9762 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9763 		return (ctf_process_rst(m, th, so, tp));
9764 
9765 	/*
9766 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9767 	 * synchronized state.
9768 	 */
9769 	if (thflags & TH_SYN) {
9770 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9771 		return (ret_val);
9772 	}
9773 	/*
9774 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9775 	 * it's less than ts_recent, drop it.
9776 	 */
9777 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9778 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9779 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9780 			return (ret_val);
9781 	}
9782 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9783 		return (ret_val);
9784 	}
9785 	/*
9786 	 * If new data are received on a connection after the user processes
9787 	 * are gone, then we may RST the other end depending on the outcome
9788 	 * of bbr_check_data_after_close.
9789 	 * We call a new function now so we might continue and setup
9790 	 * to reset at all data being ack'd.
9791 	 */
9792 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9793 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9794 		return (1);
9795 	/*
9796 	 * If last ACK falls within this segment's sequence numbers, record
9797 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9798 	 * from the latest proposal of the tcplw@cray.com list (Braden
9799 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9800 	 * with our earlier PAWS tests, so this check should be solely
9801 	 * predicated on the sequence space of this segment. 3) That we
9802 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9803 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9804 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9805 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9806 	 * p.869. In such cases, we can still calculate the RTT correctly
9807 	 * when RCV.NXT == Last.ACK.Sent.
9808 	 */
9809 	if ((to->to_flags & TOF_TS) != 0 &&
9810 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9811 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9812 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9813 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9814 		tp->ts_recent = to->to_tsval;
9815 	}
9816 	/*
9817 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9818 	 * is on (half-synchronized state), then queue data for later
9819 	 * processing; else drop segment and return.
9820 	 */
9821 	if ((thflags & TH_ACK) == 0) {
9822 		if (tp->t_flags & TF_NEEDSYN) {
9823 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9824 			    tiwin, thflags, nxt_pkt));
9825 		} else if (tp->t_flags & TF_ACKNOW) {
9826 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9827 			bbr->r_wanted_output = 1;
9828 			return (ret_val);
9829 		} else {
9830 			ctf_do_drop(m, NULL);
9831 			return (0);
9832 		}
9833 	}
9834 	/*
9835 	 * Ack processing.
9836 	 */
9837 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9838 		return (ret_val);
9839 	}
9840 	if (sbavail(&so->so_snd)) {
9841 		if (ctf_progress_timeout_check(tp, true)) {
9842 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9843 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9844 			return (1);
9845 		}
9846 	}
9847 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9848 	    tiwin, thflags, nxt_pkt));
9849 }
9850 
9851 static void
9852 bbr_stop_all_timers(struct tcpcb *tp)
9853 {
9854 	struct tcp_bbr *bbr;
9855 
9856 	/*
9857 	 * Assure no timers are running.
9858 	 */
9859 	if (tcp_timer_active(tp, TT_PERSIST)) {
9860 		/* We enter in persists, set the flag appropriately */
9861 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9862 		bbr->rc_in_persist = 1;
9863 	}
9864 }
9865 
9866 static void
9867 bbr_google_mode_on(struct tcp_bbr *bbr)
9868 {
9869 	bbr->rc_use_google = 1;
9870 	bbr->rc_no_pacing = 0;
9871 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9872 	bbr->r_use_policer = bbr_policer_detection_enabled;
9873 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9874 	bbr->bbr_use_rack_cheat = 0;
9875 	bbr->r_ctl.rc_incr_tmrs = 0;
9876 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9877 	bbr->r_ctl.rc_inc_ip_oh = 0;
9878 	bbr->r_ctl.rc_inc_enet_oh = 0;
9879 	reset_time(&bbr->r_ctl.rc_delrate,
9880 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9881 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9882 			 (11 * USECS_IN_SECOND));
9883 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9884 }
9885 
9886 static void
9887 bbr_google_mode_off(struct tcp_bbr *bbr)
9888 {
9889 	bbr->rc_use_google = 0;
9890 	bbr->r_ctl.bbr_google_discount = 0;
9891 	bbr->no_pacing_until = bbr_no_pacing_until;
9892 	bbr->r_use_policer = 0;
9893 	if (bbr->no_pacing_until)
9894 		bbr->rc_no_pacing = 1;
9895 	else
9896 		bbr->rc_no_pacing = 0;
9897 	if (bbr_use_rack_resend_cheat)
9898 		bbr->bbr_use_rack_cheat = 1;
9899 	else
9900 		bbr->bbr_use_rack_cheat = 0;
9901 	if (bbr_incr_timers)
9902 		bbr->r_ctl.rc_incr_tmrs = 1;
9903 	else
9904 		bbr->r_ctl.rc_incr_tmrs = 0;
9905 	if (bbr_include_tcp_oh)
9906 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9907 	else
9908 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9909 	if (bbr_include_ip_oh)
9910 		bbr->r_ctl.rc_inc_ip_oh = 1;
9911 	else
9912 		bbr->r_ctl.rc_inc_ip_oh = 0;
9913 	if (bbr_include_enet_oh)
9914 		bbr->r_ctl.rc_inc_enet_oh = 1;
9915 	else
9916 		bbr->r_ctl.rc_inc_enet_oh = 0;
9917 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9918 	reset_time(&bbr->r_ctl.rc_delrate,
9919 		   bbr_num_pktepo_for_del_limit);
9920 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9921 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9922 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9923 }
9924 /*
9925  * Return 0 on success, non-zero on failure
9926  * which indicates the error (usually no memory).
9927  */
9928 static int
9929 bbr_init(struct tcpcb *tp)
9930 {
9931 	struct inpcb *inp = tptoinpcb(tp);
9932 	struct tcp_bbr *bbr = NULL;
9933 	uint32_t cts;
9934 
9935 	tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
9936 	if (tp->t_fb_ptr == NULL) {
9937 		/*
9938 		 * We need to allocate memory but cant. The INP and INP_INFO
9939 		 * locks and they are recursive (happens during setup. So a
9940 		 * scheme to drop the locks fails :(
9941 		 *
9942 		 */
9943 		return (ENOMEM);
9944 	}
9945 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9946 	bbr->rtt_valid = 0;
9947 	inp->inp_flags2 |= INP_CANNOT_DO_ECN;
9948 	inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
9949 	TAILQ_INIT(&bbr->r_ctl.rc_map);
9950 	TAILQ_INIT(&bbr->r_ctl.rc_free);
9951 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
9952 	bbr->rc_tp = tp;
9953 	bbr->rc_inp = inp;
9954 	cts = tcp_get_usecs(&bbr->rc_tv);
9955 	tp->t_acktime = 0;
9956 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
9957 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
9958 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
9959 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
9960 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
9961 	bbr->r_ctl.rc_min_to = bbr_min_to;
9962 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
9963 	bbr->r_ctl.bbr_lost_at_state = 0;
9964 	bbr->r_ctl.rc_lost_at_startup = 0;
9965 	bbr->rc_all_timers_stopped = 0;
9966 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
9967 	bbr->r_ctl.rc_pkt_epoch_del = 0;
9968 	bbr->r_ctl.rc_pkt_epoch = 0;
9969 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
9970 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
9971 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
9972 	bbr->r_ctl.rc_went_idle_time = cts;
9973 	bbr->rc_pacer_started = cts;
9974 	bbr->r_ctl.rc_pkt_epoch_time = cts;
9975 	bbr->r_ctl.rc_rcvtime = cts;
9976 	bbr->r_ctl.rc_bbr_state_time = cts;
9977 	bbr->r_ctl.rc_del_time = cts;
9978 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
9979 	bbr->r_ctl.last_in_probertt = cts;
9980 	bbr->skip_gain = 0;
9981 	bbr->gain_is_limited = 0;
9982 	bbr->no_pacing_until = bbr_no_pacing_until;
9983 	if (bbr->no_pacing_until)
9984 		bbr->rc_no_pacing = 1;
9985 	if (bbr_use_google_algo) {
9986 		bbr->rc_no_pacing = 0;
9987 		bbr->rc_use_google = 1;
9988 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9989 		bbr->r_use_policer = bbr_policer_detection_enabled;
9990 	} else {
9991 		bbr->rc_use_google = 0;
9992 		bbr->r_ctl.bbr_google_discount = 0;
9993 		bbr->r_use_policer = 0;
9994 	}
9995 	if (bbr_ts_limiting)
9996 		bbr->rc_use_ts_limit = 1;
9997 	else
9998 		bbr->rc_use_ts_limit = 0;
9999 	if (bbr_ts_can_raise)
10000 		bbr->ts_can_raise = 1;
10001 	else
10002 		bbr->ts_can_raise = 0;
10003 	if (V_tcp_delack_enabled == 1)
10004 		tp->t_delayed_ack = 2;
10005 	else if (V_tcp_delack_enabled == 0)
10006 		tp->t_delayed_ack = 0;
10007 	else if (V_tcp_delack_enabled < 100)
10008 		tp->t_delayed_ack = V_tcp_delack_enabled;
10009 	else
10010 		tp->t_delayed_ack = 2;
10011 	if (bbr->rc_use_google == 0)
10012 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10013 	else
10014 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10015 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10016 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10017 	bbr->rc_init_win = bbr_def_init_win;
10018 	if (tp->t_flags & TF_REQ_TSTMP)
10019 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10020 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10021 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10022 	bbr->r_init_rtt = 1;
10023 
10024 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10025 	if (bbr_allow_hdwr_pacing)
10026 		bbr->bbr_hdw_pace_ena = 1;
10027 	else
10028 		bbr->bbr_hdw_pace_ena = 0;
10029 	if (bbr_sends_full_iwnd)
10030 		bbr->bbr_init_win_cheat = 1;
10031 	else
10032 		bbr->bbr_init_win_cheat = 0;
10033 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10034 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10035 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10036 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10037 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10038 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10039 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10040 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10041 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10042 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10043 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10044 	bbr->r_ctl.rc_rtt_shrinks = cts;
10045 	if (bbr->rc_use_google) {
10046 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10047 				  FILTER_TYPE_MAX,
10048 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10049 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10050 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10051 	} else {
10052 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10053 				  FILTER_TYPE_MAX,
10054 				  bbr_num_pktepo_for_del_limit);
10055 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10056 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10057 	}
10058 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10059 	if (bbr_uses_idle_restart)
10060 		bbr->rc_use_idle_restart = 1;
10061 	else
10062 		bbr->rc_use_idle_restart = 0;
10063 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10064 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10065 	if (bbr_resends_use_tso)
10066 		bbr->rc_resends_use_tso = 1;
10067 #ifdef NETFLIX_PEAKRATE
10068 	tp->t_peakrate_thr = tp->t_maxpeakrate;
10069 #endif
10070 	if (tp->snd_una != tp->snd_max) {
10071 		/* Create a send map for the current outstanding data */
10072 		struct bbr_sendmap *rsm;
10073 
10074 		rsm = bbr_alloc(bbr);
10075 		if (rsm == NULL) {
10076 			uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10077 			tp->t_fb_ptr = NULL;
10078 			return (ENOMEM);
10079 		}
10080 		rsm->r_rtt_not_allowed = 1;
10081 		rsm->r_tim_lastsent[0] = cts;
10082 		rsm->r_rtr_cnt = 1;
10083 		rsm->r_rtr_bytes = 0;
10084 		rsm->r_start = tp->snd_una;
10085 		rsm->r_end = tp->snd_max;
10086 		rsm->r_dupack = 0;
10087 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10088 		rsm->r_ts_valid = 0;
10089 		rsm->r_del_ack_ts = tp->ts_recent;
10090 		rsm->r_del_time = cts;
10091 		if (bbr->r_ctl.r_app_limited_until)
10092 			rsm->r_app_limited = 1;
10093 		else
10094 			rsm->r_app_limited = 0;
10095 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10096 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10097 		rsm->r_in_tmap = 1;
10098 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10099 			rsm->r_bbr_state = bbr_state_val(bbr);
10100 		else
10101 			rsm->r_bbr_state = 8;
10102 	}
10103 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10104 		bbr->bbr_use_rack_cheat = 1;
10105 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10106 		bbr->r_ctl.rc_incr_tmrs = 1;
10107 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10108 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10109 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10110 		bbr->r_ctl.rc_inc_ip_oh = 1;
10111 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10112 		bbr->r_ctl.rc_inc_enet_oh = 1;
10113 
10114 	bbr_log_type_statechange(bbr, cts, __LINE__);
10115 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10116 	    (tp->t_srtt)) {
10117 		uint32_t rtt;
10118 
10119 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10120 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10121 	}
10122 	/* announce the settings and state */
10123 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10124 	tcp_bbr_tso_size_check(bbr, cts);
10125 	/*
10126 	 * Now call the generic function to start a timer. This will place
10127 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10128 	 * flags.
10129 	 */
10130 	bbr_stop_all_timers(tp);
10131 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10132 	return (0);
10133 }
10134 
10135 /*
10136  * Return 0 if we can accept the connection. Return
10137  * non-zero if we can't handle the connection. A EAGAIN
10138  * means you need to wait until the connection is up.
10139  * a EADDRNOTAVAIL means we can never handle the connection
10140  * (no SACK).
10141  */
10142 static int
10143 bbr_handoff_ok(struct tcpcb *tp)
10144 {
10145 	if ((tp->t_state == TCPS_CLOSED) ||
10146 	    (tp->t_state == TCPS_LISTEN)) {
10147 		/* Sure no problem though it may not stick */
10148 		return (0);
10149 	}
10150 	if ((tp->t_state == TCPS_SYN_SENT) ||
10151 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10152 		/*
10153 		 * We really don't know you have to get to ESTAB or beyond
10154 		 * to tell.
10155 		 */
10156 		return (EAGAIN);
10157 	}
10158 	if (tp->t_flags & TF_SENTFIN)
10159 		return (EINVAL);
10160 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10161 		return (0);
10162 	}
10163 	/*
10164 	 * If we reach here we don't do SACK on this connection so we can
10165 	 * never do rack.
10166 	 */
10167 	return (EINVAL);
10168 }
10169 
10170 static void
10171 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10172 {
10173 	if (tp->t_fb_ptr) {
10174 		struct inpcb *inp = tptoinpcb(tp);
10175 		uint32_t calc;
10176 		struct tcp_bbr *bbr;
10177 		struct bbr_sendmap *rsm;
10178 
10179 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10180 		if (bbr->r_ctl.crte)
10181 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10182 		bbr_log_flowend(bbr);
10183 		bbr->rc_tp = NULL;
10184 		/* Backout any flags2 we applied */
10185 		inp->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10186 		inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10187 		inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10188 		if (bbr->bbr_hdrw_pacing)
10189 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10190 		else
10191 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10192 		if (bbr->r_ctl.crte != NULL) {
10193 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10194 			bbr->r_ctl.crte = NULL;
10195 		}
10196 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10197 		while (rsm) {
10198 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10199 			uma_zfree(bbr_zone, rsm);
10200 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10201 		}
10202 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10203 		while (rsm) {
10204 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10205 			uma_zfree(bbr_zone, rsm);
10206 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10207 		}
10208 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10209 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10210 			BBR_STAT_INC(bbr_dynamic_rwnd);
10211 		else
10212 			BBR_STAT_INC(bbr_static_rwnd);
10213 		bbr->r_ctl.rc_free_cnt = 0;
10214 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10215 		tp->t_fb_ptr = NULL;
10216 	}
10217 	/* Make sure snd_nxt is correctly set */
10218 	tp->snd_nxt = tp->snd_max;
10219 }
10220 
10221 static void
10222 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10223 {
10224 	switch (tp->t_state) {
10225 	case TCPS_SYN_SENT:
10226 		bbr->r_state = TCPS_SYN_SENT;
10227 		bbr->r_substate = bbr_do_syn_sent;
10228 		break;
10229 	case TCPS_SYN_RECEIVED:
10230 		bbr->r_state = TCPS_SYN_RECEIVED;
10231 		bbr->r_substate = bbr_do_syn_recv;
10232 		break;
10233 	case TCPS_ESTABLISHED:
10234 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10235 		bbr->r_state = TCPS_ESTABLISHED;
10236 		bbr->r_substate = bbr_do_established;
10237 		break;
10238 	case TCPS_CLOSE_WAIT:
10239 		bbr->r_state = TCPS_CLOSE_WAIT;
10240 		bbr->r_substate = bbr_do_close_wait;
10241 		break;
10242 	case TCPS_FIN_WAIT_1:
10243 		bbr->r_state = TCPS_FIN_WAIT_1;
10244 		bbr->r_substate = bbr_do_fin_wait_1;
10245 		break;
10246 	case TCPS_CLOSING:
10247 		bbr->r_state = TCPS_CLOSING;
10248 		bbr->r_substate = bbr_do_closing;
10249 		break;
10250 	case TCPS_LAST_ACK:
10251 		bbr->r_state = TCPS_LAST_ACK;
10252 		bbr->r_substate = bbr_do_lastack;
10253 		break;
10254 	case TCPS_FIN_WAIT_2:
10255 		bbr->r_state = TCPS_FIN_WAIT_2;
10256 		bbr->r_substate = bbr_do_fin_wait_2;
10257 		break;
10258 	case TCPS_LISTEN:
10259 	case TCPS_CLOSED:
10260 	case TCPS_TIME_WAIT:
10261 	default:
10262 		break;
10263 	};
10264 }
10265 
10266 static void
10267 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10268 {
10269 	/*
10270 	 * Now what state are we going into now? Is there adjustments
10271 	 * needed?
10272 	 */
10273 	int32_t old_state;
10274 
10275 	old_state = bbr_state_val(bbr);
10276 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10277 		/* Save the lowest srtt we saw in our end of the sub-state */
10278 		bbr->rc_hit_state_1 = 0;
10279 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10280 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10281 	}
10282 	bbr->rc_bbr_substate++;
10283 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10284 		/* Cycle back to first state-> gain */
10285 		bbr->rc_bbr_substate = 0;
10286 	}
10287 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10288 		/*
10289 		 * We enter the gain(5/4) cycle (possibly less if
10290 		 * shallow buffer detection is enabled)
10291 		 */
10292 		if (bbr->skip_gain) {
10293 			/*
10294 			 * Hardware pacing has set our rate to
10295 			 * the max and limited our b/w just
10296 			 * do level i.e. no gain.
10297 			 */
10298 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10299 		} else if (bbr->gain_is_limited &&
10300 			   bbr->bbr_hdrw_pacing &&
10301 			   bbr->r_ctl.crte) {
10302 			/*
10303 			 * We can't gain above the hardware pacing
10304 			 * rate which is less than our rate + the gain
10305 			 * calculate the gain needed to reach the hardware
10306 			 * pacing rate..
10307 			 */
10308 			uint64_t bw, rate, gain_calc;
10309 
10310 			bw = bbr_get_bw(bbr);
10311 			rate = bbr->r_ctl.crte->rate;
10312 			if ((rate > bw) &&
10313 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10314 				gain_calc = (rate * BBR_UNIT) / bw;
10315 				if (gain_calc < BBR_UNIT)
10316 					gain_calc = BBR_UNIT;
10317 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10318 			} else {
10319 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10320 			}
10321 		} else
10322 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10323 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10324 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10325 		} else
10326 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10327 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10328 		bbr->rc_hit_state_1 = 1;
10329 		bbr->r_ctl.rc_exta_time_gd = 0;
10330 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10331 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10332 		if (bbr_state_drain_2_tar) {
10333 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10334 		} else
10335 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10336 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10337 	} else {
10338 		/* All other cycles hit here 2-7 */
10339 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10340 			if (bbr_sub_drain_slam_cwnd &&
10341 			    (bbr->rc_use_google == 0) &&
10342 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10343 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10344 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10345 			}
10346 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10347 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10348 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10349 			else
10350 				bbr->r_ctl.rc_exta_time_gd = 0;
10351 			if (bbr->r_ctl.rc_exta_time_gd) {
10352 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10353 				/* Now chop up the time for each state (div by 7) */
10354 				bbr->r_ctl.rc_level_state_extra /= 7;
10355 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10356 					/* Add a randomization */
10357 					bbr_randomize_extra_state_time(bbr);
10358 				}
10359 			}
10360 		}
10361 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10362 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10363 	}
10364 	if (bbr->rc_use_google) {
10365 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10366 	}
10367 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10368 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10369 	if (dolog)
10370 		bbr_log_type_statechange(bbr, cts, line);
10371 
10372 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10373 		uint32_t time_in;
10374 
10375 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10376 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10377 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10378 		} else {
10379 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10380 		}
10381 	}
10382 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10383 	bbr_set_state_target(bbr, __LINE__);
10384 	if (bbr_sub_drain_slam_cwnd &&
10385 	    (bbr->rc_use_google == 0) &&
10386 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10387 		/* Slam down the cwnd */
10388 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10389 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10390 		if (bbr_sub_drain_app_limit) {
10391 			/* Go app limited if we are on a long drain */
10392 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10393 							  ctf_flight_size(bbr->rc_tp,
10394 							      (bbr->r_ctl.rc_sacked +
10395 							       bbr->r_ctl.rc_lost_bytes)));
10396 		}
10397 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10398 	}
10399 	if (bbr->rc_lt_use_bw) {
10400 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10401 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10402 	}
10403 	/* Google changes TSO size every cycle */
10404 	if (bbr->rc_use_google)
10405 		tcp_bbr_tso_size_check(bbr, cts);
10406 	bbr->r_ctl.gain_epoch = cts;
10407 	bbr->r_ctl.rc_bbr_state_time = cts;
10408 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10409 }
10410 
10411 static void
10412 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10413 {
10414 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10415 	    (google_allow_early_out == 1) &&
10416 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10417 		/* We have reached out target flight size possibly early */
10418 		goto change_state;
10419 	}
10420 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10421 		return;
10422 	}
10423 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10424 		/*
10425 		 * Must be a rttProp movement forward before
10426 		 * we can change states.
10427 		 */
10428 		return;
10429 	}
10430 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10431 		/*
10432 		 * The needed time has passed but for
10433 		 * the gain cycle extra rules apply:
10434 		 * 1) If we have seen loss, we exit
10435 		 * 2) If we have not reached the target
10436 		 *    we stay in GAIN (gain-to-target).
10437 		 */
10438 		if (google_consider_lost && losses)
10439 			goto change_state;
10440 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10441 			return;
10442 		}
10443 	}
10444 change_state:
10445 	/* For gain we must reach our target, all others last 1 rttProp */
10446 	bbr_substate_change(bbr, cts, __LINE__, 1);
10447 }
10448 
10449 static void
10450 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10451 {
10452 	uint32_t flight, bbr_cur_cycle_time;
10453 
10454 	if (bbr->rc_use_google) {
10455 		bbr_set_probebw_google_gains(bbr, cts, losses);
10456 		return;
10457 	}
10458 	if (cts == 0) {
10459 		/*
10460 		 * Never alow cts to be 0 we
10461 		 * do this so we can judge if
10462 		 * we have set a timestamp.
10463 		 */
10464 		cts = 1;
10465 	}
10466 	if (bbr_state_is_pkt_epoch)
10467 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10468 	else
10469 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10470 
10471 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10472 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10473 			flight = ctf_flight_size(bbr->rc_tp,
10474 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10475 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10476 				/* Keep it slam down */
10477 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10478 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10479 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10480 				}
10481 				if (bbr_sub_drain_app_limit) {
10482 					/* Go app limited if we are on a long drain */
10483 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10484 				}
10485 			}
10486 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10487 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10488 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10489 				/*
10490 				 * Still here after the same time as
10491 				 * the gain. We need to drain harder
10492 				 * for the next srtt. Reduce by a set amount
10493 				 * the gain drop is capped at DRAIN states
10494 				 * value (88).
10495 				 */
10496 				bbr->r_ctl.flightsize_at_drain = flight;
10497 				if (bbr_drain_drop_mul &&
10498 				    bbr_drain_drop_div &&
10499 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10500 					/* Use your specific drop value (def 4/5 = 20%) */
10501 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10502 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10503 				} else {
10504 					/* You get drop of 20% */
10505 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10506 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10507 				}
10508 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10509 					/* Reduce our gain again to the bottom  */
10510 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10511 				}
10512 				bbr_log_exit_gain(bbr, cts, 4);
10513 				/*
10514 				 * Extend out so we wait another
10515 				 * epoch before dropping again.
10516 				 */
10517 				bbr->r_ctl.gain_epoch = cts;
10518 			}
10519 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10520 				if (bbr_sub_drain_slam_cwnd &&
10521 				    (bbr->rc_use_google == 0) &&
10522 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10523 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10524 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10525 				}
10526 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10527 				bbr_log_exit_gain(bbr, cts, 3);
10528 			}
10529 		} else {
10530 			/* Its a gain  */
10531 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10532 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10533 				goto change_state;
10534 			}
10535 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10536 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10537 			     bbr->rc_tp->snd_wnd)) {
10538 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10539 				bbr_log_exit_gain(bbr, cts, 2);
10540 			}
10541 		}
10542 		/**
10543 		 * We fall through and return always one of two things has
10544 		 * occurred.
10545 		 * 1) We are still not at target
10546 		 *    <or>
10547 		 * 2) We reached the target and set rc_bbr_state_atflight
10548 		 *    which means we no longer hit this block
10549 		 *    next time we are called.
10550 		 */
10551 		return;
10552 	}
10553 change_state:
10554 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10555 		return;
10556 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10557 		/* Less than a full time-period has passed */
10558 		return;
10559 	}
10560 	if (bbr->r_ctl.rc_level_state_extra &&
10561 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10562 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10563 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10564 		/* Less than a full time-period + extra has passed */
10565 		return;
10566 	}
10567 	if (bbr_gain_gets_extra_too &&
10568 	    bbr->r_ctl.rc_level_state_extra &&
10569 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10570 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10571 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10572 		/* Less than a full time-period + extra has passed */
10573 		return;
10574 	}
10575 	bbr_substate_change(bbr, cts, __LINE__, 1);
10576 }
10577 
10578 static uint32_t
10579 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10580 {
10581 	uint32_t mss, tar;
10582 
10583 	if (bbr->rc_use_google) {
10584 		/* Google just uses the cwnd target */
10585 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10586 	} else {
10587 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10588 			  bbr->r_ctl.rc_pace_max_segs);
10589 		/* Get the base cwnd with gain rounded to a mss */
10590 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10591 						      gain), mss);
10592 		/* Make sure it is within our min */
10593 		if (tar < get_min_cwnd(bbr))
10594 			return (get_min_cwnd(bbr));
10595 	}
10596 	return (tar);
10597 }
10598 
10599 static void
10600 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10601 {
10602 	uint32_t tar, meth;
10603 
10604 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10605 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10606 		/* Special case using old probe-rtt method */
10607 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10608 		meth = 1;
10609 	} else {
10610 		/* Non-probe-rtt case and reduced probe-rtt  */
10611 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10612 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10613 			/* For gain cycle we use the hptsi gain */
10614 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10615 			meth = 2;
10616 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10617 			/*
10618 			 * If configured, or for google all other states
10619 			 * get BBR_UNIT.
10620 			 */
10621 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10622 			meth = 3;
10623 		} else {
10624 			/*
10625 			 * Or we set a target based on the pacing gain
10626 			 * for non-google mode and default (non-configured).
10627 			 * Note we don't set a target goal below drain (192).
10628 			 */
10629 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10630 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10631 				meth = 4;
10632 			} else {
10633 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10634 				meth = 5;
10635 			}
10636 		}
10637 	}
10638 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10639 	bbr->r_ctl.rc_target_at_state = tar;
10640 }
10641 
10642 static void
10643 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10644 {
10645 	/* Change to probe_rtt */
10646 	uint32_t time_in;
10647 
10648 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10649 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10650 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10651 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10652 					  + bbr->r_ctl.rc_delivered);
10653 	/* Setup so we force feed the filter */
10654 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10655 		bbr->rc_prtt_set_ts = 1;
10656 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10657 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10658 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10659 	}
10660 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10661 	bbr->r_ctl.rc_rtt_shrinks = cts;
10662 	bbr->r_ctl.last_in_probertt = cts;
10663 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10664 	bbr->r_ctl.rc_bbr_state_time = cts;
10665 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10666 	/* We need to force the filter to update */
10667 
10668 	if ((bbr_sub_drain_slam_cwnd) &&
10669 	    bbr->rc_hit_state_1 &&
10670 	    (bbr->rc_use_google == 0) &&
10671 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10672 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10673 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10674 	} else
10675 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10676 	/* Update the lost */
10677 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10678 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10679 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10680 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10681 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10682 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10683 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10684 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10685 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10686 	} else {
10687 		/*
10688 		 * We bring it down slowly by using a hptsi gain that is
10689 		 * probably 75%. This will slowly float down our outstanding
10690 		 * without tampering with the cwnd.
10691 		 */
10692 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10693 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10694 		bbr_set_state_target(bbr, __LINE__);
10695 		if (bbr_prtt_slam_cwnd &&
10696 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10697 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10698 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10699 		}
10700 	}
10701 	if (ctf_flight_size(bbr->rc_tp,
10702 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10703 	    bbr->r_ctl.rc_target_at_state) {
10704 		/* We are at target */
10705 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10706 	} else {
10707 		/* We need to come down to reach target before our time begins */
10708 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10709 	}
10710 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10711 	BBR_STAT_INC(bbr_enter_probertt);
10712 	bbr_log_exit_gain(bbr, cts, 0);
10713 	bbr_log_type_statechange(bbr, cts, line);
10714 }
10715 
10716 static void
10717 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10718 {
10719 	/*
10720 	 * Sanity check on probe-rtt intervals.
10721 	 * In crazy situations where we are competing
10722 	 * against new-reno flows with huge buffers
10723 	 * our rtt-prop interval could come to dominate
10724 	 * things if we can't get through a full set
10725 	 * of cycles, we need to adjust it.
10726 	 */
10727 	if (bbr_can_adjust_probertt &&
10728 	    (bbr->rc_use_google == 0)) {
10729 		uint16_t val = 0;
10730 		uint32_t cur_rttp, fval, newval, baseval;
10731 
10732 		/* Are we to small and go into probe-rtt to often? */
10733 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10734 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10735 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10736 		if (bbr_is_ratio == 0) {
10737 			if (fval > bbr_rtt_probe_limit)
10738 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10739 			else
10740 				newval = cur_rttp;
10741 		} else {
10742 			int mul;
10743 
10744 			mul = fval / bbr_rtt_probe_limit;
10745 			newval = cur_rttp * mul;
10746 		}
10747 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10748 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10749 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10750 			val = 1;
10751 		} else {
10752 			/*
10753 			 * No adjustments were made
10754 			 * do we need to shrink it?
10755 			 */
10756 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10757 				if (cur_rttp <= bbr_rtt_probe_limit) {
10758 					/*
10759 					 * Things have calmed down lets
10760 					 * shrink all the way to default
10761 					 */
10762 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10763 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10764 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10765 					cur_rttp = bbr_rtt_probe_limit;
10766 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10767 					val = 2;
10768 				} else {
10769 					/*
10770 					 * Well does some adjustment make sense?
10771 					 */
10772 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10773 						/* We can reduce interval time some */
10774 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10775 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10776 						val = 3;
10777 					}
10778 				}
10779 			}
10780 		}
10781 		if (val)
10782 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10783 	}
10784 }
10785 
10786 static void
10787 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10788 {
10789 	/* Exit probe-rtt */
10790 
10791 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10792 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10793 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10794 	}
10795 	bbr_log_exit_gain(bbr, cts, 1);
10796 	bbr->rc_hit_state_1 = 0;
10797 	bbr->r_ctl.rc_rtt_shrinks = cts;
10798 	bbr->r_ctl.last_in_probertt = cts;
10799 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10800 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10801 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10802 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10803 					  bbr->r_ctl.rc_delivered);
10804 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10805 		uint32_t time_in;
10806 
10807 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10808 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10809 	}
10810 	if (bbr->rc_filled_pipe) {
10811 		/* Switch to probe_bw */
10812 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10813 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10814 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10815 		bbr_substate_change(bbr, cts, __LINE__, 0);
10816 		bbr_log_type_statechange(bbr, cts, __LINE__);
10817 	} else {
10818 		/* Back to startup */
10819 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10820 		bbr->r_ctl.rc_bbr_state_time = cts;
10821 		/*
10822 		 * We don't want to give a complete free 3
10823 		 * measurements until we exit, so we use
10824 		 * the number of pe's we were in probe-rtt
10825 		 * to add to the startup_epoch. That way
10826 		 * we will still retain the old state.
10827 		 */
10828 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10829 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10830 		/* Make sure to use the lower pg when shifting back in */
10831 		if (bbr->r_ctl.rc_lost &&
10832 		    bbr_use_lower_gain_in_startup &&
10833 		    (bbr->rc_use_google == 0))
10834 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10835 		else
10836 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10837 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10838 		/* Probably not needed but set it anyway */
10839 		bbr_set_state_target(bbr, __LINE__);
10840 		bbr_log_type_statechange(bbr, cts, __LINE__);
10841 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10842 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10843 	}
10844 	bbr_check_probe_rtt_limits(bbr, cts);
10845 }
10846 
10847 static int32_t inline
10848 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10849 {
10850 	if ((bbr->rc_past_init_win == 1) &&
10851 	    (bbr->rc_in_persist == 0) &&
10852 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10853 		return (1);
10854 	}
10855 	if (bbr_can_force_probertt &&
10856 	    (bbr->rc_in_persist == 0) &&
10857 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10858 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10859 		return (1);
10860 	}
10861 	return (0);
10862 }
10863 
10864 static int32_t
10865 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10866 {
10867 	uint64_t btlbw, gain;
10868 	if (pkt_epoch == 0) {
10869 		/*
10870 		 * Need to be on a pkt-epoch to continue.
10871 		 */
10872 		return (0);
10873 	}
10874 	btlbw = bbr_get_full_bw(bbr);
10875 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10876 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10877 	if (btlbw >= gain) {
10878 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10879 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10880 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10881 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10882 	}
10883 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10884 		return (1);
10885 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10886 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10887 	return(0);
10888 }
10889 
10890 static int32_t inline
10891 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10892 {
10893 	/* Have we gained 25% in the last 3 packet based epoch's? */
10894 	uint64_t btlbw, gain;
10895 	int do_exit;
10896 	int delta, rtt_gain;
10897 
10898 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10899 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10900 		/*
10901 		 * This qualifies as a RTT_PROBE session since we drop the
10902 		 * data outstanding to nothing and waited more than
10903 		 * bbr_rtt_probe_time.
10904 		 */
10905 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10906 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10907 	}
10908 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10909 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10910 		return (0);
10911 	}
10912 	if (bbr->rc_use_google)
10913 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10914 
10915 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10916 	    (bbr_use_lower_gain_in_startup)) {
10917 		/* Drop to a lower gain 1.5 x since we saw loss */
10918 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10919 	}
10920 	if (pkt_epoch == 0) {
10921 		/*
10922 		 * Need to be on a pkt-epoch to continue.
10923 		 */
10924 		return (0);
10925 	}
10926 	if (bbr_rtt_gain_thresh) {
10927 		/*
10928 		 * Do we allow a flow to stay
10929 		 * in startup with no loss and no
10930 		 * gain in rtt over a set threshold?
10931 		 */
10932 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
10933 		    bbr->r_ctl.startup_last_srtt &&
10934 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
10935 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
10936 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
10937 		} else
10938 			rtt_gain = 0;
10939 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
10940 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
10941 			/* First time or new lower value */
10942 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
10943 
10944 		if ((bbr->r_ctl.rc_lost == 0) &&
10945 		    (rtt_gain < bbr_rtt_gain_thresh)) {
10946 			/*
10947 			 * No loss, and we are under
10948 			 * our gain threhold for
10949 			 * increasing RTT.
10950 			 */
10951 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10952 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
10953 			bbr_log_startup_event(bbr, cts, rtt_gain,
10954 					      delta, bbr->r_ctl.startup_last_srtt, 10);
10955 			return (0);
10956 		}
10957 	}
10958 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
10959 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
10960 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
10961 		/*
10962 		 * We only assess if we have a new measurement when
10963 		 * we have no loss and are not in recovery.
10964 		 * Drag up by one our last_startup epoch so we will hold
10965 		 * the number of non-gain we have already accumulated.
10966 		 */
10967 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10968 			bbr->r_ctl.rc_bbr_last_startup_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, 9);
10971 		return (0);
10972 	}
10973 	/* Case where we reduced the lost (bad retransmit) */
10974 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
10975 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10976 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
10977 	btlbw = bbr_get_full_bw(bbr);
10978 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
10979 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10980 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10981 	else
10982 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10983 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10984 	do_exit = 0;
10985 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
10986 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10987 	if (btlbw >= gain) {
10988 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10989 		/* Update the lost so we won't exit in next set of tests */
10990 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10991 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10992 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10993 	}
10994 	if ((bbr->rc_loss_exit &&
10995 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10996 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
10997 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
10998 		/*
10999 		 * If we had no gain,  we had loss and that loss was above
11000 		 * our threshould, the rwnd is not constrained, and we have
11001 		 * had at least 3 packet epochs exit. Note that this is
11002 		 * switched off by sysctl. Google does not do this by the
11003 		 * way.
11004 		 */
11005 		if ((ctf_flight_size(bbr->rc_tp,
11006 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11007 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11008 			do_exit = 1;
11009 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11010 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11011 		} else {
11012 			/* Just record an updated loss value */
11013 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11014 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11015 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11016 		}
11017 	} else
11018 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11019 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11020 	    do_exit) {
11021 		/* Return 1 to exit the startup state. */
11022 		return (1);
11023 	}
11024 	/* Stay in startup */
11025 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11026 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11027 	return (0);
11028 }
11029 
11030 static void
11031 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11032 {
11033 	/*
11034 	 * A tick occurred in the rtt epoch do we need to do anything?
11035 	 */
11036 #ifdef BBR_INVARIANTS
11037 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11038 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11039 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11040 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11041 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11042 		/* Debug code? */
11043 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11044 	}
11045 #endif
11046 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11047 		/* Do we exit the startup state? */
11048 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11049 			uint32_t time_in;
11050 
11051 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11052 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11053 			bbr->rc_filled_pipe = 1;
11054 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11055 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11056 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11057 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11058 			} else
11059 				time_in = 0;
11060 			if (bbr->rc_no_pacing)
11061 				bbr->rc_no_pacing = 0;
11062 			bbr->r_ctl.rc_bbr_state_time = cts;
11063 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11064 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11065 			bbr_set_state_target(bbr, __LINE__);
11066 			if ((bbr->rc_use_google == 0) &&
11067 			    bbr_slam_cwnd_in_main_drain) {
11068 				/* Here we don't have to worry about probe-rtt */
11069 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11070 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11071 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11072 			}
11073 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11074 			bbr_log_type_statechange(bbr, cts, __LINE__);
11075 			if (ctf_flight_size(bbr->rc_tp,
11076 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11077 			    bbr->r_ctl.rc_target_at_state) {
11078 				/*
11079 				 * Switch to probe_bw if we are already
11080 				 * there
11081 				 */
11082 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11083 				bbr_substate_change(bbr, cts, __LINE__, 0);
11084 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11085 				bbr_log_type_statechange(bbr, cts, __LINE__);
11086 			}
11087 		}
11088 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11089 		uint32_t inflight;
11090 		struct tcpcb *tp;
11091 
11092 		tp = bbr->rc_tp;
11093 		inflight = ctf_flight_size(tp,
11094 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11095 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11096 			/* We have reached a flight of the cwnd target */
11097 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11098 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11099 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11100 			bbr_set_state_target(bbr, __LINE__);
11101 			/*
11102 			 * Rig it so we don't do anything crazy and
11103 			 * start fresh with a new randomization.
11104 			 */
11105 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11106 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11107 			bbr_substate_change(bbr, cts, __LINE__, 1);
11108 		}
11109 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11110 		/* Has in-flight reached the bdp (or less)? */
11111 		uint32_t inflight;
11112 		struct tcpcb *tp;
11113 
11114 		tp = bbr->rc_tp;
11115 		inflight = ctf_flight_size(tp,
11116 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11117 		if ((bbr->rc_use_google == 0) &&
11118 		    bbr_slam_cwnd_in_main_drain &&
11119 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11120 			/*
11121 			 * Here we don't have to worry about probe-rtt
11122 			 * re-slam it, but keep it slammed down.
11123 			 */
11124 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11125 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11126 		}
11127 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11128 			/* We have drained */
11129 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11130 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11131 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11132 				uint32_t time_in;
11133 
11134 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11135 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11136 			}
11137 			if ((bbr->rc_use_google == 0) &&
11138 			    bbr_slam_cwnd_in_main_drain &&
11139 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11140 				/* Restore the cwnd */
11141 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11142 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11143 			}
11144 			/* Setup probe-rtt has being done now RRS-HERE */
11145 			bbr->r_ctl.rc_rtt_shrinks = cts;
11146 			bbr->r_ctl.last_in_probertt = cts;
11147 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11148 			/* Randomly pick a sub-state */
11149 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11150 			bbr_substate_change(bbr, cts, __LINE__, 0);
11151 			bbr_log_type_statechange(bbr, cts, __LINE__);
11152 		}
11153 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11154 		uint32_t flight;
11155 
11156 		flight = ctf_flight_size(bbr->rc_tp,
11157 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11158 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11159 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11160 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11161 			/*
11162 			 * We must keep cwnd at the desired MSS.
11163 			 */
11164 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11165 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11166 		} else if ((bbr_prtt_slam_cwnd) &&
11167 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11168 			/* Re-slam it */
11169 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11170 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11171 		}
11172 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11173 			/* Has outstanding reached our target? */
11174 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11175 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11176 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11177 				/* If time is exactly 0, be 1usec off */
11178 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11179 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11180 				if (bbr->rc_use_google == 0) {
11181 					/*
11182 					 * Restore any lowering that as occurred to
11183 					 * reach here
11184 					 */
11185 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11186 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11187 					else
11188 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11189 				}
11190 			}
11191 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11192 			    (bbr->rc_use_google == 0) &&
11193 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11194 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11195 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11196 				/*
11197 				 * We have doddled with our current hptsi
11198 				 * gain an srtt and have still not made it
11199 				 * to target, or we have increased our flight.
11200 				 * Lets reduce the gain by xx%
11201 				 * flooring the reduce at DRAIN (based on
11202 				 * mul/div)
11203 				 */
11204 				int red;
11205 
11206 				bbr->r_ctl.flightsize_at_drain = flight;
11207 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11208 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11209 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11210 					/* Reduce our gain again */
11211 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11212 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11213 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11214 					/* one more chance before we give up */
11215 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11216 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11217 				} else {
11218 					/* At the very bottom */
11219 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11220 				}
11221 			}
11222 		}
11223 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11224 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11225 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11226 			/* Time to exit probe RTT normally */
11227 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11228 		}
11229 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11230 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11231 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11232 			/*
11233 			 * This qualifies as a RTT_PROBE session since we
11234 			 * drop the data outstanding to nothing and waited
11235 			 * more than bbr_rtt_probe_time.
11236 			 */
11237 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11238 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11239 		}
11240 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11241 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11242 		} else {
11243 			bbr_set_probebw_gains(bbr, cts, losses);
11244 		}
11245 	}
11246 }
11247 
11248 static void
11249 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11250 {
11251 	int32_t epoch = 0;
11252 
11253 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11254 		bbr_set_epoch(bbr, cts, line);
11255 		/* At each epoch doe lt bw sampling */
11256 		epoch = 1;
11257 	}
11258 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11259 }
11260 
11261 static int
11262 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11263     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11264     int32_t nxt_pkt, struct timeval *tv)
11265 {
11266 	struct inpcb *inp = tptoinpcb(tp);
11267 	int32_t thflags, retval;
11268 	uint32_t cts, lcts;
11269 	uint32_t tiwin;
11270 	struct tcpopt to;
11271 	struct tcp_bbr *bbr;
11272 	struct bbr_sendmap *rsm;
11273 	struct timeval ltv;
11274 	int32_t did_out = 0;
11275 	uint16_t nsegs;
11276 	int32_t prev_state;
11277 	uint32_t lost;
11278 
11279 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11280 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11281 	/* add in our stats */
11282 	kern_prefetch(bbr, &prev_state);
11283 	prev_state = 0;
11284 	thflags = tcp_get_flags(th);
11285 	/*
11286 	 * If this is either a state-changing packet or current state isn't
11287 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11288 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11289 	 * caller may have unnecessarily acquired a write lock due to a
11290 	 * race.
11291 	 */
11292 	INP_WLOCK_ASSERT(tptoinpcb(tp));
11293 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11294 	    __func__));
11295 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11296 	    __func__));
11297 
11298 	tp->t_rcvtime = ticks;
11299 	/*
11300 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11301 	 * the scale is zero.
11302 	 */
11303 	tiwin = th->th_win << tp->snd_scale;
11304 #ifdef STATS
11305 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11306 #endif
11307 
11308 	if (m->m_flags & M_TSTMP) {
11309 		/* Prefer the hardware timestamp if present */
11310 		struct timespec ts;
11311 
11312 		mbuf_tstmp2timespec(m, &ts);
11313 		bbr->rc_tv.tv_sec = ts.tv_sec;
11314 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11315 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11316 	} else if (m->m_flags & M_TSTMP_LRO) {
11317 		/* Next the arrival timestamp */
11318 		struct timespec ts;
11319 
11320 		mbuf_tstmp2timespec(m, &ts);
11321 		bbr->rc_tv.tv_sec = ts.tv_sec;
11322 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11323 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11324 	} else {
11325 		/*
11326 		 * Ok just get the current time.
11327 		 */
11328 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11329 	}
11330 	/*
11331 	 * Parse options on any incoming segment.
11332 	 */
11333 	tcp_dooptions(&to, (u_char *)(th + 1),
11334 	    (th->th_off << 2) - sizeof(struct tcphdr),
11335 	    (thflags & TH_SYN) ? TO_SYN : 0);
11336 
11337 	/*
11338 	 * If timestamps were negotiated during SYN/ACK and a
11339 	 * segment without a timestamp is received, silently drop
11340 	 * the segment, unless it is a RST segment or missing timestamps are
11341 	 * tolerated.
11342 	 * See section 3.2 of RFC 7323.
11343 	 */
11344 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11345 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11346 		retval = 0;
11347 		m_freem(m);
11348 		goto done_with_input;
11349 	}
11350 	/*
11351 	 * If echoed timestamp is later than the current time, fall back to
11352 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11353 	 * were used when this connection was established.
11354 	 */
11355 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11356 		to.to_tsecr -= tp->ts_offset;
11357 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11358 			to.to_tsecr = 0;
11359 	}
11360 	/*
11361 	 * If its the first time in we need to take care of options and
11362 	 * verify we can do SACK for rack!
11363 	 */
11364 	if (bbr->r_state == 0) {
11365 		/*
11366 		 * Process options only when we get SYN/ACK back. The SYN
11367 		 * case for incoming connections is handled in tcp_syncache.
11368 		 * According to RFC1323 the window field in a SYN (i.e., a
11369 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11370 		 * this is traditional behavior, may need to be cleaned up.
11371 		 */
11372 		if (bbr->rc_inp == NULL) {
11373 			bbr->rc_inp = inp;
11374 		}
11375 		/*
11376 		 * We need to init rc_inp here since its not init'd when
11377 		 * bbr_init is called
11378 		 */
11379 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11380 			if ((to.to_flags & TOF_SCALE) &&
11381 			    (tp->t_flags & TF_REQ_SCALE)) {
11382 				tp->t_flags |= TF_RCVD_SCALE;
11383 				tp->snd_scale = to.to_wscale;
11384 			} else
11385 				tp->t_flags &= ~TF_REQ_SCALE;
11386 			/*
11387 			 * Initial send window.  It will be updated with the
11388 			 * next incoming segment to the scaled value.
11389 			 */
11390 			tp->snd_wnd = th->th_win;
11391 			if ((to.to_flags & TOF_TS) &&
11392 			    (tp->t_flags & TF_REQ_TSTMP)) {
11393 				tp->t_flags |= TF_RCVD_TSTMP;
11394 				tp->ts_recent = to.to_tsval;
11395 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11396 			} else
11397 			    tp->t_flags &= ~TF_REQ_TSTMP;
11398 			if (to.to_flags & TOF_MSS)
11399 				tcp_mss(tp, to.to_mss);
11400 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11401 			    (to.to_flags & TOF_SACKPERM) == 0)
11402 				tp->t_flags &= ~TF_SACK_PERMIT;
11403 			if (IS_FASTOPEN(tp->t_flags)) {
11404 				if (to.to_flags & TOF_FASTOPEN) {
11405 					uint16_t mss;
11406 
11407 					if (to.to_flags & TOF_MSS)
11408 						mss = to.to_mss;
11409 					else
11410 						if ((inp->inp_vflag & INP_IPV6) != 0)
11411 							mss = TCP6_MSS;
11412 						else
11413 							mss = TCP_MSS;
11414 					tcp_fastopen_update_cache(tp, mss,
11415 					    to.to_tfo_len, to.to_tfo_cookie);
11416 				} else
11417 					tcp_fastopen_disable_path(tp);
11418 			}
11419 		}
11420 		/*
11421 		 * At this point we are at the initial call. Here we decide
11422 		 * if we are doing RACK or not. We do this by seeing if
11423 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11424 		 * we switch to the default code.
11425 		 */
11426 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11427 			/* Bail */
11428 			tcp_switch_back_to_default(tp);
11429 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11430 			    tlen, iptos);
11431 			return (1);
11432 		}
11433 		/* Set the flag */
11434 		bbr->r_is_v6 = (inp->inp_vflag & INP_IPV6) != 0;
11435 		tcp_set_hpts(inp);
11436 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11437 	}
11438 	if (thflags & TH_ACK) {
11439 		/* Track ack types */
11440 		if (to.to_flags & TOF_SACK)
11441 			BBR_STAT_INC(bbr_acks_with_sacks);
11442 		else
11443 			BBR_STAT_INC(bbr_plain_acks);
11444 	}
11445 	/*
11446 	 * This is the one exception case where we set the rack state
11447 	 * always. All other times (timers etc) we must have a rack-state
11448 	 * set (so we assure we have done the checks above for SACK).
11449 	 */
11450 	if (thflags & TH_FIN)
11451 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11452 	if (bbr->r_state != tp->t_state)
11453 		bbr_set_state(tp, bbr, tiwin);
11454 
11455 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11456 		kern_prefetch(rsm, &prev_state);
11457 	prev_state = bbr->r_state;
11458 	bbr->rc_ack_was_delayed = 0;
11459 	lost = bbr->r_ctl.rc_lost;
11460 	bbr->rc_is_pkt_epoch_now = 0;
11461 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11462 		/* Get the real time into lcts and figure the real delay */
11463 		lcts = tcp_get_usecs(&ltv);
11464 		if (TSTMP_GT(lcts, cts)) {
11465 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11466 			bbr->rc_ack_was_delayed = 1;
11467 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11468 				     bbr->r_ctl.highest_hdwr_delay))
11469 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11470 		} else {
11471 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11472 			bbr->rc_ack_was_delayed = 0;
11473 		}
11474 	} else {
11475 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11476 		bbr->rc_ack_was_delayed = 0;
11477 	}
11478 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11479 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11480 		retval = 0;
11481 		m_freem(m);
11482 		goto done_with_input;
11483 	}
11484 	/*
11485 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11486 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11487 	 */
11488 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11489 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11490 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11491 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11492 		return (1);
11493 	}
11494 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11495 		bbr->r_ctl.rc_high_rwnd = tiwin;
11496 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11497 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11498 	bbr->rtt_valid = 0;
11499 	if (to.to_flags & TOF_TS) {
11500 		bbr->rc_ts_valid = 1;
11501 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11502 	} else {
11503 		bbr->rc_ts_valid = 0;
11504 		bbr->r_ctl.last_inbound_ts = 0;
11505 	}
11506 	retval = (*bbr->r_substate) (m, th, so,
11507 	    tp, &to, drop_hdrlen,
11508 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11509 	if (nxt_pkt == 0)
11510 		BBR_STAT_INC(bbr_rlock_left_ret0);
11511 	else
11512 		BBR_STAT_INC(bbr_rlock_left_ret1);
11513 	if (retval == 0) {
11514 		/*
11515 		 * If retval is 1 the tcb is unlocked and most likely the tp
11516 		 * is gone.
11517 		 */
11518 		INP_WLOCK_ASSERT(inp);
11519 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11520 		if (bbr->rc_is_pkt_epoch_now)
11521 			bbr_set_pktepoch(bbr, cts, __LINE__);
11522 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11523 		if (nxt_pkt == 0) {
11524 			if (bbr->r_wanted_output != 0) {
11525 				bbr->rc_output_starts_timer = 0;
11526 				did_out = 1;
11527 				if (tcp_output(tp) < 0)
11528 					return (1);
11529 			} else
11530 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11531 		}
11532 		if ((nxt_pkt == 0) &&
11533 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11534 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11535 		     (tp->t_flags & TF_DELACK) ||
11536 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11537 		      (tp->t_state <= TCPS_CLOSING)))) {
11538 			/*
11539 			 * We could not send (probably in the hpts but
11540 			 * stopped the timer)?
11541 			 */
11542 			if ((tp->snd_max == tp->snd_una) &&
11543 			    ((tp->t_flags & TF_DELACK) == 0) &&
11544 			    (tcp_in_hpts(bbr->rc_inp)) &&
11545 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11546 				/*
11547 				 * keep alive not needed if we are hptsi
11548 				 * output yet
11549 				 */
11550 				;
11551 			} else {
11552 				if (tcp_in_hpts(bbr->rc_inp)) {
11553 					tcp_hpts_remove(bbr->rc_inp);
11554 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11555 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11556 						uint32_t del;
11557 
11558 						del = lcts - bbr->rc_pacer_started;
11559 						if (bbr->r_ctl.rc_last_delay_val > del) {
11560 							BBR_STAT_INC(bbr_force_timer_start);
11561 							bbr->r_ctl.rc_last_delay_val -= del;
11562 							bbr->rc_pacer_started = lcts;
11563 						} else {
11564 							/* We are late */
11565 							bbr->r_ctl.rc_last_delay_val = 0;
11566 							BBR_STAT_INC(bbr_force_output);
11567 							if (tcp_output(tp) < 0)
11568 								return (1);
11569 						}
11570 					}
11571 				}
11572 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11573 				    0);
11574 			}
11575 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11576 			/* Do we have the correct timer running? */
11577 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11578 		}
11579 		/* Do we have a new state */
11580 		if (bbr->r_state != tp->t_state)
11581 			bbr_set_state(tp, bbr, tiwin);
11582 done_with_input:
11583 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11584 		if (did_out)
11585 			bbr->r_wanted_output = 0;
11586 	}
11587 	return (retval);
11588 }
11589 
11590 static void
11591 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11592     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11593 {
11594 	struct timeval tv;
11595 	int retval;
11596 
11597 	/* First lets see if we have old packets */
11598 	if (tp->t_in_pkt) {
11599 		if (ctf_do_queued_segments(so, tp, 1)) {
11600 			m_freem(m);
11601 			return;
11602 		}
11603 	}
11604 	if (m->m_flags & M_TSTMP_LRO) {
11605 		mbuf_tstmp2timeval(m, &tv);
11606 	} else {
11607 		/* Should not be should we kassert instead? */
11608 		tcp_get_usecs(&tv);
11609 	}
11610 	retval = bbr_do_segment_nounlock(m, th, so, tp,
11611 					 drop_hdrlen, tlen, iptos, 0, &tv);
11612 	if (retval == 0) {
11613 		INP_WUNLOCK(tptoinpcb(tp));
11614 	}
11615 }
11616 
11617 /*
11618  * Return how much data can be sent without violating the
11619  * cwnd or rwnd.
11620  */
11621 
11622 static inline uint32_t
11623 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11624     uint32_t avail, int32_t sb_offset, uint32_t cts)
11625 {
11626 	uint32_t len;
11627 
11628 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11629 		/* We never want to go over our peers rcv-window */
11630 		len = 0;
11631 	} else {
11632 		uint32_t flight;
11633 
11634 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11635 		if (flight >= sendwin) {
11636 			/*
11637 			 * We have in flight what we are allowed by cwnd (if
11638 			 * it was rwnd blocking it would have hit above out
11639 			 * >= tp->snd_wnd).
11640 			 */
11641 			return (0);
11642 		}
11643 		len = sendwin - flight;
11644 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11645 			/* We would send too much (beyond the rwnd) */
11646 			len = tp->snd_wnd - ctf_outstanding(tp);
11647 		}
11648 		if ((len + sb_offset) > avail) {
11649 			/*
11650 			 * We don't have that much in the SB, how much is
11651 			 * there?
11652 			 */
11653 			len = avail - sb_offset;
11654 		}
11655 	}
11656 	return (len);
11657 }
11658 
11659 static inline void
11660 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11661 {
11662 #ifdef NETFLIX_STATS
11663 	KMOD_TCPSTAT_INC(tcps_sndpack_error);
11664 	KMOD_TCPSTAT_ADD(tcps_sndbyte_error, len);
11665 #endif
11666 }
11667 
11668 static inline void
11669 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11670 {
11671 	if (error) {
11672 		bbr_do_error_accounting(tp, bbr, rsm, len, error);
11673 		return;
11674 	}
11675 	if (rsm) {
11676 		if (rsm->r_flags & BBR_TLP) {
11677 			/*
11678 			 * TLP should not count in retran count, but in its
11679 			 * own bin
11680 			 */
11681 #ifdef NETFLIX_STATS
11682 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11683 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11684 #endif
11685 		} else {
11686 			/* Retransmit */
11687 			tp->t_sndrexmitpack++;
11688 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11689 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11690 #ifdef STATS
11691 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11692 			    len);
11693 #endif
11694 		}
11695 		/*
11696 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11697 		 * sub-state
11698 		 */
11699 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11700 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11701 			/* Non probe_bw log in 1, 2, or 4. */
11702 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11703 		} else {
11704 			/*
11705 			 * Log our probe state 3, and log also 5-13 to show
11706 			 * us the recovery sub-state for the send. This
11707 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11708 			 */
11709 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11710 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11711 		}
11712 		/* Place in both 16's the totals of retransmitted */
11713 		counter_u64_add(bbr_state_lost[16], len);
11714 		counter_u64_add(bbr_state_resend[16], len);
11715 		/* Place in 17's the total sent */
11716 		counter_u64_add(bbr_state_resend[17], len);
11717 		counter_u64_add(bbr_state_lost[17], len);
11718 
11719 	} else {
11720 		/* New sends */
11721 		KMOD_TCPSTAT_INC(tcps_sndpack);
11722 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11723 		/* Place in 17's the total sent */
11724 		counter_u64_add(bbr_state_resend[17], len);
11725 		counter_u64_add(bbr_state_lost[17], len);
11726 #ifdef STATS
11727 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11728 		    len);
11729 #endif
11730 	}
11731 }
11732 
11733 static void
11734 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11735 {
11736 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11737 		/*
11738 		 * Limit the cwnd to not be above N x the target plus whats
11739 		 * is outstanding. The target is based on the current b/w
11740 		 * estimate.
11741 		 */
11742 		uint32_t target;
11743 
11744 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11745 		target += ctf_outstanding(tp);
11746 		target *= bbr_target_cwnd_mult_limit;
11747 		if (tp->snd_cwnd > target)
11748 			tp->snd_cwnd = target;
11749 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11750 	}
11751 }
11752 
11753 static int
11754 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11755 {
11756 	/*
11757 	 * "adv" is the amount we could increase the window, taking into
11758 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11759 	 */
11760 	int32_t adv;
11761 	int32_t oldwin;
11762 
11763 	adv = recwin;
11764 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11765 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11766 		if (adv > oldwin)
11767 			adv -= oldwin;
11768 		else {
11769 			/* We can't increase the window */
11770 			adv = 0;
11771 		}
11772 	} else
11773 		oldwin = 0;
11774 
11775 	/*
11776 	 * If the new window size ends up being the same as or less
11777 	 * than the old size when it is scaled, then don't force
11778 	 * a window update.
11779 	 */
11780 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11781 		return (0);
11782 
11783 	if (adv >= (2 * maxseg) &&
11784 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11785 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11786 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11787 		return (1);
11788 	}
11789 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11790 		return (1);
11791 	return (0);
11792 }
11793 
11794 /*
11795  * Return 0 on success and a errno on failure to send.
11796  * Note that a 0 return may not mean we sent anything
11797  * if the TCB was on the hpts. A non-zero return
11798  * does indicate the error we got from ip[6]_output.
11799  */
11800 static int
11801 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11802 {
11803 	struct socket *so;
11804 	int32_t len;
11805 	uint32_t cts;
11806 	uint32_t recwin, sendwin;
11807 	int32_t sb_offset;
11808 	int32_t flags, abandon, error = 0;
11809 	struct tcp_log_buffer *lgb = NULL;
11810 	struct mbuf *m;
11811 	struct mbuf *mb;
11812 	uint32_t if_hw_tsomaxsegcount = 0;
11813 	uint32_t if_hw_tsomaxsegsize = 0;
11814 	uint32_t if_hw_tsomax = 0;
11815 	struct ip *ip = NULL;
11816 	struct tcp_bbr *bbr;
11817 	struct tcphdr *th;
11818 	struct udphdr *udp = NULL;
11819 	u_char opt[TCP_MAXOLEN];
11820 	unsigned ipoptlen, optlen, hdrlen;
11821 	unsigned ulen;
11822 	uint32_t bbr_seq;
11823 	uint32_t delay_calc=0;
11824 	uint8_t doing_tlp = 0;
11825 	uint8_t local_options;
11826 #ifdef BBR_INVARIANTS
11827 	uint8_t doing_retran_from = 0;
11828 	uint8_t picked_up_retran = 0;
11829 #endif
11830 	uint8_t wanted_cookie = 0;
11831 	uint8_t more_to_rxt=0;
11832 	int32_t prefetch_so_done = 0;
11833 	int32_t prefetch_rsm = 0;
11834 	uint32_t tot_len = 0;
11835 	uint32_t maxseg, pace_max_segs, p_maxseg;
11836 	int32_t csum_flags = 0;
11837  	int32_t hw_tls;
11838 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11839 	unsigned ipsec_optlen = 0;
11840 
11841 #endif
11842 	volatile int32_t sack_rxmit;
11843 	struct bbr_sendmap *rsm = NULL;
11844 	int32_t tso, mtu;
11845 	struct tcpopt to;
11846 	int32_t slot = 0;
11847 	struct inpcb *inp;
11848 	struct sockbuf *sb;
11849 	uint32_t hpts_calling;
11850 #ifdef INET6
11851 	struct ip6_hdr *ip6 = NULL;
11852 	int32_t isipv6;
11853 #endif
11854 	uint8_t app_limited = BBR_JR_SENT_DATA;
11855 	uint8_t filled_all = 0;
11856 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11857 	/* We take a cache hit here */
11858 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11859 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11860 	inp = bbr->rc_inp;
11861 	so = inp->inp_socket;
11862 	sb = &so->so_snd;
11863  	if (sb->sb_flags & SB_TLS_IFNET)
11864  		hw_tls = 1;
11865  	else
11866  		hw_tls = 0;
11867 	kern_prefetch(sb, &maxseg);
11868 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11869 	if (bbr_minseg(bbr) < maxseg) {
11870 		tcp_bbr_tso_size_check(bbr, cts);
11871 	}
11872 	/* Remove any flags that indicate we are pacing on the inp  */
11873 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11874 	p_maxseg = min(maxseg, pace_max_segs);
11875 	INP_WLOCK_ASSERT(inp);
11876 #ifdef TCP_OFFLOAD
11877 	if (tp->t_flags & TF_TOE)
11878 		return (tcp_offload_output(tp));
11879 #endif
11880 
11881 #ifdef INET6
11882 	if (bbr->r_state) {
11883 		/* Use the cache line loaded if possible */
11884 		isipv6 = bbr->r_is_v6;
11885 	} else {
11886 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11887 	}
11888 #endif
11889 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11890 	    tcp_in_hpts(inp)) {
11891 		/*
11892 		 * We are on the hpts for some timer but not hptsi output.
11893 		 * Possibly remove from the hpts so we can send/recv etc.
11894 		 */
11895 		if ((tp->t_flags & TF_ACKNOW) == 0) {
11896 			/*
11897 			 * No immediate demand right now to send an ack, but
11898 			 * the user may have read, making room for new data
11899 			 * (a window update). If so we may want to cancel
11900 			 * whatever timer is running (KEEP/DEL-ACK?) and
11901 			 * continue to send out a window update. Or we may
11902 			 * have gotten more data into the socket buffer to
11903 			 * send.
11904 			 */
11905 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
11906 				      (long)TCP_MAXWIN << tp->rcv_scale);
11907 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
11908 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
11909 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
11910 			    (tp->snd_max - tp->snd_una))) {
11911 				/*
11912 				 * Nothing new to send and no window update
11913 				 * is needed to send. Lets just return and
11914 				 * let the timer-run off.
11915 				 */
11916 				return (0);
11917 			}
11918 		}
11919 		tcp_hpts_remove(inp);
11920 		bbr_timer_cancel(bbr, __LINE__, cts);
11921 	}
11922 	if (bbr->r_ctl.rc_last_delay_val) {
11923 		/* Calculate a rough delay for early escape to sending  */
11924 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11925 			delay_calc = cts - bbr->rc_pacer_started;
11926 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11927 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11928 		else
11929 			delay_calc = 0;
11930 	}
11931 	/* Mark that we have called bbr_output(). */
11932 	if ((bbr->r_timer_override) ||
11933 	    (tp->t_state < TCPS_ESTABLISHED)) {
11934 		/* Timeouts or early states are exempt */
11935 		if (tcp_in_hpts(inp))
11936 			tcp_hpts_remove(inp);
11937 	} else if (tcp_in_hpts(inp)) {
11938 		if ((bbr->r_ctl.rc_last_delay_val) &&
11939 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11940 		    delay_calc) {
11941 			/*
11942 			 * We were being paced for output and the delay has
11943 			 * already exceeded when we were supposed to be
11944 			 * called, lets go ahead and pull out of the hpts
11945 			 * and call output.
11946 			 */
11947 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
11948 			bbr->r_ctl.rc_last_delay_val = 0;
11949 			tcp_hpts_remove(inp);
11950 		} else if (tp->t_state == TCPS_CLOSED) {
11951 			bbr->r_ctl.rc_last_delay_val = 0;
11952 			tcp_hpts_remove(inp);
11953 		} else {
11954 			/*
11955 			 * On the hpts, you shall not pass! even if ACKNOW
11956 			 * is on, we will when the hpts fires, unless of
11957 			 * course we are overdue.
11958 			 */
11959 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
11960 			return (0);
11961 		}
11962 	}
11963 	bbr->rc_cwnd_limited = 0;
11964 	if (bbr->r_ctl.rc_last_delay_val) {
11965 		/* recalculate the real delay and deal with over/under  */
11966 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11967 			delay_calc = cts - bbr->rc_pacer_started;
11968 		else
11969 			delay_calc = 0;
11970 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11971 			/* Setup the delay which will be added in */
11972 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11973 		else {
11974 			/*
11975 			 * We are early setup to adjust
11976 			 * our slot time.
11977 			 */
11978 			uint64_t merged_val;
11979 
11980 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
11981 			bbr->r_agg_early_set = 1;
11982 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
11983 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
11984 					/* Nope our previous late cancels out the early */
11985 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
11986 					bbr->r_agg_early_set = 0;
11987 					bbr->r_ctl.rc_agg_early = 0;
11988 				} else {
11989 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
11990 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
11991 				}
11992 			}
11993 			merged_val = bbr->rc_pacer_started;
11994 			merged_val <<= 32;
11995 			merged_val |= bbr->r_ctl.rc_last_delay_val;
11996 			bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
11997 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
11998 						 bbr->r_agg_early_set, 3);
11999 			bbr->r_ctl.rc_last_delay_val = 0;
12000 			BBR_STAT_INC(bbr_early);
12001 			delay_calc = 0;
12002 		}
12003 	} else {
12004 		/* We were not delayed due to hptsi */
12005 		if (bbr->r_agg_early_set)
12006 			bbr->r_ctl.rc_agg_early = 0;
12007 		bbr->r_agg_early_set = 0;
12008 		delay_calc = 0;
12009 	}
12010 	if (delay_calc) {
12011 		/*
12012 		 * We had a hptsi delay which means we are falling behind on
12013 		 * sending at the expected rate. Calculate an extra amount
12014 		 * of data we can send, if any, to put us back on track.
12015 		 */
12016 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12017 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12018 		else
12019 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12020 	}
12021 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12022 	if ((tp->snd_una == tp->snd_max) &&
12023 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12024 	    (sbavail(sb))) {
12025 		/*
12026 		 * Ok we have been idle with nothing outstanding
12027 		 * we possibly need to start fresh with either a new
12028 		 * suite of states or a fast-ramp up.
12029 		 */
12030 		bbr_restart_after_idle(bbr,
12031 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12032 	}
12033 	/*
12034 	 * Now was there a hptsi delay where we are behind? We only count
12035 	 * being behind if: a) We are not in recovery. b) There was a delay.
12036 	 * <and> c) We had room to send something.
12037 	 *
12038 	 */
12039 	hpts_calling = inp->inp_hpts_calls;
12040 	inp->inp_hpts_calls = 0;
12041 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12042 		int retval;
12043 
12044 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12045 		if (retval != 0) {
12046 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12047 			/*
12048 			 * If timers want tcp_drop(), then pass error out,
12049 			 * otherwise suppress it.
12050 			 */
12051 			return (retval < 0 ? retval : 0);
12052 		}
12053 	}
12054 	bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12055 	if (hpts_calling &&
12056 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12057 		bbr->r_ctl.rc_last_delay_val = 0;
12058 	}
12059 	bbr->r_timer_override = 0;
12060 	bbr->r_wanted_output = 0;
12061 	/*
12062 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12063 	 * SYN|ACK and those sent by the retransmit timer.
12064 	 */
12065 	if (IS_FASTOPEN(tp->t_flags) &&
12066 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12067 	     (tp->t_state == TCPS_SYN_SENT)) &&
12068 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12069 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12070 		len = 0;
12071 		goto just_return_nolock;
12072 	}
12073 	/*
12074 	 * Before sending anything check for a state update. For hpts
12075 	 * calling without input this is important. If its input calling
12076 	 * then this was already done.
12077 	 */
12078 	if (bbr->rc_use_google == 0)
12079 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12080 again:
12081 	/*
12082 	 * If we've recently taken a timeout, snd_max will be greater than
12083 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12084 	 * for historic reasons the persist timer still uses it. This means
12085 	 * we have to look at it. All retransmissions that are not persits
12086 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12087 	 * end of this routine we pull snd_nxt always up to snd_max.
12088 	 */
12089 	doing_tlp = 0;
12090 #ifdef BBR_INVARIANTS
12091 	doing_retran_from = picked_up_retran = 0;
12092 #endif
12093 	error = 0;
12094 	tso = 0;
12095 	slot = 0;
12096 	mtu = 0;
12097 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12098 	sb_offset = tp->snd_max - tp->snd_una;
12099 	flags = tcp_outflags[tp->t_state];
12100 	sack_rxmit = 0;
12101 	len = 0;
12102 	rsm = NULL;
12103 	if (flags & TH_RST) {
12104 		SOCKBUF_LOCK(sb);
12105 		goto send;
12106 	}
12107 recheck_resend:
12108 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12109 		/* We need to always have one in reserve */
12110 		rsm = bbr_alloc(bbr);
12111 		if (rsm == NULL) {
12112 			error = ENOMEM;
12113 			/* Lie to get on the hpts */
12114 			tot_len = tp->t_maxseg;
12115 			if (hpts_calling)
12116 				/* Retry in a ms */
12117 				slot = 1001;
12118 			goto just_return_nolock;
12119 		}
12120 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12121 		bbr->r_ctl.rc_free_cnt++;
12122 		rsm = NULL;
12123 	}
12124 	/* What do we send, a resend? */
12125 	if (bbr->r_ctl.rc_resend == NULL) {
12126 		/* Check for rack timeout */
12127 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12128 		if (bbr->r_ctl.rc_resend) {
12129 #ifdef BBR_INVARIANTS
12130 			picked_up_retran = 1;
12131 #endif
12132 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12133 		}
12134 	}
12135 	if (bbr->r_ctl.rc_resend) {
12136 		rsm = bbr->r_ctl.rc_resend;
12137 #ifdef BBR_INVARIANTS
12138 		doing_retran_from = 1;
12139 #endif
12140 		/* Remove any TLP flags its a RACK or T-O */
12141 		rsm->r_flags &= ~BBR_TLP;
12142 		bbr->r_ctl.rc_resend = NULL;
12143 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12144 #ifdef BBR_INVARIANTS
12145 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12146 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12147 			goto recheck_resend;
12148 #else
12149 			/* TSNH */
12150 			rsm = NULL;
12151 			goto recheck_resend;
12152 #endif
12153 		}
12154 		if (rsm->r_flags & BBR_HAS_SYN) {
12155 			/* Only retransmit a SYN by itself */
12156 			len = 0;
12157 			if ((flags & TH_SYN) == 0) {
12158 				/* Huh something is wrong */
12159 				rsm->r_start++;
12160 				if (rsm->r_start == rsm->r_end) {
12161 					/* Clean it up, somehow we missed the ack? */
12162 					bbr_log_syn(tp, NULL);
12163 				} else {
12164 					/* TFO with data? */
12165 					rsm->r_flags &= ~BBR_HAS_SYN;
12166 					len = rsm->r_end - rsm->r_start;
12167 				}
12168 			} else {
12169 				/* Retransmitting SYN */
12170 				rsm = NULL;
12171 				SOCKBUF_LOCK(sb);
12172 				goto send;
12173 			}
12174 		} else
12175 			len = rsm->r_end - rsm->r_start;
12176 		if ((bbr->rc_resends_use_tso == 0) &&
12177 		    (len > maxseg)) {
12178 			len = maxseg;
12179 			more_to_rxt = 1;
12180 		}
12181 		sb_offset = rsm->r_start - tp->snd_una;
12182 		if (len > 0) {
12183 			sack_rxmit = 1;
12184 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12185 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12186 			    min(len, maxseg));
12187 		} else {
12188 			/* I dont think this can happen */
12189 			rsm = NULL;
12190 			goto recheck_resend;
12191 		}
12192 		BBR_STAT_INC(bbr_resends_set);
12193 	} else if (bbr->r_ctl.rc_tlp_send) {
12194 		/*
12195 		 * Tail loss probe
12196 		 */
12197 		doing_tlp = 1;
12198 		rsm = bbr->r_ctl.rc_tlp_send;
12199 		bbr->r_ctl.rc_tlp_send = NULL;
12200 		sack_rxmit = 1;
12201 		len = rsm->r_end - rsm->r_start;
12202 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12203 			len = maxseg;
12204 
12205 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12206 #ifdef BBR_INVARIANTS
12207 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12208 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12209 #else
12210 			/* TSNH */
12211 			rsm = NULL;
12212 			goto recheck_resend;
12213 #endif
12214 		}
12215 		sb_offset = rsm->r_start - tp->snd_una;
12216 		BBR_STAT_INC(bbr_tlp_set);
12217 	}
12218 	/*
12219 	 * Enforce a connection sendmap count limit if set
12220 	 * as long as we are not retransmiting.
12221 	 */
12222 	if ((rsm == NULL) &&
12223 	    (V_tcp_map_entries_limit > 0) &&
12224 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12225 		BBR_STAT_INC(bbr_alloc_limited);
12226 		if (!bbr->alloc_limit_reported) {
12227 			bbr->alloc_limit_reported = 1;
12228 			BBR_STAT_INC(bbr_alloc_limited_conns);
12229 		}
12230 		goto just_return_nolock;
12231 	}
12232 #ifdef BBR_INVARIANTS
12233 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12234 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12235 		    tp, bbr, rsm, sb_offset, len);
12236 	}
12237 #endif
12238 	/*
12239 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12240 	 * state flags.
12241 	 */
12242 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12243 		flags |= TH_FIN;
12244 	if (tp->t_flags & TF_NEEDSYN)
12245 		flags |= TH_SYN;
12246 
12247 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12248 		/* we are retransmitting the fin */
12249 		len--;
12250 		if (len) {
12251 			/*
12252 			 * When retransmitting data do *not* include the
12253 			 * FIN. This could happen from a TLP probe if we
12254 			 * allowed data with a FIN.
12255 			 */
12256 			flags &= ~TH_FIN;
12257 		}
12258 	} else if (rsm) {
12259 		if (flags & TH_FIN)
12260 			flags &= ~TH_FIN;
12261 	}
12262 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12263 		void *end_rsm;
12264 
12265 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12266 		if (end_rsm)
12267 			kern_prefetch(end_rsm, &prefetch_rsm);
12268 		prefetch_rsm = 1;
12269 	}
12270 	SOCKBUF_LOCK(sb);
12271 	/*
12272 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12273 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12274 	 * negative length.  This can also occur when TCP opens up its
12275 	 * congestion window while receiving additional duplicate acks after
12276 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12277 	 * the fast-retransmit.
12278 	 *
12279 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12280 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12281 	 * up 0.
12282 	 *
12283 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12284 	 * in which case len is already set.
12285 	 */
12286 	if (sack_rxmit == 0) {
12287 		uint32_t avail;
12288 
12289 		avail = sbavail(sb);
12290 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12291 			sb_offset = tp->snd_max - tp->snd_una;
12292 		else
12293 			sb_offset = 0;
12294 		if (bbr->rc_tlp_new_data) {
12295 			/* TLP is forcing out new data */
12296 			uint32_t tlplen;
12297 
12298 			doing_tlp = 1;
12299 			tlplen = maxseg;
12300 
12301 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12302 				tlplen = (uint32_t)(avail - sb_offset);
12303 			}
12304 			if (tlplen > tp->snd_wnd) {
12305 				len = tp->snd_wnd;
12306 			} else {
12307 				len = tlplen;
12308 			}
12309 			bbr->rc_tlp_new_data = 0;
12310 		} else {
12311 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12312 			if ((len < p_maxseg) &&
12313 			    (bbr->rc_in_persist == 0) &&
12314 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12315 			    ((avail - sb_offset) >= p_maxseg)) {
12316 				/*
12317 				 * We are not completing whats in the socket
12318 				 * buffer (i.e. there is at least a segment
12319 				 * waiting to send) and we have 2 or more
12320 				 * segments outstanding. There is no sense
12321 				 * of sending a little piece. Lets defer and
12322 				 * and wait until we can send a whole
12323 				 * segment.
12324 				 */
12325 				len = 0;
12326 			}
12327 			if (bbr->rc_in_persist) {
12328 				/*
12329 				 * We are in persists, figure out if
12330 				 * a retransmit is available (maybe the previous
12331 				 * persists we sent) or if we have to send new
12332 				 * data.
12333 				 */
12334 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12335 				if (rsm) {
12336 					len = rsm->r_end - rsm->r_start;
12337 					if (rsm->r_flags & BBR_HAS_FIN)
12338 						len--;
12339 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12340 						len = maxseg;
12341 					if (len > 1)
12342 						BBR_STAT_INC(bbr_persist_reneg);
12343 					/*
12344 					 * XXXrrs we could force the len to
12345 					 * 1 byte here to cause the chunk to
12346 					 * split apart.. but that would then
12347 					 * mean we always retransmit it as
12348 					 * one byte even after the window
12349 					 * opens.
12350 					 */
12351 					sack_rxmit = 1;
12352 					sb_offset = rsm->r_start - tp->snd_una;
12353 				} else {
12354 					/*
12355 					 * First time through in persists or peer
12356 					 * acked our one byte. Though we do have
12357 					 * to have something in the sb.
12358 					 */
12359 					len = 1;
12360 					sb_offset = 0;
12361 					if (avail == 0)
12362 					    len = 0;
12363 				}
12364 			}
12365 		}
12366 	}
12367 	if (prefetch_so_done == 0) {
12368 		kern_prefetch(so, &prefetch_so_done);
12369 		prefetch_so_done = 1;
12370 	}
12371 	/*
12372 	 * Lop off SYN bit if it has already been sent.  However, if this is
12373 	 * SYN-SENT state and if segment contains data and if we don't know
12374 	 * that foreign host supports TAO, suppress sending segment.
12375 	 */
12376 	if ((flags & TH_SYN) && (rsm == NULL) &&
12377 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12378 		if (tp->t_state != TCPS_SYN_RECEIVED)
12379 			flags &= ~TH_SYN;
12380 		/*
12381 		 * When sending additional segments following a TFO SYN|ACK,
12382 		 * do not include the SYN bit.
12383 		 */
12384 		if (IS_FASTOPEN(tp->t_flags) &&
12385 		    (tp->t_state == TCPS_SYN_RECEIVED))
12386 			flags &= ~TH_SYN;
12387 		sb_offset--, len++;
12388 		if (sbavail(sb) == 0)
12389 			len = 0;
12390 	} else if ((flags & TH_SYN) && rsm) {
12391 		/*
12392 		 * Subtract one from the len for the SYN being
12393 		 * retransmitted.
12394 		 */
12395 		len--;
12396 	}
12397 	/*
12398 	 * Be careful not to send data and/or FIN on SYN segments. This
12399 	 * measure is needed to prevent interoperability problems with not
12400 	 * fully conformant TCP implementations.
12401 	 */
12402 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12403 		len = 0;
12404 		flags &= ~TH_FIN;
12405 	}
12406 	/*
12407 	 * On TFO sockets, ensure no data is sent in the following cases:
12408 	 *
12409 	 *  - When retransmitting SYN|ACK on a passively-created socket
12410 	 *  - When retransmitting SYN on an actively created socket
12411 	 *  - When sending a zero-length cookie (cookie request) on an
12412 	 *    actively created socket
12413 	 *  - When the socket is in the CLOSED state (RST is being sent)
12414 	 */
12415 	if (IS_FASTOPEN(tp->t_flags) &&
12416 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12417 	     ((tp->t_state == TCPS_SYN_SENT) &&
12418 	      (tp->t_tfo_client_cookie_len == 0)) ||
12419 	     (flags & TH_RST))) {
12420 		len = 0;
12421 		sack_rxmit = 0;
12422 		rsm = NULL;
12423 	}
12424 	/* Without fast-open there should never be data sent on a SYN */
12425 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12426 		len = 0;
12427 	if (len <= 0) {
12428 		/*
12429 		 * If FIN has been sent but not acked, but we haven't been
12430 		 * called to retransmit, len will be < 0.  Otherwise, window
12431 		 * shrank after we sent into it.  If window shrank to 0,
12432 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12433 		 * window, and set the persist timer if it isn't already
12434 		 * going.  If the window didn't close completely, just wait
12435 		 * for an ACK.
12436 		 *
12437 		 * We also do a general check here to ensure that we will
12438 		 * set the persist timer when we have data to send, but a
12439 		 * 0-byte window. This makes sure the persist timer is set
12440 		 * even if the packet hits one of the "goto send" lines
12441 		 * below.
12442 		 */
12443 		len = 0;
12444 		if ((tp->snd_wnd == 0) &&
12445 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12446 		    (tp->snd_una == tp->snd_max) &&
12447 		    (sb_offset < (int)sbavail(sb))) {
12448 			/*
12449 			 * Not enough room in the rwnd to send
12450 			 * a paced segment out.
12451 			 */
12452 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12453 		}
12454 	} else if ((rsm == NULL) &&
12455 		   (doing_tlp == 0) &&
12456 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12457 		/*
12458 		 * We are not sending a full segment for
12459 		 * some reason. Should we not send anything (think
12460 		 * sws or persists)?
12461 		 */
12462 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12463 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12464 		    (len < (int)(sbavail(sb) - sb_offset))) {
12465 			/*
12466 			 * Here the rwnd is less than
12467 			 * the pacing size, this is not a retransmit,
12468 			 * we are established and
12469 			 * the send is not the last in the socket buffer
12470 			 * lets not send, and possibly enter persists.
12471 			 */
12472 			len = 0;
12473 			if (tp->snd_max == tp->snd_una)
12474 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12475 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12476 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12477 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12478 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12479 			   (len < bbr_minseg(bbr))) {
12480 			/*
12481 			 * Here we are not retransmitting, and
12482 			 * the cwnd is not so small that we could
12483 			 * not send at least a min size (rxt timer
12484 			 * not having gone off), We have 2 segments or
12485 			 * more already in flight, its not the tail end
12486 			 * of the socket buffer  and the cwnd is blocking
12487 			 * us from sending out minimum pacing segment size.
12488 			 * Lets not send anything.
12489 			 */
12490 			bbr->rc_cwnd_limited = 1;
12491 			len = 0;
12492 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12493 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12494 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12495 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12496 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12497 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12498 			/*
12499 			 * Here we have a send window but we have
12500 			 * filled it up and we can't send another pacing segment.
12501 			 * We also have in flight more than 2 segments
12502 			 * and we are not completing the sb i.e. we allow
12503 			 * the last bytes of the sb to go out even if
12504 			 * its not a full pacing segment.
12505 			 */
12506 			len = 0;
12507 		}
12508 	}
12509 	/* len will be >= 0 after this point. */
12510 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12511 	tcp_sndbuf_autoscale(tp, so, sendwin);
12512 	/*
12513 	 *
12514 	 */
12515 	if (bbr->rc_in_persist &&
12516 	    len &&
12517 	    (rsm == NULL) &&
12518 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12519 		/*
12520 		 * We are in persist, not doing a retransmit and don't have enough space
12521 		 * yet to send a full TSO. So is it at the end of the sb
12522 		 * if so we need to send else nuke to 0 and don't send.
12523 		 */
12524 		int sbleft;
12525 		if (sbavail(sb) > sb_offset)
12526 			sbleft = sbavail(sb) - sb_offset;
12527 		else
12528 			sbleft = 0;
12529 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12530 			/* not at end of sb lets not send */
12531 			len = 0;
12532 		}
12533 	}
12534 	/*
12535 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12536 	 * hardware).
12537 	 *
12538 	 * TSO may only be used if we are in a pure bulk sending state.  The
12539 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12540 	 * options prevent using TSO.  With TSO the TCP header is the same
12541 	 * (except for the sequence number) for all generated packets.  This
12542 	 * makes it impossible to transmit any options which vary per
12543 	 * generated segment or packet.
12544 	 *
12545 	 * IPv4 handling has a clear separation of ip options and ip header
12546 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12547 	 * does the right thing below to provide length of just ip options
12548 	 * and thus checking for ipoptlen is enough to decide if ip options
12549 	 * are present.
12550 	 */
12551 #ifdef INET6
12552 	if (isipv6)
12553 		ipoptlen = ip6_optlen(inp);
12554 	else
12555 #endif
12556 	if (inp->inp_options)
12557 		ipoptlen = inp->inp_options->m_len -
12558 		    offsetof(struct ipoption, ipopt_list);
12559 	else
12560 		ipoptlen = 0;
12561 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12562 	/*
12563 	 * Pre-calculate here as we save another lookup into the darknesses
12564 	 * of IPsec that way and can actually decide if TSO is ok.
12565 	 */
12566 #ifdef INET6
12567 	if (isipv6 && IPSEC_ENABLED(ipv6))
12568 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12569 #ifdef INET
12570 	else
12571 #endif
12572 #endif				/* INET6 */
12573 #ifdef INET
12574 	if (IPSEC_ENABLED(ipv4))
12575 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12576 #endif				/* INET */
12577 #endif				/* IPSEC */
12578 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12579 	ipoptlen += ipsec_optlen;
12580 #endif
12581 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12582 	    (len > maxseg) &&
12583 	    (tp->t_port == 0) &&
12584 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12585 	    tp->rcv_numsacks == 0 &&
12586 	    ipoptlen == 0)
12587 		tso = 1;
12588 
12589 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12590 	    (long)TCP_MAXWIN << tp->rcv_scale);
12591 	/*
12592 	 * Sender silly window avoidance.   We transmit under the following
12593 	 * conditions when len is non-zero:
12594 	 *
12595 	 * - We have a full segment (or more with TSO) - This is the last
12596 	 * buffer in a write()/send() and we are either idle or running
12597 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12598 	 * then 1/2 the maximum send window's worth of data (receiver may be
12599 	 * limited the window size) - we need to retransmit
12600 	 */
12601 	if (rsm)
12602 		goto send;
12603 	if (len) {
12604 		if (sack_rxmit)
12605 			goto send;
12606 		if (len >= p_maxseg)
12607 			goto send;
12608 		/*
12609 		 * NOTE! on localhost connections an 'ack' from the remote
12610 		 * end may occur synchronously with the output and cause us
12611 		 * to flush a buffer queued with moretocome.  XXX
12612 		 *
12613 		 */
12614 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12615 		    ((tp->t_flags & TF_NODELAY) ||
12616 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12617 		    (tp->t_flags & TF_NOPUSH) == 0) {
12618 			goto send;
12619 		}
12620 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12621 			goto send;
12622 		}
12623 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12624 			goto send;
12625 		}
12626 	}
12627 	/*
12628 	 * Sending of standalone window updates.
12629 	 *
12630 	 * Window updates are important when we close our window due to a
12631 	 * full socket buffer and are opening it again after the application
12632 	 * reads data from it.  Once the window has opened again and the
12633 	 * remote end starts to send again the ACK clock takes over and
12634 	 * provides the most current window information.
12635 	 *
12636 	 * We must avoid the silly window syndrome whereas every read from
12637 	 * the receive buffer, no matter how small, causes a window update
12638 	 * to be sent.  We also should avoid sending a flurry of window
12639 	 * updates when the socket buffer had queued a lot of data and the
12640 	 * application is doing small reads.
12641 	 *
12642 	 * Prevent a flurry of pointless window updates by only sending an
12643 	 * update when we can increase the advertized window by more than
12644 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12645 	 * full or is very small be more aggressive and send an update
12646 	 * whenever we can increase by two mss sized segments. In all other
12647 	 * situations the ACK's to new incoming data will carry further
12648 	 * window increases.
12649 	 *
12650 	 * Don't send an independent window update if a delayed ACK is
12651 	 * pending (it will get piggy-backed on it) or the remote side
12652 	 * already has done a half-close and won't send more data.  Skip
12653 	 * this if the connection is in T/TCP half-open state.
12654 	 */
12655 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12656 	    !(tp->t_flags & TF_DELACK) &&
12657 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12658 		/* Check to see if we should do a window update */
12659 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12660 			goto send;
12661 	}
12662 	/*
12663 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12664 	 * is also a catch-all for the retransmit timer timeout case.
12665 	 */
12666 	if (tp->t_flags & TF_ACKNOW) {
12667 		goto send;
12668 	}
12669 	if (flags & TH_RST) {
12670 		/* Always send a RST if one is due */
12671 		goto send;
12672 	}
12673 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12674 		goto send;
12675 	}
12676 	/*
12677 	 * If our state indicates that FIN should be sent and we have not
12678 	 * yet done so, then we need to send.
12679 	 */
12680 	if (flags & TH_FIN &&
12681 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12682 		goto send;
12683 	}
12684 	/*
12685 	 * No reason to send a segment, just return.
12686 	 */
12687 just_return:
12688 	SOCKBUF_UNLOCK(sb);
12689 just_return_nolock:
12690 	if (tot_len)
12691 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12692 	if (bbr->rc_no_pacing)
12693 		slot = 0;
12694 	if (tot_len == 0) {
12695 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12696 		    tp->snd_wnd) {
12697 			BBR_STAT_INC(bbr_rwnd_limited);
12698 			app_limited = BBR_JR_RWND_LIMITED;
12699 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12700 			if ((bbr->rc_in_persist == 0) &&
12701 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12702 			    (tp->snd_max == tp->snd_una) &&
12703 			    sbavail(&so->so_snd)) {
12704 				/* No send window.. we must enter persist */
12705 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12706 			}
12707 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12708 			BBR_STAT_INC(bbr_app_limited);
12709 			app_limited = BBR_JR_APP_LIMITED;
12710 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12711 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12712 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12713 			BBR_STAT_INC(bbr_cwnd_limited);
12714  			app_limited = BBR_JR_CWND_LIMITED;
12715 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12716 									bbr->r_ctl.rc_lost_bytes)));
12717 			bbr->rc_cwnd_limited = 1;
12718 		} else {
12719 			BBR_STAT_INC(bbr_app_limited);
12720 			app_limited = BBR_JR_APP_LIMITED;
12721 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12722 		}
12723 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12724 		bbr->r_agg_early_set = 0;
12725 		bbr->r_ctl.rc_agg_early = 0;
12726 		bbr->r_ctl.rc_last_delay_val = 0;
12727 	} else if (bbr->rc_use_google == 0)
12728 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12729 	/* Are we app limited? */
12730 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12731 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12732 		/**
12733 		 * We are application limited.
12734 		 */
12735 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12736 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12737 	}
12738 	if (tot_len == 0)
12739 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12740 	/* Dont update the time if we did not send */
12741 	bbr->r_ctl.rc_last_delay_val = 0;
12742 	bbr->rc_output_starts_timer = 1;
12743 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12744 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12745 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12746 		/* Make sure snd_nxt is drug up */
12747 		tp->snd_nxt = tp->snd_max;
12748 	}
12749 	return (error);
12750 
12751 send:
12752 	if (doing_tlp == 0) {
12753 		/*
12754 		 * Data not a TLP, and its not the rxt firing. If it is the
12755 		 * rxt firing, we want to leave the tlp_in_progress flag on
12756 		 * so we don't send another TLP. It has to be a rack timer
12757 		 * or normal send (response to acked data) to clear the tlp
12758 		 * in progress flag.
12759 		 */
12760 		bbr->rc_tlp_in_progress = 0;
12761 		bbr->rc_tlp_rtx_out = 0;
12762 	} else {
12763 		/*
12764 		 * Its a TLP.
12765 		 */
12766 		bbr->rc_tlp_in_progress = 1;
12767 	}
12768 	bbr_timer_cancel(bbr, __LINE__, cts);
12769 	if (rsm == NULL) {
12770 		if (sbused(sb) > 0) {
12771 			/*
12772 			 * This is sub-optimal. We only send a stand alone
12773 			 * FIN on its own segment.
12774 			 */
12775 			if (flags & TH_FIN) {
12776 				flags &= ~TH_FIN;
12777 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12778 					/* Lets not send this */
12779 					slot = 0;
12780 					goto just_return;
12781 				}
12782 			}
12783 		}
12784 	} else {
12785 		/*
12786 		 * We do *not* send a FIN on a retransmit if it has data.
12787 		 * The if clause here where len > 1 should never come true.
12788 		 */
12789 		if ((len > 0) &&
12790 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12791 		    (flags & TH_FIN))) {
12792 			flags &= ~TH_FIN;
12793 			len--;
12794 		}
12795 	}
12796 	SOCKBUF_LOCK_ASSERT(sb);
12797 	if (len > 0) {
12798 		if ((tp->snd_una == tp->snd_max) &&
12799 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12800 			/*
12801 			 * This qualifies as a RTT_PROBE session since we
12802 			 * drop the data outstanding to nothing and waited
12803 			 * more than bbr_rtt_probe_time.
12804 			 */
12805 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12806 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12807 		}
12808 		if (len >= maxseg)
12809 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12810 		else
12811 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12812 	}
12813 	/*
12814 	 * Before ESTABLISHED, force sending of initial options unless TCP
12815 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12816 	 * plus TCP options always fit in a single mbuf, leaving room for a
12817 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12818 	 * + optlen <= MCLBYTES
12819 	 */
12820 	optlen = 0;
12821 #ifdef INET6
12822 	if (isipv6)
12823 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12824 	else
12825 #endif
12826 		hdrlen = sizeof(struct tcpiphdr);
12827 
12828 	/*
12829 	 * Compute options for segment. We only have to care about SYN and
12830 	 * established connection segments.  Options for SYN-ACK segments
12831 	 * are handled in TCP syncache.
12832 	 */
12833 	to.to_flags = 0;
12834 	local_options = 0;
12835 	if ((tp->t_flags & TF_NOOPT) == 0) {
12836 		/* Maximum segment size. */
12837 		if (flags & TH_SYN) {
12838 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12839 			if (tp->t_port)
12840 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12841 			to.to_flags |= TOF_MSS;
12842 			/*
12843 			 * On SYN or SYN|ACK transmits on TFO connections,
12844 			 * only include the TFO option if it is not a
12845 			 * retransmit, as the presence of the TFO option may
12846 			 * have caused the original SYN or SYN|ACK to have
12847 			 * been dropped by a middlebox.
12848 			 */
12849 			if (IS_FASTOPEN(tp->t_flags) &&
12850 			    (tp->t_rxtshift == 0)) {
12851 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12852 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12853 					to.to_tfo_cookie =
12854 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12855 					to.to_flags |= TOF_FASTOPEN;
12856 					wanted_cookie = 1;
12857 				} else if (tp->t_state == TCPS_SYN_SENT) {
12858 					to.to_tfo_len =
12859 					    tp->t_tfo_client_cookie_len;
12860 					to.to_tfo_cookie =
12861 					    tp->t_tfo_cookie.client;
12862 					to.to_flags |= TOF_FASTOPEN;
12863 					wanted_cookie = 1;
12864 				}
12865 			}
12866 		}
12867 		/* Window scaling. */
12868 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12869 			to.to_wscale = tp->request_r_scale;
12870 			to.to_flags |= TOF_SCALE;
12871 		}
12872 		/* Timestamps. */
12873 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12874 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12875 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12876 			to.to_tsecr = tp->ts_recent;
12877 			to.to_flags |= TOF_TS;
12878 			local_options += TCPOLEN_TIMESTAMP + 2;
12879 		}
12880 		/* Set receive buffer autosizing timestamp. */
12881 		if (tp->rfbuf_ts == 0 &&
12882 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12883 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12884 		/* Selective ACK's. */
12885 		if (flags & TH_SYN)
12886 			to.to_flags |= TOF_SACKPERM;
12887 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12888 		    tp->rcv_numsacks > 0) {
12889 			to.to_flags |= TOF_SACK;
12890 			to.to_nsacks = tp->rcv_numsacks;
12891 			to.to_sacks = (u_char *)tp->sackblks;
12892 		}
12893 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
12894 		/* TCP-MD5 (RFC2385). */
12895 		if (tp->t_flags & TF_SIGNATURE)
12896 			to.to_flags |= TOF_SIGNATURE;
12897 #endif				/* TCP_SIGNATURE */
12898 
12899 		/* Processing the options. */
12900 		hdrlen += (optlen = tcp_addoptions(&to, opt));
12901 		/*
12902 		 * If we wanted a TFO option to be added, but it was unable
12903 		 * to fit, ensure no data is sent.
12904 		 */
12905 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
12906 		    !(to.to_flags & TOF_FASTOPEN))
12907 			len = 0;
12908 	}
12909 	if (tp->t_port) {
12910 		if (V_tcp_udp_tunneling_port == 0) {
12911 			/* The port was removed?? */
12912 			SOCKBUF_UNLOCK(&so->so_snd);
12913 			return (EHOSTUNREACH);
12914 		}
12915 		hdrlen += sizeof(struct udphdr);
12916 	}
12917 #ifdef INET6
12918 	if (isipv6)
12919 		ipoptlen = ip6_optlen(inp);
12920 	else
12921 #endif
12922 	if (inp->inp_options)
12923 		ipoptlen = inp->inp_options->m_len -
12924 		    offsetof(struct ipoption, ipopt_list);
12925 	else
12926 		ipoptlen = 0;
12927 	ipoptlen = 0;
12928 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12929 	ipoptlen += ipsec_optlen;
12930 #endif
12931 	if (bbr->rc_last_options != local_options) {
12932 		/*
12933 		 * Cache the options length this generally does not change
12934 		 * on a connection. We use this to calculate TSO.
12935 		 */
12936 		bbr->rc_last_options = local_options;
12937 	}
12938 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
12939 	p_maxseg = min(maxseg, pace_max_segs);
12940 	/*
12941 	 * Adjust data length if insertion of options will bump the packet
12942 	 * length beyond the t_maxseg length. Clear the FIN bit because we
12943 	 * cut off the tail of the segment.
12944 	 */
12945 	if (len > maxseg) {
12946 		if (len != 0 && (flags & TH_FIN)) {
12947 			flags &= ~TH_FIN;
12948 		}
12949 		if (tso) {
12950 			uint32_t moff;
12951 			int32_t max_len;
12952 
12953 			/* extract TSO information */
12954 			if_hw_tsomax = tp->t_tsomax;
12955 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
12956 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
12957 			KASSERT(ipoptlen == 0,
12958 			    ("%s: TSO can't do IP options", __func__));
12959 
12960 			/*
12961 			 * Check if we should limit by maximum payload
12962 			 * length:
12963 			 */
12964 			if (if_hw_tsomax != 0) {
12965 				/* compute maximum TSO length */
12966 				max_len = (if_hw_tsomax - hdrlen -
12967 				    max_linkhdr);
12968 				if (max_len <= 0) {
12969 					len = 0;
12970 				} else if (len > max_len) {
12971 					len = max_len;
12972 				}
12973 			}
12974 			/*
12975 			 * Prevent the last segment from being fractional
12976 			 * unless the send sockbuf can be emptied:
12977 			 */
12978 			if ((sb_offset + len) < sbavail(sb)) {
12979 				moff = len % (uint32_t)maxseg;
12980 				if (moff != 0) {
12981 					len -= moff;
12982 				}
12983 			}
12984 			/*
12985 			 * In case there are too many small fragments don't
12986 			 * use TSO:
12987 			 */
12988 			if (len <= maxseg) {
12989 				len = maxseg;
12990 				tso = 0;
12991 			}
12992 		} else {
12993 			/* Not doing TSO */
12994 			if (optlen + ipoptlen >= tp->t_maxseg) {
12995 				/*
12996 				 * Since we don't have enough space to put
12997 				 * the IP header chain and the TCP header in
12998 				 * one packet as required by RFC 7112, don't
12999 				 * send it. Also ensure that at least one
13000 				 * byte of the payload can be put into the
13001 				 * TCP segment.
13002 				 */
13003 				SOCKBUF_UNLOCK(&so->so_snd);
13004 				error = EMSGSIZE;
13005 				sack_rxmit = 0;
13006 				goto out;
13007 			}
13008 			len = maxseg;
13009 		}
13010 	} else {
13011 		/* Not doing TSO */
13012 		if_hw_tsomaxsegcount = 0;
13013 		tso = 0;
13014 	}
13015 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13016 	    ("%s: len > IP_MAXPACKET", __func__));
13017 #ifdef DIAGNOSTIC
13018 #ifdef INET6
13019 	if (max_linkhdr + hdrlen > MCLBYTES)
13020 #else
13021 	if (max_linkhdr + hdrlen > MHLEN)
13022 #endif
13023 		panic("tcphdr too big");
13024 #endif
13025 	/*
13026 	 * This KASSERT is here to catch edge cases at a well defined place.
13027 	 * Before, those had triggered (random) panic conditions further
13028 	 * down.
13029 	 */
13030 #ifdef BBR_INVARIANTS
13031 	if (sack_rxmit) {
13032 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13033 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13034 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13035 		}
13036 	}
13037 #endif
13038 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13039 	if ((len == 0) &&
13040 	    (flags & TH_FIN) &&
13041 	    (sbused(sb))) {
13042 		/*
13043 		 * We have outstanding data, don't send a fin by itself!.
13044 		 */
13045 		slot = 0;
13046 		goto just_return;
13047 	}
13048 	/*
13049 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13050 	 * and initialize the header from the template for sends on this
13051 	 * connection.
13052 	 */
13053 	if (len) {
13054 		uint32_t moff;
13055 
13056 		/*
13057 		 * We place a limit on sending with hptsi.
13058 		 */
13059 		if ((rsm == NULL) && len > pace_max_segs)
13060 			len = pace_max_segs;
13061 		if (len <= maxseg)
13062 			tso = 0;
13063 #ifdef INET6
13064 		if (MHLEN < hdrlen + max_linkhdr)
13065 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13066 		else
13067 #endif
13068 			m = m_gethdr(M_NOWAIT, MT_DATA);
13069 
13070 		if (m == NULL) {
13071 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13072 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13073 			SOCKBUF_UNLOCK(sb);
13074 			error = ENOBUFS;
13075 			sack_rxmit = 0;
13076 			goto out;
13077 		}
13078 		m->m_data += max_linkhdr;
13079 		m->m_len = hdrlen;
13080 		/*
13081 		 * Start the m_copy functions from the closest mbuf to the
13082 		 * sb_offset in the socket buffer chain.
13083 		 */
13084 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13085 #ifdef BBR_INVARIANTS
13086 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13087 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13088 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13089 				    doing_retran_from,
13090 				    picked_up_retran,
13091 				    doing_tlp);
13092 
13093 #endif
13094 			/*
13095 			 * In this messed up situation we have two choices,
13096 			 * a) pretend the send worked, and just start timers
13097 			 * and what not (not good since that may lead us
13098 			 * back here a lot). <or> b) Send the lowest segment
13099 			 * in the map. <or> c) Drop the connection. Lets do
13100 			 * <b> which if it continues to happen will lead to
13101 			 * <c> via timeouts.
13102 			 */
13103 			BBR_STAT_INC(bbr_offset_recovery);
13104 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13105 			sb_offset = 0;
13106 			if (rsm == NULL) {
13107 				sack_rxmit = 0;
13108 				len = sbavail(sb);
13109 			} else {
13110 				sack_rxmit = 1;
13111 				if (rsm->r_start != tp->snd_una) {
13112 					/*
13113 					 * Things are really messed up, <c>
13114 					 * is the only thing to do.
13115 					 */
13116 					BBR_STAT_INC(bbr_offset_drop);
13117 					SOCKBUF_UNLOCK(sb);
13118 					(void)m_free(m);
13119 					return (-EFAULT); /* tcp_drop() */
13120 				}
13121 				len = rsm->r_end - rsm->r_start;
13122 			}
13123 			if (len > sbavail(sb))
13124 				len = sbavail(sb);
13125 			if (len > maxseg)
13126 				len = maxseg;
13127 		}
13128 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13129 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13130 			m_copydata(mb, moff, (int)len,
13131 			    mtod(m, caddr_t)+hdrlen);
13132 			if (rsm == NULL)
13133 				sbsndptr_adv(sb, mb, len);
13134 			m->m_len += len;
13135 		} else {
13136 			struct sockbuf *msb;
13137 
13138 			if (rsm)
13139 				msb = NULL;
13140 			else
13141 				msb = sb;
13142 #ifdef BBR_INVARIANTS
13143 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13144 				if (rsm) {
13145 					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 ",
13146 					    tp, bbr, len, moff,
13147 					    sbavail(sb), rsm,
13148 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13149 					    doing_retran_from,
13150 					    picked_up_retran,
13151 					    doing_tlp, sack_rxmit);
13152 				} else {
13153 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13154 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13155 				}
13156 			}
13157 #endif
13158 			m->m_next = tcp_m_copym(
13159 				mb, moff, &len,
13160 				if_hw_tsomaxsegcount,
13161 				if_hw_tsomaxsegsize, msb,
13162 				((rsm == NULL) ? hw_tls : 0)
13163 #ifdef NETFLIX_COPY_ARGS
13164 				, &filled_all
13165 #endif
13166 				);
13167 			if (len <= maxseg) {
13168 				/*
13169 				 * Must have ran out of mbufs for the copy
13170 				 * shorten it to no longer need tso. Lets
13171 				 * not put on sendalot since we are low on
13172 				 * mbufs.
13173 				 */
13174 				tso = 0;
13175 			}
13176 			if (m->m_next == NULL) {
13177 				SOCKBUF_UNLOCK(sb);
13178 				(void)m_free(m);
13179 				error = ENOBUFS;
13180 				sack_rxmit = 0;
13181 				goto out;
13182 			}
13183 		}
13184 #ifdef BBR_INVARIANTS
13185 		if (tso && len < maxseg) {
13186 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13187 			    tp, len, maxseg);
13188 		}
13189 		if (tso && if_hw_tsomaxsegcount) {
13190 			int32_t seg_cnt = 0;
13191 			struct mbuf *foo;
13192 
13193 			foo = m;
13194 			while (foo) {
13195 				seg_cnt++;
13196 				foo = foo->m_next;
13197 			}
13198 			if (seg_cnt > if_hw_tsomaxsegcount) {
13199 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13200 			}
13201 		}
13202 #endif
13203 		/*
13204 		 * If we're sending everything we've got, set PUSH. (This
13205 		 * will keep happy those implementations which only give
13206 		 * data to the user when a buffer fills or a PUSH comes in.)
13207 		 */
13208 		if (sb_offset + len == sbused(sb) &&
13209 		    sbused(sb) &&
13210 		    !(flags & TH_SYN)) {
13211 			flags |= TH_PUSH;
13212 		}
13213 		SOCKBUF_UNLOCK(sb);
13214 	} else {
13215 		SOCKBUF_UNLOCK(sb);
13216 		if (tp->t_flags & TF_ACKNOW)
13217 			KMOD_TCPSTAT_INC(tcps_sndacks);
13218 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13219 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13220 		else
13221 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13222 
13223 		m = m_gethdr(M_NOWAIT, MT_DATA);
13224 		if (m == NULL) {
13225 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13226 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13227 			error = ENOBUFS;
13228 			/* Fudge the send time since we could not send */
13229 			sack_rxmit = 0;
13230 			goto out;
13231 		}
13232 #ifdef INET6
13233 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13234 		    MHLEN >= hdrlen) {
13235 			M_ALIGN(m, hdrlen);
13236 		} else
13237 #endif
13238 			m->m_data += max_linkhdr;
13239 		m->m_len = hdrlen;
13240 	}
13241 	SOCKBUF_UNLOCK_ASSERT(sb);
13242 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13243 #ifdef MAC
13244 	mac_inpcb_create_mbuf(inp, m);
13245 #endif
13246 #ifdef INET6
13247 	if (isipv6) {
13248 		ip6 = mtod(m, struct ip6_hdr *);
13249 		if (tp->t_port) {
13250 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13251 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13252 			udp->uh_dport = tp->t_port;
13253 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13254 			udp->uh_ulen = htons(ulen);
13255 			th = (struct tcphdr *)(udp + 1);
13256 		} else {
13257 			th = (struct tcphdr *)(ip6 + 1);
13258 		}
13259 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13260 	} else
13261 #endif				/* INET6 */
13262 	{
13263 		ip = mtod(m, struct ip *);
13264 		if (tp->t_port) {
13265 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13266 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13267 			udp->uh_dport = tp->t_port;
13268 			ulen = hdrlen + len - sizeof(struct ip);
13269 			udp->uh_ulen = htons(ulen);
13270 			th = (struct tcphdr *)(udp + 1);
13271 		} else {
13272 			th = (struct tcphdr *)(ip + 1);
13273 		}
13274 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13275 	}
13276 	/*
13277 	 * If we are doing retransmissions, then snd_nxt will not reflect
13278 	 * the first unsent octet.  For ACK only packets, we do not want the
13279 	 * sequence number of the retransmitted packet, we want the sequence
13280 	 * number of the next unsent octet.  So, if there is no data (and no
13281 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13282 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13283 	 * one byte beyond the right edge of the window, so use snd_nxt in
13284 	 * that case, since we know we aren't doing a retransmission.
13285 	 * (retransmit and persist are mutually exclusive...)
13286 	 */
13287 	if (sack_rxmit == 0) {
13288 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13289 			/* New data (including new persists) */
13290 			th->th_seq = htonl(tp->snd_max);
13291 			bbr_seq = tp->snd_max;
13292 		} else if (flags & TH_SYN) {
13293 			/* Syn's always send from iss */
13294 			th->th_seq = htonl(tp->iss);
13295 			bbr_seq = tp->iss;
13296 		} else if (flags & TH_FIN) {
13297 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13298 				/*
13299 				 * If we sent the fin already its 1 minus
13300 				 * snd_max
13301 				 */
13302 				th->th_seq = (htonl(tp->snd_max - 1));
13303 				bbr_seq = (tp->snd_max - 1);
13304 			} else {
13305 				/* First time FIN use snd_max */
13306 				th->th_seq = htonl(tp->snd_max);
13307 				bbr_seq = tp->snd_max;
13308 			}
13309 		} else {
13310 			/*
13311 			 * len == 0 and not persist we use snd_max, sending
13312 			 * an ack unless we have sent the fin then its 1
13313 			 * minus.
13314 			 */
13315 			/*
13316 			 * XXXRRS Question if we are in persists and we have
13317 			 * nothing outstanding to send and we have not sent
13318 			 * a FIN, we will send an ACK. In such a case it
13319 			 * might be better to send (tp->snd_una - 1) which
13320 			 * would force the peer to ack.
13321 			 */
13322 			if (tp->t_flags & TF_SENTFIN) {
13323 				th->th_seq = htonl(tp->snd_max - 1);
13324 				bbr_seq = (tp->snd_max - 1);
13325 			} else {
13326 				th->th_seq = htonl(tp->snd_max);
13327 				bbr_seq = tp->snd_max;
13328 			}
13329 		}
13330 	} else {
13331 		/* All retransmits use the rsm to guide the send */
13332 		th->th_seq = htonl(rsm->r_start);
13333 		bbr_seq = rsm->r_start;
13334 	}
13335 	th->th_ack = htonl(tp->rcv_nxt);
13336 	if (optlen) {
13337 		bcopy(opt, th + 1, optlen);
13338 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13339 	}
13340 	tcp_set_flags(th, flags);
13341 	/*
13342 	 * Calculate receive window.  Don't shrink window, but avoid silly
13343 	 * window syndrome.
13344 	 */
13345 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13346 				  recwin < maxseg)))
13347 		recwin = 0;
13348 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13349 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13350 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13351 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13352 		recwin = TCP_MAXWIN << tp->rcv_scale;
13353 
13354 	/*
13355 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13356 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13357 	 * handled in syncache.
13358 	 */
13359 	if (flags & TH_SYN)
13360 		th->th_win = htons((u_short)
13361 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13362 	else {
13363 		/* Avoid shrinking window with window scaling. */
13364 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13365 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13366 	}
13367 	/*
13368 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13369 	 * window.  This may cause the remote transmitter to stall.  This
13370 	 * flag tells soreceive() to disable delayed acknowledgements when
13371 	 * draining the buffer.  This can occur if the receiver is
13372 	 * attempting to read more data than can be buffered prior to
13373 	 * transmitting on the connection.
13374 	 */
13375 	if (th->th_win == 0) {
13376 		tp->t_sndzerowin++;
13377 		tp->t_flags |= TF_RXWIN0SENT;
13378 	} else
13379 		tp->t_flags &= ~TF_RXWIN0SENT;
13380 	/*
13381 	 * We don't support urgent data, but drag along
13382 	 * the pointer in case of a stack switch.
13383 	 */
13384 	tp->snd_up = tp->snd_una;
13385 
13386 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13387 	if (to.to_flags & TOF_SIGNATURE) {
13388 		/*
13389 		 * Calculate MD5 signature and put it into the place
13390 		 * determined before. NOTE: since TCP options buffer doesn't
13391 		 * point into mbuf's data, calculate offset and use it.
13392 		 */
13393 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13394 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13395 			/*
13396 			 * Do not send segment if the calculation of MD5
13397 			 * digest has failed.
13398 			 */
13399 			goto out;
13400 		}
13401 	}
13402 #endif
13403 
13404 	/*
13405 	 * Put TCP length in extended header, and then checksum extended
13406 	 * header and data.
13407 	 */
13408 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13409 #ifdef INET6
13410 	if (isipv6) {
13411 		/*
13412 		 * ip6_plen is not need to be filled now, and will be filled
13413 		 * in ip6_output.
13414 		 */
13415 		if (tp->t_port) {
13416 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13417 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13418 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13419 			th->th_sum = htons(0);
13420 			UDPSTAT_INC(udps_opackets);
13421 		} else {
13422 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13423 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13424 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13425 			    optlen + len, IPPROTO_TCP, 0);
13426 		}
13427 	}
13428 #endif
13429 #if defined(INET6) && defined(INET)
13430 	else
13431 #endif
13432 #ifdef INET
13433 	{
13434 		if (tp->t_port) {
13435 			m->m_pkthdr.csum_flags = CSUM_UDP;
13436 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13437 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13438 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13439 			th->th_sum = htons(0);
13440 			UDPSTAT_INC(udps_opackets);
13441 		} else {
13442 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13443 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13444 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13445 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13446 			    IPPROTO_TCP + len + optlen));
13447 		}
13448 		/* IP version must be set here for ipv4/ipv6 checking later */
13449 		KASSERT(ip->ip_v == IPVERSION,
13450 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13451 	}
13452 #endif
13453 
13454 	/*
13455 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13456 	 * header checksum is always provided. XXX: Fixme: This is currently
13457 	 * not the case for IPv6.
13458 	 */
13459 	if (tso) {
13460 		KASSERT(len > maxseg,
13461 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13462 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13463 		csum_flags |= CSUM_TSO;
13464 		m->m_pkthdr.tso_segsz = maxseg;
13465 	}
13466 	KASSERT(len + hdrlen == m_length(m, NULL),
13467 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13468 	    __func__, len, hdrlen, m_length(m, NULL)));
13469 
13470 #ifdef TCP_HHOOK
13471 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13472 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13473 #endif
13474 
13475 	/* Log to the black box */
13476 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13477 		union tcp_log_stackspecific log;
13478 
13479 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13480 		/* Record info on type of transmission */
13481 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13482 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13483 		log.u_bbr.flex3 = maxseg;
13484 		log.u_bbr.flex4 = delay_calc;
13485 		/* Encode filled_all into the upper flex5 bit */
13486 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13487 		log.u_bbr.flex5 <<= 1;
13488 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13489 		log.u_bbr.flex5 <<= 29;
13490 		if (filled_all)
13491 			log.u_bbr.flex5 |= 0x80000000;
13492 		log.u_bbr.flex5 |= tp->t_maxseg;
13493 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13494 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13495 		/* lets poke in the low and the high here for debugging */
13496 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13497 		if (rsm || sack_rxmit) {
13498 			if (doing_tlp)
13499 				log.u_bbr.flex8 = 2;
13500 			else
13501 				log.u_bbr.flex8 = 1;
13502 		} else {
13503 			log.u_bbr.flex8 = 0;
13504 		}
13505 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13506 		    len, &log, false, NULL, NULL, 0, tv);
13507 	} else {
13508 		lgb = NULL;
13509 	}
13510 	/*
13511 	 * Fill in IP length and desired time to live and send to IP level.
13512 	 * There should be a better way to handle ttl and tos; we could keep
13513 	 * them in the template, but need a way to checksum without them.
13514 	 */
13515 	/*
13516 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13517 	 * because in6_cksum() need it.
13518 	 */
13519 #ifdef INET6
13520 	if (isipv6) {
13521 		/*
13522 		 * we separately set hoplimit for every segment, since the
13523 		 * user might want to change the value via setsockopt. Also,
13524 		 * desired default hop limit might be changed via Neighbor
13525 		 * Discovery.
13526 		 */
13527 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13528 
13529 		/*
13530 		 * Set the packet size here for the benefit of DTrace
13531 		 * probes. ip6_output() will set it properly; it's supposed
13532 		 * to include the option header lengths as well.
13533 		 */
13534 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13535 
13536 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13537 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13538 		else
13539 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13540 
13541 		if (tp->t_state == TCPS_SYN_SENT)
13542 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13543 
13544 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13545 		/* TODO: IPv6 IP6TOS_ECT bit on */
13546 		error = ip6_output(m, inp->in6p_outputopts,
13547 		    &inp->inp_route6,
13548 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13549 		    NULL, NULL, inp);
13550 
13551 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13552 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13553 	}
13554 #endif				/* INET6 */
13555 #if defined(INET) && defined(INET6)
13556 	else
13557 #endif
13558 #ifdef INET
13559 	{
13560 		ip->ip_len = htons(m->m_pkthdr.len);
13561 #ifdef INET6
13562 		if (isipv6)
13563 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13564 #endif				/* INET6 */
13565 		/*
13566 		 * If we do path MTU discovery, then we set DF on every
13567 		 * packet. This might not be the best thing to do according
13568 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13569 		 * the problem so it affects only the first tcp connection
13570 		 * with a host.
13571 		 *
13572 		 * NB: Don't set DF on small MTU/MSS to have a safe
13573 		 * fallback.
13574 		 */
13575 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13576 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13577 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13578 				ip->ip_off |= htons(IP_DF);
13579 			}
13580 		} else {
13581 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13582 		}
13583 
13584 		if (tp->t_state == TCPS_SYN_SENT)
13585 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13586 
13587 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13588 
13589 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13590 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13591 		    inp);
13592 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13593 			mtu = inp->inp_route.ro_nh->nh_mtu;
13594 	}
13595 #endif				/* INET */
13596 out:
13597 
13598 	if (lgb) {
13599 		lgb->tlb_errno = error;
13600 		lgb = NULL;
13601 	}
13602 	/*
13603 	 * In transmit state, time the transmission and arrange for the
13604 	 * retransmit.  In persist state, just set snd_max.
13605 	 */
13606 	if (error == 0) {
13607 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13608 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13609 		    (tp->t_flags & TF_SACK_PERMIT) &&
13610 		    tp->rcv_numsacks > 0)
13611 			tcp_clean_dsack_blocks(tp);
13612 		/* We sent an ack clear the bbr_segs_rcvd count */
13613 		bbr->output_error_seen = 0;
13614 		bbr->oerror_cnt = 0;
13615 		bbr->bbr_segs_rcvd = 0;
13616 		if (len == 0)
13617 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13618 		/* Do accounting for new sends */
13619 		if ((len > 0) && (rsm == NULL)) {
13620 			int idx;
13621 			if (tp->snd_una == tp->snd_max) {
13622 				/*
13623 				 * Special case to match google, when
13624 				 * nothing is in flight the delivered
13625 				 * time does get updated to the current
13626 				 * time (see tcp_rate_bsd.c).
13627 				 */
13628 				bbr->r_ctl.rc_del_time = cts;
13629 			}
13630 			if (len >= maxseg) {
13631 				idx = (len / maxseg) + 3;
13632 				if (idx >= TCP_MSS_ACCT_ATIMER)
13633 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13634 				else
13635 					counter_u64_add(bbr_out_size[idx], 1);
13636 			} else {
13637 				/* smaller than a MSS */
13638 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13639 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13640 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13641 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13642 			}
13643 		}
13644 	}
13645 	abandon = 0;
13646 	/*
13647 	 * We must do the send accounting before we log the output,
13648 	 * otherwise the state of the rsm could change and we account to the
13649 	 * wrong bucket.
13650 	 */
13651 	if (len > 0) {
13652 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13653 		if (error == 0) {
13654 			if (tp->snd_una == tp->snd_max)
13655 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13656 		}
13657 	}
13658 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13659 	    cts, mb, &abandon, rsm, 0, sb);
13660 	if (abandon) {
13661 		/*
13662 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13663 		 * sent we should hit this condition.
13664 		 */
13665 		return (0);
13666 	}
13667 	if (bbr->rc_in_persist == 0) {
13668 		/*
13669 		 * Advance snd_nxt over sequence space of this segment.
13670 		 */
13671 		if (error)
13672 			/* We don't log or do anything with errors */
13673 			goto skip_upd;
13674 
13675 		if (tp->snd_una == tp->snd_max &&
13676 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13677 			/*
13678 			 * Update the time we just added data since none was
13679 			 * outstanding.
13680 			 */
13681 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13682 			bbr->rc_tp->t_acktime  = ticks;
13683 		}
13684 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13685 			if (flags & TH_SYN) {
13686 				/*
13687 				 * Smack the snd_max to iss + 1
13688 				 * if its a FO we will add len below.
13689 				 */
13690 				tp->snd_max = tp->iss + 1;
13691 			}
13692 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13693 				tp->snd_max++;
13694 				tp->t_flags |= TF_SENTFIN;
13695 			}
13696 		}
13697 		if (sack_rxmit == 0)
13698 			tp->snd_max += len;
13699 skip_upd:
13700 		if ((error == 0) && len)
13701 			tot_len += len;
13702 	} else {
13703 		/* Persists case */
13704 		int32_t xlen = len;
13705 
13706 		if (error)
13707 			goto nomore;
13708 
13709 		if (flags & TH_SYN)
13710 			++xlen;
13711 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13712 			++xlen;
13713 			tp->t_flags |= TF_SENTFIN;
13714 		}
13715 		if (xlen && (tp->snd_una == tp->snd_max)) {
13716 			/*
13717 			 * Update the time we just added data since none was
13718 			 * outstanding.
13719 			 */
13720 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13721 			bbr->rc_tp->t_acktime = ticks;
13722 		}
13723 		if (sack_rxmit == 0)
13724 			tp->snd_max += xlen;
13725 		tot_len += (len + optlen + ipoptlen);
13726 	}
13727 nomore:
13728 	if (error) {
13729 		/*
13730 		 * Failures do not advance the seq counter above. For the
13731 		 * case of ENOBUFS we will fall out and become ack-clocked.
13732 		 * capping the cwnd at the current flight.
13733 		 * Everything else will just have to retransmit with the timer
13734 		 * (no pacer).
13735 		 */
13736 		SOCKBUF_UNLOCK_ASSERT(sb);
13737 		BBR_STAT_INC(bbr_saw_oerr);
13738 		/* Clear all delay/early tracks */
13739 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13740 		bbr->r_ctl.rc_agg_early = 0;
13741 		bbr->r_agg_early_set = 0;
13742 		bbr->output_error_seen = 1;
13743 		if (bbr->oerror_cnt < 0xf)
13744 			bbr->oerror_cnt++;
13745 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13746 			/* drop the session */
13747 			return (-ENETDOWN);
13748 		}
13749 		switch (error) {
13750 		case ENOBUFS:
13751 			/*
13752 			 * Make this guy have to get ack's to send
13753 			 * more but lets make sure we don't
13754 			 * slam him below a T-O (1MSS).
13755 			 */
13756 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13757 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13758 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13759 				if (tp->snd_cwnd < maxseg)
13760 					tp->snd_cwnd = maxseg;
13761 			}
13762 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13763 			BBR_STAT_INC(bbr_saw_enobuf);
13764 			if (bbr->bbr_hdrw_pacing)
13765 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13766 			else
13767 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13768 			/*
13769 			 * Here even in the enobuf's case we want to do our
13770 			 * state update. The reason being we may have been
13771 			 * called by the input function. If so we have had
13772 			 * things change.
13773 			 */
13774 			error = 0;
13775 			goto enobufs;
13776 		case EMSGSIZE:
13777 			/*
13778 			 * For some reason the interface we used initially
13779 			 * to send segments changed to another or lowered
13780 			 * its MTU. If TSO was active we either got an
13781 			 * interface without TSO capabilits or TSO was
13782 			 * turned off. If we obtained mtu from ip_output()
13783 			 * then update it and try again.
13784 			 */
13785 			/* Turn on tracing (or try to) */
13786 			{
13787 				int old_maxseg;
13788 
13789 				old_maxseg = tp->t_maxseg;
13790 				BBR_STAT_INC(bbr_saw_emsgsiz);
13791 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13792 				if (mtu != 0)
13793 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13794 				if (old_maxseg <= tp->t_maxseg) {
13795 					/* Huh it did not shrink? */
13796 					tp->t_maxseg = old_maxseg - 40;
13797 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13798 				}
13799 				/*
13800 				 * Nuke all other things that can interfere
13801 				 * with slot
13802 				 */
13803 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13804 					slot = bbr_get_pacing_delay(bbr,
13805 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13806 					    (tot_len + len), cts, 0);
13807 					if (slot < bbr_error_base_paceout)
13808 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13809 				} else
13810 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13811 				bbr->rc_output_starts_timer = 1;
13812 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13813 				    tot_len);
13814 				return (error);
13815 			}
13816 		case EPERM:
13817 			tp->t_softerror = error;
13818 			/* Fall through */
13819 		case EHOSTDOWN:
13820 		case EHOSTUNREACH:
13821 		case ENETDOWN:
13822 		case ENETUNREACH:
13823 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13824 				tp->t_softerror = error;
13825 			}
13826 			/* FALLTHROUGH */
13827 		default:
13828 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13829 			bbr->rc_output_starts_timer = 1;
13830 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13831 			return (error);
13832 		}
13833 #ifdef STATS
13834 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13835 		    len &&
13836 		    (rsm == NULL) &&
13837 	    (bbr->rc_in_persist == 0)) {
13838 		tp->gput_seq = bbr_seq;
13839 		tp->gput_ack = bbr_seq +
13840 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13841 		tp->gput_ts = cts;
13842 		tp->t_flags |= TF_GPUTINPROG;
13843 #endif
13844 	}
13845 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13846 	if ((bbr->bbr_hdw_pace_ena) &&
13847 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13848 	    (bbr->rc_past_init_win) &&
13849 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13850 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13851 	    (inp->inp_route.ro_nh &&
13852 	     inp->inp_route.ro_nh->nh_ifp)) {
13853 		/*
13854 		 * We are past the initial window and
13855 		 * have at least one measurement so we
13856 		 * could use hardware pacing if its available.
13857 		 * We have an interface and we have not attempted
13858 		 * to setup hardware pacing, lets try to now.
13859 		 */
13860 		uint64_t rate_wanted;
13861 		int err = 0;
13862 
13863 		rate_wanted = bbr_get_hardware_rate(bbr);
13864 		bbr->bbr_attempt_hdwr_pace = 1;
13865 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13866 						      inp->inp_route.ro_nh->nh_ifp,
13867 						      rate_wanted,
13868 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
13869 						      &err, NULL);
13870 		if (bbr->r_ctl.crte) {
13871 			bbr_type_log_hdwr_pacing(bbr,
13872 						 bbr->r_ctl.crte->ptbl->rs_ifp,
13873 						 rate_wanted,
13874 						 bbr->r_ctl.crte->rate,
13875 						 __LINE__, cts, err);
13876 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
13877 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
13878 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
13879 			bbr->bbr_hdrw_pacing = 1;
13880 			/* Now what is our gain status? */
13881 			if (bbr->r_ctl.crte->rate < rate_wanted) {
13882 				/* We have a problem */
13883 				bbr_setup_less_of_rate(bbr, cts,
13884 						       bbr->r_ctl.crte->rate, rate_wanted);
13885 			} else {
13886 				/* We are good */
13887 				bbr->gain_is_limited = 0;
13888 				bbr->skip_gain = 0;
13889 			}
13890 			tcp_bbr_tso_size_check(bbr, cts);
13891 		} else {
13892 			bbr_type_log_hdwr_pacing(bbr,
13893 						 inp->inp_route.ro_nh->nh_ifp,
13894 						 rate_wanted,
13895 						 0,
13896 						 __LINE__, cts, err);
13897 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
13898 		}
13899 	}
13900 	if (bbr->bbr_hdrw_pacing) {
13901 		/*
13902 		 * Worry about cases where the route
13903 		 * changes or something happened that we
13904 		 * lost our hardware pacing possibly during
13905 		 * the last ip_output call.
13906 		 */
13907 		if (inp->inp_snd_tag == NULL) {
13908 			/* A change during ip output disabled hw pacing? */
13909 			bbr->bbr_hdrw_pacing = 0;
13910 		} else if ((inp->inp_route.ro_nh == NULL) ||
13911 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
13912 			/*
13913 			 * We had an interface or route change,
13914 			 * detach from the current hdwr pacing
13915 			 * and setup to re-attempt next go
13916 			 * round.
13917 			 */
13918 			bbr->bbr_hdrw_pacing = 0;
13919 			bbr->bbr_attempt_hdwr_pace = 0;
13920 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
13921 			tcp_bbr_tso_size_check(bbr, cts);
13922 		}
13923 	}
13924 	/*
13925 	 * Data sent (as far as we can tell). If this advertises a larger
13926 	 * window than any other segment, then remember the size of the
13927 	 * advertised window. Any pending ACK has now been sent.
13928 	 */
13929 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
13930 		tp->rcv_adv = tp->rcv_nxt + recwin;
13931 
13932 	tp->last_ack_sent = tp->rcv_nxt;
13933 	if ((error == 0) &&
13934 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
13935 	    (doing_tlp == 0) &&
13936 	    (tso == 0) &&
13937 	    (len > 0) &&
13938 	    ((flags & TH_RST) == 0) &&
13939 	    ((flags & TH_SYN) == 0) &&
13940 	    (IN_RECOVERY(tp->t_flags) == 0) &&
13941 	    (bbr->rc_in_persist == 0) &&
13942 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
13943 		/*
13944 		 * For non-tso we need to goto again until we have sent out
13945 		 * enough data to match what we are hptsi out every hptsi
13946 		 * interval.
13947 		 */
13948 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13949 			/* Make sure snd_nxt is drug up */
13950 			tp->snd_nxt = tp->snd_max;
13951 		}
13952 		if (rsm != NULL) {
13953 			rsm = NULL;
13954 			goto skip_again;
13955 		}
13956 		rsm = NULL;
13957 		sack_rxmit = 0;
13958 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13959 		goto again;
13960 	}
13961 skip_again:
13962 	if ((error == 0) && (flags & TH_FIN))
13963 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
13964 	if ((error == 0) && (flags & TH_RST))
13965 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13966 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
13967 		/*
13968 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
13969 		 * what we have sent so far
13970 		 */
13971 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
13972 		if (bbr->rc_no_pacing)
13973 			slot = 0;
13974 	}
13975 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13976 enobufs:
13977 	if (bbr->rc_use_google == 0)
13978 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
13979 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13980 							bbr->r_ctl.rc_lost_bytes)));
13981 	bbr->rc_output_starts_timer = 1;
13982 	if (bbr->bbr_use_rack_cheat &&
13983 	    (more_to_rxt ||
13984 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
13985 		/* Rack cheats and shotguns out all rxt's 1ms apart */
13986 		if (slot > 1000)
13987 			slot = 1000;
13988 	}
13989 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
13990 		/*
13991 		 * We don't change the tso size until some number of sends
13992 		 * to give the hardware commands time to get down
13993 		 * to the interface.
13994 		 */
13995 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
13996 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
13997 			bbr->hw_pacing_set = 1;
13998 			tcp_bbr_tso_size_check(bbr, cts);
13999 		}
14000 	}
14001 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14002 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14003 		/* Make sure snd_nxt is drug up */
14004 		tp->snd_nxt = tp->snd_max;
14005 	}
14006 	return (error);
14007 
14008 }
14009 
14010 /*
14011  * See bbr_output_wtime() for return values.
14012  */
14013 static int
14014 bbr_output(struct tcpcb *tp)
14015 {
14016 	int32_t ret;
14017 	struct timeval tv;
14018 
14019 	NET_EPOCH_ASSERT();
14020 
14021 	INP_WLOCK_ASSERT(tptoinpcb(tp));
14022 	(void)tcp_get_usecs(&tv);
14023 	ret = bbr_output_wtime(tp, &tv);
14024 	return (ret);
14025 }
14026 
14027 static void
14028 bbr_mtu_chg(struct tcpcb *tp)
14029 {
14030 	struct tcp_bbr *bbr;
14031 	struct bbr_sendmap *rsm, *frsm = NULL;
14032 	uint32_t maxseg;
14033 
14034 	/*
14035 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14036 	 * over the current size as SACK_PASS so a retransmit will occur.
14037 	 */
14038 
14039 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14040 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14041 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14042 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14043 		/* Don't mess with ones acked (by sack?) */
14044 		if (rsm->r_flags & BBR_ACKED)
14045 			continue;
14046 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14047 			/*
14048 			 * We mark sack-passed on all the previous large
14049 			 * sends we did. This will force them to retransmit.
14050 			 */
14051 			rsm->r_flags |= BBR_SACK_PASSED;
14052 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14053 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14054 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14055 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14056 				rsm->r_flags |= BBR_MARKED_LOST;
14057 			}
14058 			if (frsm == NULL)
14059 				frsm = rsm;
14060 		}
14061 	}
14062 	if (frsm) {
14063 		bbr->r_ctl.rc_resend = frsm;
14064 	}
14065 }
14066 
14067 static int
14068 bbr_pru_options(struct tcpcb *tp, int flags)
14069 {
14070 	if (flags & PRUS_OOB)
14071 		return (EOPNOTSUPP);
14072 	return (0);
14073 }
14074 
14075 struct tcp_function_block __tcp_bbr = {
14076 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14077 	.tfb_tcp_output = bbr_output,
14078 	.tfb_do_queued_segments = ctf_do_queued_segments,
14079 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14080 	.tfb_tcp_do_segment = bbr_do_segment,
14081 	.tfb_tcp_ctloutput = bbr_ctloutput,
14082 	.tfb_tcp_fb_init = bbr_init,
14083 	.tfb_tcp_fb_fini = bbr_fini,
14084 	.tfb_tcp_timer_stop_all = bbr_stopall,
14085 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14086 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14087 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14088 	.tfb_pru_options = bbr_pru_options,
14089 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14090 };
14091 
14092 /*
14093  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14094  * socket option arguments.  When it re-acquires the lock after the copy, it
14095  * has to revalidate that the connection is still valid for the socket
14096  * option.
14097  */
14098 static int
14099 bbr_set_sockopt(struct inpcb *inp, struct sockopt *sopt)
14100 {
14101 	struct epoch_tracker et;
14102 	struct tcpcb *tp;
14103 	struct tcp_bbr *bbr;
14104 	int32_t error = 0, optval;
14105 
14106 	switch (sopt->sopt_level) {
14107 	case IPPROTO_IPV6:
14108 	case IPPROTO_IP:
14109 		return (tcp_default_ctloutput(inp, sopt));
14110 	}
14111 
14112 	switch (sopt->sopt_name) {
14113 	case TCP_RACK_PACE_MAX_SEG:
14114 	case TCP_RACK_MIN_TO:
14115 	case TCP_RACK_REORD_THRESH:
14116 	case TCP_RACK_REORD_FADE:
14117 	case TCP_RACK_TLP_THRESH:
14118 	case TCP_RACK_PKT_DELAY:
14119 	case TCP_BBR_ALGORITHM:
14120 	case TCP_BBR_TSLIMITS:
14121 	case TCP_BBR_IWINTSO:
14122 	case TCP_BBR_RECFORCE:
14123 	case TCP_BBR_STARTUP_PG:
14124 	case TCP_BBR_DRAIN_PG:
14125 	case TCP_BBR_RWND_IS_APP:
14126 	case TCP_BBR_PROBE_RTT_INT:
14127 	case TCP_BBR_PROBE_RTT_GAIN:
14128 	case TCP_BBR_PROBE_RTT_LEN:
14129 	case TCP_BBR_STARTUP_LOSS_EXIT:
14130 	case TCP_BBR_USEDEL_RATE:
14131 	case TCP_BBR_MIN_RTO:
14132 	case TCP_BBR_MAX_RTO:
14133 	case TCP_BBR_PACE_PER_SEC:
14134 	case TCP_DELACK:
14135 	case TCP_BBR_PACE_DEL_TAR:
14136 	case TCP_BBR_SEND_IWND_IN_TSO:
14137 	case TCP_BBR_EXTRA_STATE:
14138 	case TCP_BBR_UTTER_MAX_TSO:
14139 	case TCP_BBR_MIN_TOPACEOUT:
14140 	case TCP_BBR_FLOOR_MIN_TSO:
14141 	case TCP_BBR_TSTMP_RAISES:
14142 	case TCP_BBR_POLICER_DETECT:
14143 	case TCP_BBR_USE_RACK_CHEAT:
14144 	case TCP_DATA_AFTER_CLOSE:
14145 	case TCP_BBR_HDWR_PACE:
14146 	case TCP_BBR_PACE_SEG_MAX:
14147 	case TCP_BBR_PACE_SEG_MIN:
14148 	case TCP_BBR_PACE_CROSS:
14149 	case TCP_BBR_PACE_OH:
14150 #ifdef NETFLIX_PEAKRATE
14151 	case TCP_MAXPEAKRATE:
14152 #endif
14153 	case TCP_BBR_TMR_PACE_OH:
14154 	case TCP_BBR_RACK_RTT_USE:
14155 	case TCP_BBR_RETRAN_WTSO:
14156 		break;
14157 	default:
14158 		return (tcp_default_ctloutput(inp, sopt));
14159 		break;
14160 	}
14161 	INP_WUNLOCK(inp);
14162 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14163 	if (error)
14164 		return (error);
14165 	INP_WLOCK(inp);
14166 	if (inp->inp_flags & INP_DROPPED) {
14167 		INP_WUNLOCK(inp);
14168 		return (ECONNRESET);
14169 	}
14170 	tp = intotcpcb(inp);
14171 	if (tp->t_fb != &__tcp_bbr) {
14172 		INP_WUNLOCK(inp);
14173 		return (ENOPROTOOPT);
14174 	}
14175 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14176 	switch (sopt->sopt_name) {
14177 	case TCP_BBR_PACE_PER_SEC:
14178 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14179 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14180 		break;
14181 	case TCP_BBR_PACE_DEL_TAR:
14182 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14183 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14184 		break;
14185 	case TCP_BBR_PACE_SEG_MAX:
14186 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14187 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14188 		break;
14189 	case TCP_BBR_PACE_SEG_MIN:
14190 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14191 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14192 		break;
14193 	case TCP_BBR_PACE_CROSS:
14194 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14195 		bbr->r_ctl.bbr_cross_over = optval;
14196 		break;
14197 	case TCP_BBR_ALGORITHM:
14198 		BBR_OPTS_INC(tcp_bbr_algorithm);
14199 		if (optval && (bbr->rc_use_google == 0)) {
14200 			/* Turn on the google mode */
14201 			bbr_google_mode_on(bbr);
14202 			if ((optval > 3) && (optval < 500)) {
14203 				/*
14204 				 * Must be at least greater than .3%
14205 				 * and must be less than 50.0%.
14206 				 */
14207 				bbr->r_ctl.bbr_google_discount = optval;
14208 			}
14209 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14210 			/* Turn off the google mode */
14211 			bbr_google_mode_off(bbr);
14212 		}
14213 		break;
14214 	case TCP_BBR_TSLIMITS:
14215 		BBR_OPTS_INC(tcp_bbr_tslimits);
14216 		if (optval == 1)
14217 			bbr->rc_use_ts_limit = 1;
14218 		else if (optval == 0)
14219 			bbr->rc_use_ts_limit = 0;
14220 		else
14221 			error = EINVAL;
14222 		break;
14223 
14224 	case TCP_BBR_IWINTSO:
14225 		BBR_OPTS_INC(tcp_bbr_iwintso);
14226 		if ((optval >= 0) && (optval < 128)) {
14227 			uint32_t twin;
14228 
14229 			bbr->rc_init_win = optval;
14230 			twin = bbr_initial_cwnd(bbr, tp);
14231 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14232 				tp->snd_cwnd = twin;
14233 			else
14234 				error = EBUSY;
14235 		} else
14236 			error = EINVAL;
14237 		break;
14238 	case TCP_BBR_STARTUP_PG:
14239 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14240 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14241 			bbr->r_ctl.rc_startup_pg = optval;
14242 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14243 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14244 			}
14245 		} else
14246 			error = EINVAL;
14247 		break;
14248 	case TCP_BBR_DRAIN_PG:
14249 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14250 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14251 			bbr->r_ctl.rc_drain_pg = optval;
14252 		else
14253 			error = EINVAL;
14254 		break;
14255 	case TCP_BBR_PROBE_RTT_LEN:
14256 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14257 		if (optval <= 1)
14258 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14259 		else
14260 			error = EINVAL;
14261 		break;
14262 	case TCP_BBR_PROBE_RTT_GAIN:
14263 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14264 		if (optval <= BBR_UNIT)
14265 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14266 		else
14267 			error = EINVAL;
14268 		break;
14269 	case TCP_BBR_PROBE_RTT_INT:
14270 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14271 		if (optval > 1000)
14272 			bbr->r_ctl.rc_probertt_int = optval;
14273 		else
14274 			error = EINVAL;
14275 		break;
14276 	case TCP_BBR_MIN_TOPACEOUT:
14277 		BBR_OPTS_INC(tcp_bbr_topaceout);
14278 		if (optval == 0) {
14279 			bbr->no_pacing_until = 0;
14280 			bbr->rc_no_pacing = 0;
14281 		} else if (optval <= 0x00ff) {
14282 			bbr->no_pacing_until = optval;
14283 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14284 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14285 				/* Turn on no pacing */
14286 				bbr->rc_no_pacing = 1;
14287 			}
14288 		} else
14289 			error = EINVAL;
14290 		break;
14291 	case TCP_BBR_STARTUP_LOSS_EXIT:
14292 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14293 		bbr->rc_loss_exit = optval;
14294 		break;
14295 	case TCP_BBR_USEDEL_RATE:
14296 		error = EINVAL;
14297 		break;
14298 	case TCP_BBR_MIN_RTO:
14299 		BBR_OPTS_INC(tcp_bbr_min_rto);
14300 		bbr->r_ctl.rc_min_rto_ms = optval;
14301 		break;
14302 	case TCP_BBR_MAX_RTO:
14303 		BBR_OPTS_INC(tcp_bbr_max_rto);
14304 		bbr->rc_max_rto_sec = optval;
14305 		break;
14306 	case TCP_RACK_MIN_TO:
14307 		/* Minimum time between rack t-o's in ms */
14308 		BBR_OPTS_INC(tcp_rack_min_to);
14309 		bbr->r_ctl.rc_min_to = optval;
14310 		break;
14311 	case TCP_RACK_REORD_THRESH:
14312 		/* RACK reorder threshold (shift amount) */
14313 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14314 		if ((optval > 0) && (optval < 31))
14315 			bbr->r_ctl.rc_reorder_shift = optval;
14316 		else
14317 			error = EINVAL;
14318 		break;
14319 	case TCP_RACK_REORD_FADE:
14320 		/* Does reordering fade after ms time */
14321 		BBR_OPTS_INC(tcp_rack_reord_fade);
14322 		bbr->r_ctl.rc_reorder_fade = optval;
14323 		break;
14324 	case TCP_RACK_TLP_THRESH:
14325 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14326 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14327 		if (optval)
14328 			bbr->rc_tlp_threshold = optval;
14329 		else
14330 			error = EINVAL;
14331 		break;
14332 	case TCP_BBR_USE_RACK_CHEAT:
14333 		BBR_OPTS_INC(tcp_use_rackcheat);
14334 		if (bbr->rc_use_google) {
14335 			error = EINVAL;
14336 			break;
14337 		}
14338 		BBR_OPTS_INC(tcp_rack_cheat);
14339 		if (optval)
14340 			bbr->bbr_use_rack_cheat = 1;
14341 		else
14342 			bbr->bbr_use_rack_cheat = 0;
14343 		break;
14344 	case TCP_BBR_FLOOR_MIN_TSO:
14345 		BBR_OPTS_INC(tcp_utter_max_tso);
14346 		if ((optval >= 0) && (optval < 40))
14347 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14348 		else
14349 			error = EINVAL;
14350 		break;
14351 	case TCP_BBR_UTTER_MAX_TSO:
14352 		BBR_OPTS_INC(tcp_utter_max_tso);
14353 		if ((optval >= 0) && (optval < 0xffff))
14354 			bbr->r_ctl.bbr_utter_max = optval;
14355 		else
14356 			error = EINVAL;
14357 		break;
14358 
14359 	case TCP_BBR_EXTRA_STATE:
14360 		BBR_OPTS_INC(tcp_extra_state);
14361 		if (optval)
14362 			bbr->rc_use_idle_restart = 1;
14363 		else
14364 			bbr->rc_use_idle_restart = 0;
14365 		break;
14366 	case TCP_BBR_SEND_IWND_IN_TSO:
14367 		BBR_OPTS_INC(tcp_iwnd_tso);
14368 		if (optval) {
14369 			bbr->bbr_init_win_cheat = 1;
14370 			if (bbr->rc_past_init_win == 0) {
14371 				uint32_t cts;
14372 				cts = tcp_get_usecs(&bbr->rc_tv);
14373 				tcp_bbr_tso_size_check(bbr, cts);
14374 			}
14375 		} else
14376 			bbr->bbr_init_win_cheat = 0;
14377 		break;
14378 	case TCP_BBR_HDWR_PACE:
14379 		BBR_OPTS_INC(tcp_hdwr_pacing);
14380 		if (optval){
14381 			bbr->bbr_hdw_pace_ena = 1;
14382 			bbr->bbr_attempt_hdwr_pace = 0;
14383 		} else {
14384 			bbr->bbr_hdw_pace_ena = 0;
14385 #ifdef RATELIMIT
14386 			if (bbr->r_ctl.crte != NULL) {
14387 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14388 				bbr->r_ctl.crte = NULL;
14389 			}
14390 #endif
14391 		}
14392 		break;
14393 
14394 	case TCP_DELACK:
14395 		BBR_OPTS_INC(tcp_delack);
14396 		if (optval < 100) {
14397 			if (optval == 0) /* off */
14398 				tp->t_delayed_ack = 0;
14399 			else if (optval == 1) /* on which is 2 */
14400 				tp->t_delayed_ack = 2;
14401 			else /* higher than 2 and less than 100 */
14402 				tp->t_delayed_ack = optval;
14403 			if (tp->t_flags & TF_DELACK) {
14404 				tp->t_flags &= ~TF_DELACK;
14405 				tp->t_flags |= TF_ACKNOW;
14406 				NET_EPOCH_ENTER(et);
14407 				bbr_output(tp);
14408 				NET_EPOCH_EXIT(et);
14409 			}
14410 		} else
14411 			error = EINVAL;
14412 		break;
14413 	case TCP_RACK_PKT_DELAY:
14414 		/* RACK added ms i.e. rack-rtt + reord + N */
14415 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14416 		bbr->r_ctl.rc_pkt_delay = optval;
14417 		break;
14418 #ifdef NETFLIX_PEAKRATE
14419 	case TCP_MAXPEAKRATE:
14420 		BBR_OPTS_INC(tcp_maxpeak);
14421 		error = tcp_set_maxpeakrate(tp, optval);
14422 		if (!error)
14423 			tp->t_peakrate_thr = tp->t_maxpeakrate;
14424 		break;
14425 #endif
14426 	case TCP_BBR_RETRAN_WTSO:
14427 		BBR_OPTS_INC(tcp_retran_wtso);
14428 		if (optval)
14429 			bbr->rc_resends_use_tso = 1;
14430 		else
14431 			bbr->rc_resends_use_tso = 0;
14432 		break;
14433 	case TCP_DATA_AFTER_CLOSE:
14434 		BBR_OPTS_INC(tcp_data_ac);
14435 		if (optval)
14436 			bbr->rc_allow_data_af_clo = 1;
14437 		else
14438 			bbr->rc_allow_data_af_clo = 0;
14439 		break;
14440 	case TCP_BBR_POLICER_DETECT:
14441 		BBR_OPTS_INC(tcp_policer_det);
14442 		if (bbr->rc_use_google == 0)
14443 			error = EINVAL;
14444 		else if (optval)
14445 			bbr->r_use_policer = 1;
14446 		else
14447 			bbr->r_use_policer = 0;
14448 		break;
14449 
14450 	case TCP_BBR_TSTMP_RAISES:
14451 		BBR_OPTS_INC(tcp_ts_raises);
14452 		if (optval)
14453 			bbr->ts_can_raise = 1;
14454 		else
14455 			bbr->ts_can_raise = 0;
14456 		break;
14457 	case TCP_BBR_TMR_PACE_OH:
14458 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14459 		if (bbr->rc_use_google) {
14460 			error = EINVAL;
14461 		} else {
14462 			if (optval)
14463 				bbr->r_ctl.rc_incr_tmrs = 1;
14464 			else
14465 				bbr->r_ctl.rc_incr_tmrs = 0;
14466 		}
14467 		break;
14468 	case TCP_BBR_PACE_OH:
14469 		BBR_OPTS_INC(tcp_pacing_oh);
14470 		if (bbr->rc_use_google) {
14471 			error = EINVAL;
14472 		} else {
14473 			if (optval > (BBR_INCL_TCP_OH|
14474 				      BBR_INCL_IP_OH|
14475 				      BBR_INCL_ENET_OH)) {
14476 				error = EINVAL;
14477 				break;
14478 			}
14479 			if (optval & BBR_INCL_TCP_OH)
14480 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14481 			else
14482 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14483 			if (optval & BBR_INCL_IP_OH)
14484 				bbr->r_ctl.rc_inc_ip_oh = 1;
14485 			else
14486 				bbr->r_ctl.rc_inc_ip_oh = 0;
14487 			if (optval & BBR_INCL_ENET_OH)
14488 				bbr->r_ctl.rc_inc_enet_oh = 1;
14489 			else
14490 				bbr->r_ctl.rc_inc_enet_oh = 0;
14491 		}
14492 		break;
14493 	default:
14494 		return (tcp_default_ctloutput(inp, sopt));
14495 		break;
14496 	}
14497 #ifdef NETFLIX_STATS
14498 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14499 #endif
14500 	INP_WUNLOCK(inp);
14501 	return (error);
14502 }
14503 
14504 /*
14505  * return 0 on success, error-num on failure
14506  */
14507 static int
14508 bbr_get_sockopt(struct inpcb *inp, struct sockopt *sopt)
14509 {
14510 	struct tcpcb *tp;
14511 	struct tcp_bbr *bbr;
14512 	int32_t error, optval;
14513 
14514 	tp = intotcpcb(inp);
14515 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14516 	if (bbr == NULL) {
14517 		INP_WUNLOCK(inp);
14518 		return (EINVAL);
14519 	}
14520 	/*
14521 	 * Because all our options are either boolean or an int, we can just
14522 	 * pull everything into optval and then unlock and copy. If we ever
14523 	 * add a option that is not a int, then this will have quite an
14524 	 * impact to this routine.
14525 	 */
14526 	switch (sopt->sopt_name) {
14527 	case TCP_BBR_PACE_PER_SEC:
14528 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14529 		break;
14530 	case TCP_BBR_PACE_DEL_TAR:
14531 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14532 		break;
14533 	case TCP_BBR_PACE_SEG_MAX:
14534 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14535 		break;
14536 	case TCP_BBR_MIN_TOPACEOUT:
14537 		optval = bbr->no_pacing_until;
14538 		break;
14539 	case TCP_BBR_PACE_SEG_MIN:
14540 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14541 		break;
14542 	case TCP_BBR_PACE_CROSS:
14543 		optval = bbr->r_ctl.bbr_cross_over;
14544 		break;
14545 	case TCP_BBR_ALGORITHM:
14546 		optval = bbr->rc_use_google;
14547 		break;
14548 	case TCP_BBR_TSLIMITS:
14549 		optval = bbr->rc_use_ts_limit;
14550 		break;
14551 	case TCP_BBR_IWINTSO:
14552 		optval = bbr->rc_init_win;
14553 		break;
14554 	case TCP_BBR_STARTUP_PG:
14555 		optval = bbr->r_ctl.rc_startup_pg;
14556 		break;
14557 	case TCP_BBR_DRAIN_PG:
14558 		optval = bbr->r_ctl.rc_drain_pg;
14559 		break;
14560 	case TCP_BBR_PROBE_RTT_INT:
14561 		optval = bbr->r_ctl.rc_probertt_int;
14562 		break;
14563 	case TCP_BBR_PROBE_RTT_LEN:
14564 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14565 		break;
14566 	case TCP_BBR_PROBE_RTT_GAIN:
14567 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14568 		break;
14569 	case TCP_BBR_STARTUP_LOSS_EXIT:
14570 		optval = bbr->rc_loss_exit;
14571 		break;
14572 	case TCP_BBR_USEDEL_RATE:
14573 		error = EINVAL;
14574 		break;
14575 	case TCP_BBR_MIN_RTO:
14576 		optval = bbr->r_ctl.rc_min_rto_ms;
14577 		break;
14578 	case TCP_BBR_MAX_RTO:
14579 		optval = bbr->rc_max_rto_sec;
14580 		break;
14581 	case TCP_RACK_PACE_MAX_SEG:
14582 		/* Max segments in a pace */
14583 		optval = bbr->r_ctl.rc_pace_max_segs;
14584 		break;
14585 	case TCP_RACK_MIN_TO:
14586 		/* Minimum time between rack t-o's in ms */
14587 		optval = bbr->r_ctl.rc_min_to;
14588 		break;
14589 	case TCP_RACK_REORD_THRESH:
14590 		/* RACK reorder threshold (shift amount) */
14591 		optval = bbr->r_ctl.rc_reorder_shift;
14592 		break;
14593 	case TCP_RACK_REORD_FADE:
14594 		/* Does reordering fade after ms time */
14595 		optval = bbr->r_ctl.rc_reorder_fade;
14596 		break;
14597 	case TCP_BBR_USE_RACK_CHEAT:
14598 		/* Do we use the rack cheat for rxt */
14599 		optval = bbr->bbr_use_rack_cheat;
14600 		break;
14601 	case TCP_BBR_FLOOR_MIN_TSO:
14602 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14603 		break;
14604 	case TCP_BBR_UTTER_MAX_TSO:
14605 		optval = bbr->r_ctl.bbr_utter_max;
14606 		break;
14607 	case TCP_BBR_SEND_IWND_IN_TSO:
14608 		/* Do we send TSO size segments initially */
14609 		optval = bbr->bbr_init_win_cheat;
14610 		break;
14611 	case TCP_BBR_EXTRA_STATE:
14612 		optval = bbr->rc_use_idle_restart;
14613 		break;
14614 	case TCP_RACK_TLP_THRESH:
14615 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14616 		optval = bbr->rc_tlp_threshold;
14617 		break;
14618 	case TCP_RACK_PKT_DELAY:
14619 		/* RACK added ms i.e. rack-rtt + reord + N */
14620 		optval = bbr->r_ctl.rc_pkt_delay;
14621 		break;
14622 	case TCP_BBR_RETRAN_WTSO:
14623 		optval = bbr->rc_resends_use_tso;
14624 		break;
14625 	case TCP_DATA_AFTER_CLOSE:
14626 		optval = bbr->rc_allow_data_af_clo;
14627 		break;
14628 	case TCP_DELACK:
14629 		optval = tp->t_delayed_ack;
14630 		break;
14631 	case TCP_BBR_HDWR_PACE:
14632 		optval = bbr->bbr_hdw_pace_ena;
14633 		break;
14634 	case TCP_BBR_POLICER_DETECT:
14635 		optval = bbr->r_use_policer;
14636 		break;
14637 	case TCP_BBR_TSTMP_RAISES:
14638 		optval = bbr->ts_can_raise;
14639 		break;
14640 	case TCP_BBR_TMR_PACE_OH:
14641 		optval = bbr->r_ctl.rc_incr_tmrs;
14642 		break;
14643 	case TCP_BBR_PACE_OH:
14644 		optval = 0;
14645 		if (bbr->r_ctl.rc_inc_tcp_oh)
14646 			optval |= BBR_INCL_TCP_OH;
14647 		if (bbr->r_ctl.rc_inc_ip_oh)
14648 			optval |= BBR_INCL_IP_OH;
14649 		if (bbr->r_ctl.rc_inc_enet_oh)
14650 			optval |= BBR_INCL_ENET_OH;
14651 		break;
14652 	default:
14653 		return (tcp_default_ctloutput(inp, sopt));
14654 		break;
14655 	}
14656 	INP_WUNLOCK(inp);
14657 	error = sooptcopyout(sopt, &optval, sizeof optval);
14658 	return (error);
14659 }
14660 
14661 /*
14662  * return 0 on success, error-num on failure
14663  */
14664 static int
14665 bbr_ctloutput(struct inpcb *inp, struct sockopt *sopt)
14666 {
14667 	if (sopt->sopt_dir == SOPT_SET) {
14668 		return (bbr_set_sockopt(inp, sopt));
14669 	} else if (sopt->sopt_dir == SOPT_GET) {
14670 		return (bbr_get_sockopt(inp, sopt));
14671 	} else {
14672 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14673 	}
14674 }
14675 
14676 static const char *bbr_stack_names[] = {
14677 	__XSTRING(STACKNAME),
14678 #ifdef STACKALIAS
14679 	__XSTRING(STACKALIAS),
14680 #endif
14681 };
14682 
14683 static bool bbr_mod_inited = false;
14684 
14685 static int
14686 tcp_addbbr(module_t mod, int32_t type, void *data)
14687 {
14688 	int32_t err = 0;
14689 	int num_stacks;
14690 
14691 	switch (type) {
14692 	case MOD_LOAD:
14693 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14694 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14695 		    sizeof(struct bbr_sendmap),
14696 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14697 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14698 		    sizeof(struct tcp_bbr),
14699 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14700 		sysctl_ctx_init(&bbr_sysctl_ctx);
14701 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14702 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14703 		    OID_AUTO,
14704 #ifdef STACKALIAS
14705 		    __XSTRING(STACKALIAS),
14706 #else
14707 		    __XSTRING(STACKNAME),
14708 #endif
14709 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14710 		    "");
14711 		if (bbr_sysctl_root == NULL) {
14712 			printf("Failed to add sysctl node\n");
14713 			err = EFAULT;
14714 			goto free_uma;
14715 		}
14716 		bbr_init_sysctls();
14717 		num_stacks = nitems(bbr_stack_names);
14718 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14719 		    bbr_stack_names, &num_stacks);
14720 		if (err) {
14721 			printf("Failed to register %s stack name for "
14722 			    "%s module\n", bbr_stack_names[num_stacks],
14723 			    __XSTRING(MODNAME));
14724 			sysctl_ctx_free(&bbr_sysctl_ctx);
14725 	free_uma:
14726 			uma_zdestroy(bbr_zone);
14727 			uma_zdestroy(bbr_pcb_zone);
14728 			bbr_counter_destroy();
14729 			printf("Failed to register " __XSTRING(MODNAME)
14730 			    " module err:%d\n", err);
14731 			return (err);
14732 		}
14733 		tcp_lro_reg_mbufq();
14734 		bbr_mod_inited = true;
14735 		printf(__XSTRING(MODNAME) " is now available\n");
14736 		break;
14737 	case MOD_QUIESCE:
14738 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14739 		break;
14740 	case MOD_UNLOAD:
14741 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14742 		if (err == EBUSY)
14743 			break;
14744 		if (bbr_mod_inited) {
14745 			uma_zdestroy(bbr_zone);
14746 			uma_zdestroy(bbr_pcb_zone);
14747 			sysctl_ctx_free(&bbr_sysctl_ctx);
14748 			bbr_counter_destroy();
14749 			printf(__XSTRING(MODNAME)
14750 			    " is now no longer available\n");
14751 			bbr_mod_inited = false;
14752 		}
14753 		tcp_lro_dereg_mbufq();
14754 		err = 0;
14755 		break;
14756 	default:
14757 		return (EOPNOTSUPP);
14758 	}
14759 	return (err);
14760 }
14761 
14762 static moduledata_t tcp_bbr = {
14763 	.name = __XSTRING(MODNAME),
14764 	    .evhand = tcp_addbbr,
14765 	    .priv = 0
14766 };
14767 
14768 MODULE_VERSION(MODNAME, 1);
14769 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14770 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14771