xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision 3332f1b444d4a73238e9f59cca27bfc95fe936bd)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 #include "opt_ratelimit.h"
41 #include <sys/param.h>
42 #include <sys/arb.h>
43 #include <sys/module.h>
44 #include <sys/kernel.h>
45 #include <sys/libkern.h>
46 #ifdef TCP_HHOOK
47 #include <sys/hhook.h>
48 #endif
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/proc.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/systm.h>
56 #ifdef STATS
57 #include <sys/qmath.h>
58 #include <sys/tree.h>
59 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
60 #endif
61 #include <sys/refcount.h>
62 #include <sys/queue.h>
63 #include <sys/eventhandler.h>
64 #include <sys/smp.h>
65 #include <sys/kthread.h>
66 #include <sys/lock.h>
67 #include <sys/mutex.h>
68 #include <sys/tim_filter.h>
69 #include <sys/time.h>
70 #include <sys/protosw.h>
71 #include <vm/uma.h>
72 #include <sys/kern_prefetch.h>
73 
74 #include <net/route.h>
75 #include <net/route/nhop.h>
76 #include <net/vnet.h>
77 
78 #define TCPSTATES		/* for logging */
79 
80 #include <netinet/in.h>
81 #include <netinet/in_kdtrace.h>
82 #include <netinet/in_pcb.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
85 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
86 #include <netinet/ip_var.h>
87 #include <netinet/ip6.h>
88 #include <netinet6/in6_pcb.h>
89 #include <netinet6/ip6_var.h>
90 #define	TCPOUTFLAGS
91 #include <netinet/tcp.h>
92 #include <netinet/tcp_fsm.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcpip.h>
97 #include <netinet/tcp_hpts.h>
98 #include <netinet/cc/cc.h>
99 #include <netinet/tcp_log_buf.h>
100 #include <netinet/tcp_ratelimit.h>
101 #include <netinet/tcp_lro.h>
102 #ifdef TCPDEBUG
103 #include <netinet/tcp_debug.h>
104 #endif				/* TCPDEBUG */
105 #ifdef TCP_OFFLOAD
106 #include <netinet/tcp_offload.h>
107 #endif
108 #ifdef INET6
109 #include <netinet6/tcp6_var.h>
110 #endif
111 #include <netinet/tcp_fastopen.h>
112 
113 #include <netipsec/ipsec_support.h>
114 #include <net/if.h>
115 #include <net/if_var.h>
116 #include <net/ethernet.h>
117 
118 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
119 #include <netipsec/ipsec.h>
120 #include <netipsec/ipsec6.h>
121 #endif				/* IPSEC */
122 
123 #include <netinet/udp.h>
124 #include <netinet/udp_var.h>
125 #include <machine/in_cksum.h>
126 
127 #ifdef MAC
128 #include <security/mac/mac_framework.h>
129 #endif
130 
131 #include "sack_filter.h"
132 #include "tcp_bbr.h"
133 #include "rack_bbr_common.h"
134 uma_zone_t bbr_zone;
135 uma_zone_t bbr_pcb_zone;
136 
137 struct sysctl_ctx_list bbr_sysctl_ctx;
138 struct sysctl_oid *bbr_sysctl_root;
139 
140 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
141 	(tv) = (value); \
142 	if ((u_long)(tv) < (u_long)(tvmin)) \
143 		(tv) = (tvmin); \
144 	if ((u_long)(tv) > (u_long)(tvmax)) \
145 		(tv) = (tvmax); \
146 } while(0)
147 
148 /*#define BBR_INVARIANT 1*/
149 
150 /*
151  * initial window
152  */
153 static uint32_t bbr_def_init_win = 10;
154 static int32_t bbr_persist_min = 250000;	/* 250ms */
155 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
156 static int32_t bbr_cwnd_may_shrink = 0;
157 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
158 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
159 static int32_t bbr_hardware_pacing_limit = 8000;
160 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
161 static int32_t bbr_no_retran = 0;
162 
163 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
164 static int32_t bbr_max_net_error_cnt = 10;
165 /* Should the following be dynamic too -- loss wise */
166 static int32_t bbr_rtt_gain_thresh = 0;
167 /* Measurement controls */
168 static int32_t bbr_use_google_algo = 1;
169 static int32_t bbr_ts_limiting = 1;
170 static int32_t bbr_ts_can_raise = 0;
171 static int32_t bbr_do_red = 600;
172 static int32_t bbr_red_scale = 20000;
173 static int32_t bbr_red_mul = 1;
174 static int32_t bbr_red_div = 2;
175 static int32_t bbr_red_growth_restrict = 1;
176 static int32_t  bbr_target_is_bbunit = 0;
177 static int32_t bbr_drop_limit = 0;
178 /*
179  * How much gain do we need to see to
180  * stay in startup?
181  */
182 static int32_t bbr_marks_rxt_sack_passed = 0;
183 static int32_t bbr_start_exit = 25;
184 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
185 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
186 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
187 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
188 					 * if we go back ever to where the pacer
189 					 * has priority over timers.
190 					 */
191 static int32_t bbr_policer_call_from_rack_to = 0;
192 static int32_t bbr_policer_detection_enabled = 1;
193 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
194 						 * measurments before we are
195 						 * "good" note that 2 == 1.
196 						 * This is because we use a >
197 						 * comparison. This means if
198 						 * min_measure was 0, it takes
199 						 * num-measures > min(0) and
200 						 * you get 1 measurement and
201 						 * you are good. Set to 1, you
202 						 * have to have two
203 						 * measurements (this is done
204 						 * to prevent it from being ok
205 						 * to have no measurements). */
206 static int32_t bbr_no_pacing_until = 4;
207 
208 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
209 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
210 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
211 
212 static int32_t bbr_target_cwnd_mult_limit = 8;
213 /*
214  * bbr_cwnd_min_val is the number of
215  * segments we hold to in the RTT probe
216  * state typically 4.
217  */
218 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
219 
220 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
221 
222 static int32_t bbr_gain_to_target = 1;
223 static int32_t bbr_gain_gets_extra_too = 1;
224 /*
225  * bbr_high_gain is the 2/ln(2) value we need
226  * to double the sending rate in startup. This
227  * is used for both cwnd and hptsi gain's.
228  */
229 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
230 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
231 static int32_t bbr_use_lower_gain_in_startup = 1;
232 
233 /* thresholds for reduction on drain in sub-states/drain */
234 static int32_t bbr_drain_rtt = BBR_SRTT;
235 static int32_t bbr_drain_floor = 88;
236 static int32_t google_allow_early_out = 1;
237 static int32_t google_consider_lost = 1;
238 static int32_t bbr_drain_drop_mul = 4;
239 static int32_t bbr_drain_drop_div = 5;
240 static int32_t bbr_rand_ot = 50;
241 static int32_t bbr_can_force_probertt = 0;
242 static int32_t bbr_can_adjust_probertt = 1;
243 static int32_t bbr_probertt_sets_rtt = 0;
244 static int32_t bbr_can_use_ts_for_rtt = 1;
245 static int32_t bbr_is_ratio = 0;
246 static int32_t bbr_sub_drain_app_limit = 1;
247 static int32_t bbr_prtt_slam_cwnd = 1;
248 static int32_t bbr_sub_drain_slam_cwnd = 1;
249 static int32_t bbr_slam_cwnd_in_main_drain = 1;
250 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
251 					 * hold */
252 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
253 /*
254  * bbr_drain_gain is the reverse of the high_gain
255  * designed to drain back out the standing queue
256  * that is formed in startup by causing a larger
257  * hptsi gain and thus drainging the packets
258  * in flight.
259  */
260 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
261 static int32_t bbr_rttprobe_gain = 192;
262 
263 /*
264  * The cwnd_gain is the default cwnd gain applied when
265  * calculating a target cwnd. Note that the cwnd is
266  * a secondary factor in the way BBR works (see the
267  * paper and think about it, it will take some time).
268  * Basically the hptsi_gain spreads the packets out
269  * so you never get more than BDP to the peer even
270  * if the cwnd is high. In our implemenation that
271  * means in non-recovery/retransmission scenarios
272  * cwnd will never be reached by the flight-size.
273  */
274 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
275 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
276 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
277 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
278 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
279 static int32_t bbr_ignore_data_after_close = 1;
280 static int16_t bbr_hptsi_gain[] = {
281 	(BBR_UNIT *5 / 4),
282 	(BBR_UNIT * 3 / 4),
283 	BBR_UNIT,
284 	BBR_UNIT,
285 	BBR_UNIT,
286 	BBR_UNIT,
287 	BBR_UNIT,
288 	BBR_UNIT
289 };
290 int32_t bbr_use_rack_resend_cheat = 1;
291 int32_t bbr_sends_full_iwnd = 1;
292 
293 #define BBR_HPTSI_GAIN_MAX 8
294 /*
295  * The BBR module incorporates a number of
296  * TCP ideas that have been put out into the IETF
297  * over the last few years:
298  * - Yuchung Cheng's RACK TCP (for which its named) that
299  *    will stop us using the number of dup acks and instead
300  *    use time as the gage of when we retransmit.
301  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
302  *    of Dukkipati et.al.
303  * - Van Jacobson's et.al BBR.
304  *
305  * RACK depends on SACK, so if an endpoint arrives that
306  * cannot do SACK the state machine below will shuttle the
307  * connection back to using the "default" TCP stack that is
308  * in FreeBSD.
309  *
310  * To implement BBR and RACK the original TCP stack was first decomposed
311  * into a functional state machine with individual states
312  * for each of the possible TCP connection states. The do_segement
313  * functions role in life is to mandate the connection supports SACK
314  * initially and then assure that the RACK state matches the conenction
315  * state before calling the states do_segment function. Data processing
316  * of inbound segments also now happens in the hpts_do_segment in general
317  * with only one exception. This is so we can keep the connection on
318  * a single CPU.
319  *
320  * Each state is simplified due to the fact that the original do_segment
321  * has been decomposed and we *know* what state we are in (no
322  * switches on the state) and all tests for SACK are gone. This
323  * greatly simplifies what each state does.
324  *
325  * TCP output is also over-written with a new version since it
326  * must maintain the new rack scoreboard and has had hptsi
327  * integrated as a requirment. Still todo is to eliminate the
328  * use of the callout_() system and use the hpts for all
329  * timers as well.
330  */
331 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
332 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
333 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
334 						 * free list */
335 static int32_t bbr_tlp_thresh = 1;
336 static int32_t bbr_reorder_thresh = 2;
337 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
338 						 * 60,000,000 - 60 seconds */
339 static int32_t bbr_pkt_delay = 1000;
340 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
341 static int32_t bbr_incr_timers = 1;
342 
343 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
344 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
345 static int32_t bbr_exit_startup_at_loss = 1;
346 
347 /*
348  * bbr_lt_bw_ratio is 1/8th
349  * bbr_lt_bw_diff is  < 4 Kbit/sec
350  */
351 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
352 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
353 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
354 						 * the lt_bw for */
355 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
356 						 * lt_bw */
357 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
358 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
359 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
360 
361 static int32_t bbr_verbose_logging = 0;
362 /*
363  * Currently regular tcp has a rto_min of 30ms
364  * the backoff goes 12 times so that ends up
365  * being a total of 122.850 seconds before a
366  * connection is killed.
367  */
368 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
369 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
370 
371 /****************************************************/
372 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
373 /****************************************************/
374 /* What amount is our formula using to get TSO size */
375 static int32_t bbr_hptsi_per_second = 1000;
376 
377 /*
378  * For hptsi under bbr_cross_over connections what is delay
379  * target 7ms (in usec) combined with a seg_max of 2
380  * gets us close to identical google behavior in
381  * TSO size selection (possibly more 1MSS sends).
382  */
383 static int32_t bbr_hptsi_segments_delay_tar = 7000;
384 
385 /* Does pacing delay include overhead's in its time calculations? */
386 static int32_t bbr_include_enet_oh = 0;
387 static int32_t bbr_include_ip_oh = 1;
388 static int32_t bbr_include_tcp_oh = 1;
389 static int32_t bbr_google_discount = 10;
390 
391 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
392 static int32_t bbr_state_is_pkt_epoch = 0;
393 static int32_t bbr_state_drain_2_tar = 1;
394 /* What is the max the 0 - bbr_cross_over MBPS TSO target
395  * can reach using our delay target. Note that this
396  * value becomes the floor for the cross over
397  * algorithm.
398  */
399 static int32_t bbr_hptsi_segments_max = 2;
400 static int32_t bbr_hptsi_segments_floor = 1;
401 static int32_t bbr_hptsi_utter_max = 0;
402 
403 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
404 static int32_t bbr_hptsi_bytes_min = 1460;
405 static int32_t bbr_all_get_min = 0;
406 
407 /* Cross over point from algo-a to algo-b */
408 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
409 
410 /* Do we deal with our restart state? */
411 static int32_t bbr_uses_idle_restart = 0;
412 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
413 
414 /* Do we allow hardware pacing? */
415 static int32_t bbr_allow_hdwr_pacing = 0;
416 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
417 static int32_t bbr_hdwr_pace_floor = 1;
418 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
419 
420 /****************************************************/
421 static int32_t bbr_resends_use_tso = 0;
422 static int32_t bbr_tlp_max_resend = 2;
423 static int32_t bbr_sack_block_limit = 128;
424 
425 #define  BBR_MAX_STAT 19
426 counter_u64_t bbr_state_time[BBR_MAX_STAT];
427 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
428 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
429 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
430 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
431 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
432 counter_u64_t bbr_flows_whdwr_pacing;
433 counter_u64_t bbr_flows_nohdwr_pacing;
434 
435 counter_u64_t bbr_nohdwr_pacing_enobuf;
436 counter_u64_t bbr_hdwr_pacing_enobuf;
437 
438 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
439 
440 /*
441  * Static defintions we need for forward declarations.
442  */
443 static uint32_t
444 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
445     uint32_t useconds_time, uint64_t bw);
446 static uint32_t
447 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
448 static void
449      bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
450 static void
451 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
452 static void
453 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
454 		    int dolog);
455 static uint32_t
456 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
457 static void
458 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
459 		 int32_t pkt_epoch, uint32_t losses);
460 static uint32_t
461 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm);
462 static uint32_t bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
463 static uint32_t
464 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
465     struct bbr_sendmap *rsm, uint32_t srtt,
466     uint32_t cts);
467 static void
468 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
469     int32_t line);
470 static void
471      bbr_set_state_target(struct tcp_bbr *bbr, int line);
472 static void
473      bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
474 
475 static void
476      bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line);
477 
478 static void
479      tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
480 
481 static void
482      bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
483 
484 static void
485      bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied, uint32_t rtt,
486 			 uint32_t line, uint8_t is_start, uint16_t set);
487 
488 static struct bbr_sendmap *
489 	    bbr_find_lowest_rsm(struct tcp_bbr *bbr);
490 static __inline uint32_t
491 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
492 static void
493      bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which);
494 
495 static void
496 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
497     uint32_t thresh, uint32_t to);
498 static void
499      bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
500 
501 static void
502 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
503     uint32_t del_by, uint32_t cts, uint32_t sloton, uint32_t prev_delay);
504 
505 static void
506 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr,
507     uint32_t cts, int32_t line);
508 static void
509      bbr_stop_all_timers(struct tcpcb *tp);
510 static void
511      bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
512 static void
513      bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
514 static void
515      bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
516 
517 static void
518 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
519     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod);
520 
521 static int
522 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp,
523     struct tcpcb *tp);
524 
525 static inline uint8_t
526 bbr_state_val(struct tcp_bbr *bbr)
527 {
528 	return(bbr->rc_bbr_substate);
529 }
530 
531 static inline uint32_t
532 get_min_cwnd(struct tcp_bbr *bbr)
533 {
534 	int mss;
535 
536 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
537 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
538 		return (bbr_cwnd_min_val_hs * mss);
539 	else
540 		return (bbr_cwnd_min_val * mss);
541 }
542 
543 static uint32_t
544 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
545 {
546 	uint64_t srtt, var;
547 	uint64_t ret_val;
548 
549 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
550 	if (tp->t_srtt == 0) {
551 		srtt = (uint64_t)BBR_INITIAL_RTO;
552 		var = 0;
553 	} else {
554 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
555 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
556 	}
557 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
558 	    bbr_persist_min, bbr_persist_max);
559 	return ((uint32_t)ret_val);
560 }
561 
562 static uint32_t
563 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
564 {
565 	/*
566 	 * Start the FR timer, we do this based on getting the first one in
567 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
568 	 * events we need to stop the running timer (if its running) before
569 	 * starting the new one.
570 	 */
571 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
572 	int32_t idx;
573 	int32_t is_tlp_timer = 0;
574 	struct bbr_sendmap *rsm;
575 
576 	if (bbr->rc_all_timers_stopped) {
577 		/* All timers have been stopped none are to run */
578 		return (0);
579 	}
580 	if (bbr->rc_in_persist) {
581 		/* We can't start any timer in persists */
582 		return (bbr_get_persists_timer_val(tp, bbr));
583 	}
584 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
585 	if ((rsm == NULL) ||
586 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
587 	    (tp->t_state < TCPS_ESTABLISHED)) {
588 		/* Nothing on the send map */
589 activate_rxt:
590 		if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
591 			uint64_t tov;
592 
593 			time_since_sent = 0;
594 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
595 			if (rsm) {
596 				idx = rsm->r_rtr_cnt - 1;
597 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
598 					tstmp_touse = rsm->r_tim_lastsent[idx];
599 				else
600 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
601 				if (TSTMP_GT(tstmp_touse, cts))
602 				    time_since_sent = cts - tstmp_touse;
603 			}
604 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
605 			if (tp->t_srtt == 0)
606 				tov = BBR_INITIAL_RTO;
607 			else
608 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
609 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
610 			if (tp->t_rxtshift)
611 				tov *= tcp_backoff[tp->t_rxtshift];
612 			if (tov > time_since_sent)
613 				tov -= time_since_sent;
614 			else
615 				tov = bbr->r_ctl.rc_min_to;
616 			TCPT_RANGESET_NOSLOP(to, tov,
617 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
618 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
619 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
620 			return (to);
621 		}
622 		return (0);
623 	}
624 	if (rsm->r_flags & BBR_ACKED) {
625 		rsm = bbr_find_lowest_rsm(bbr);
626 		if (rsm == NULL) {
627 			/* No lowest? */
628 			goto activate_rxt;
629 		}
630 	}
631 	/* Convert from ms to usecs */
632 	if (rsm->r_flags & BBR_SACK_PASSED) {
633 		if ((tp->t_flags & TF_SENTFIN) &&
634 		    ((tp->snd_max - tp->snd_una) == 1) &&
635 		    (rsm->r_flags & BBR_HAS_FIN)) {
636 			/*
637 			 * We don't start a bbr rack timer if all we have is
638 			 * a FIN outstanding.
639 			 */
640 			goto activate_rxt;
641 		}
642 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
643 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
644 		idx = rsm->r_rtr_cnt - 1;
645 		exp = rsm->r_tim_lastsent[idx] + thresh;
646 		if (SEQ_GEQ(exp, cts)) {
647 			to = exp - cts;
648 			if (to < bbr->r_ctl.rc_min_to) {
649 				to = bbr->r_ctl.rc_min_to;
650 			}
651 		} else {
652 			to = bbr->r_ctl.rc_min_to;
653 		}
654 	} else {
655 		/* Ok we need to do a TLP not RACK */
656 		if (bbr->rc_tlp_in_progress != 0) {
657 			/*
658 			 * The previous send was a TLP.
659 			 */
660 			goto activate_rxt;
661 		}
662 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
663 		if (rsm == NULL) {
664 			/* We found no rsm to TLP with. */
665 			goto activate_rxt;
666 		}
667 		if (rsm->r_flags & BBR_HAS_FIN) {
668 			/* If its a FIN we don't do TLP */
669 			rsm = NULL;
670 			goto activate_rxt;
671 		}
672 		time_since_sent = 0;
673 		idx = rsm->r_rtr_cnt - 1;
674 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
675 			tstmp_touse = rsm->r_tim_lastsent[idx];
676 		else
677 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
678 		if (TSTMP_GT(tstmp_touse, cts))
679 		    time_since_sent = cts - tstmp_touse;
680 		is_tlp_timer = 1;
681 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
682 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
683 		if (thresh > time_since_sent)
684 			to = thresh - time_since_sent;
685 		else
686 			to = bbr->r_ctl.rc_min_to;
687 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
688 			/*
689 			 * If the TLP time works out to larger than the max
690 			 * RTO lets not do TLP.. just RTO.
691 			 */
692 			goto activate_rxt;
693 		}
694 		if ((bbr->rc_tlp_rtx_out == 1) &&
695 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
696 			/*
697 			 * Second retransmit of the same TLP
698 			 * lets not.
699 			 */
700 			bbr->rc_tlp_rtx_out = 0;
701 			goto activate_rxt;
702 		}
703 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
704 			/*
705 			 * The tail is no longer the last one I did a probe
706 			 * on
707 			 */
708 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
709 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
710 		}
711 	}
712 	if (is_tlp_timer == 0) {
713 		BBR_STAT_INC(bbr_to_arm_rack);
714 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
715 	} else {
716 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
717 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
718 			/*
719 			 * We have exceeded how many times we can retran the
720 			 * current TLP timer, switch to the RTO timer.
721 			 */
722 			goto activate_rxt;
723 		} else {
724 			BBR_STAT_INC(bbr_to_arm_tlp);
725 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
726 		}
727 	}
728 	return (to);
729 }
730 
731 static inline int32_t
732 bbr_minseg(struct tcp_bbr *bbr)
733 {
734 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
735 }
736 
737 static void
738 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
739 {
740 	struct inpcb *inp;
741 	struct hpts_diag diag;
742 	uint32_t delayed_ack = 0;
743 	uint32_t left = 0;
744 	uint32_t hpts_timeout;
745 	uint8_t stopped;
746 	int32_t delay_calc = 0;
747 	uint32_t prev_delay = 0;
748 
749 	inp = tp->t_inpcb;
750 	if (inp->inp_in_hpts) {
751 		/* A previous call is already set up */
752 		return;
753 	}
754 	if ((tp->t_state == TCPS_CLOSED) ||
755 	    (tp->t_state == TCPS_LISTEN)) {
756 		return;
757 	}
758 	stopped = bbr->rc_tmr_stopped;
759 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
760 		left = bbr->r_ctl.rc_timer_exp - cts;
761 	}
762 	bbr->r_ctl.rc_hpts_flags = 0;
763 	bbr->r_ctl.rc_timer_exp = 0;
764 	prev_delay = bbr->r_ctl.rc_last_delay_val;
765 	if (bbr->r_ctl.rc_last_delay_val &&
766 	    (slot == 0)) {
767 		/*
768 		 * If a previous pacer delay was in place we
769 		 * are not coming from the output side (where
770 		 * we calculate a delay, more likely a timer).
771 		 */
772 		slot = bbr->r_ctl.rc_last_delay_val;
773 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
774 			/* Compensate for time passed  */
775 			delay_calc = cts - bbr->rc_pacer_started;
776 			if (delay_calc <= slot)
777 				slot -= delay_calc;
778 		}
779 	}
780 	/* Do we have early to make up for by pushing out the pacing time? */
781 	if (bbr->r_agg_early_set) {
782 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
783 		slot += bbr->r_ctl.rc_agg_early;
784 		bbr->r_ctl.rc_agg_early = 0;
785 		bbr->r_agg_early_set = 0;
786 	}
787 	/* Are we running a total debt that needs to be compensated for? */
788 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
789 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
790 			/* We nuke the delay */
791 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
792 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
793 		} else {
794 			/* We nuke some of the delay, put in a minimal 100usecs  */
795 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
796 			bbr->r_ctl.rc_last_delay_val = slot = 100;
797 		}
798 	}
799 	bbr->r_ctl.rc_last_delay_val = slot;
800 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
801 	if (tp->t_flags & TF_DELACK) {
802 		if (bbr->rc_in_persist == 0) {
803 			delayed_ack = bbr_delack_time;
804 		} else {
805 			/*
806 			 * We are in persists and have
807 			 * gotten a new data element.
808 			 */
809 			if (hpts_timeout > bbr_delack_time) {
810 				/*
811 				 * Lets make the persists timer (which acks)
812 				 * be the smaller of hpts_timeout and bbr_delack_time.
813 				 */
814 				hpts_timeout = bbr_delack_time;
815 			}
816 		}
817 	}
818 	if (delayed_ack &&
819 	    ((hpts_timeout == 0) ||
820 	     (delayed_ack < hpts_timeout))) {
821 		/* We need a Delayed ack timer */
822 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
823 		hpts_timeout = delayed_ack;
824 	}
825 	if (slot) {
826 		/* Mark that we have a pacing timer up */
827 		BBR_STAT_INC(bbr_paced_segments);
828 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
829 	}
830 	/*
831 	 * If no timers are going to run and we will fall off thfe hptsi
832 	 * wheel, we resort to a keep-alive timer if its configured.
833 	 */
834 	if ((hpts_timeout == 0) &&
835 	    (slot == 0)) {
836 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
837 		    (tp->t_state <= TCPS_CLOSING)) {
838 			/*
839 			 * Ok we have no timer (persists, rack, tlp, rxt  or
840 			 * del-ack), we don't have segments being paced. So
841 			 * all that is left is the keepalive timer.
842 			 */
843 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
844 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
845 			} else {
846 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
847 			}
848 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
849 		}
850 	}
851 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
852 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
853 		/*
854 		 * RACK, TLP, persists and RXT timers all are restartable
855 		 * based on actions input .. i.e we received a packet (ack
856 		 * or sack) and that changes things (rw, or snd_una etc).
857 		 * Thus we can restart them with a new value. For
858 		 * keep-alive, delayed_ack we keep track of what was left
859 		 * and restart the timer with a smaller value.
860 		 */
861 		if (left < hpts_timeout)
862 			hpts_timeout = left;
863 	}
864 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
865 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
866 		/*
867 		 * If configured to do so, and the timer is either
868 		 * the TLP or RXT timer, we need to increase the timeout
869 		 * by the pacing time. Consider the bottleneck at my
870 		 * machine as an example, we are sending something
871 		 * to start a TLP on. The last packet won't be emitted
872 		 * fully until the pacing time (the bottleneck will hold
873 		 * the data in place). Once the packet is emitted that
874 		 * is when we want to start waiting for the TLP. This
875 		 * is most evident with hardware pacing (where the nic
876 		 * is holding the packet(s) before emitting). But it
877 		 * can also show up in the network so we do it for all
878 		 * cases. Technically we would take off one packet from
879 		 * this extra delay but this is easier and being more
880 		 * conservative is probably better.
881 		 */
882 		hpts_timeout += slot;
883 	}
884 	if (hpts_timeout) {
885 		/*
886 		 * Hack alert for now we can't time-out over 2147 seconds (a
887 		 * bit more than 35min)
888 		 */
889 		if (hpts_timeout > 0x7ffffffe)
890 			hpts_timeout = 0x7ffffffe;
891 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
892 	} else
893 		bbr->r_ctl.rc_timer_exp = 0;
894 	if ((slot) &&
895 	    (bbr->rc_use_google ||
896 	     bbr->output_error_seen ||
897 	     (slot <= hpts_timeout))  ) {
898 		/*
899 		 * Tell LRO that it can queue packets while
900 		 * we pace.
901 		 */
902 		bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
903 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
904 		    (bbr->rc_cwnd_limited == 0)) {
905 			/*
906 			 * If we are not cwnd limited and we
907 			 * are running a rack timer we put on
908 			 * the do not disturbe even for sack.
909 			 */
910 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
911 		} else
912 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
913 		bbr->rc_pacer_started = cts;
914 
915 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(slot),
916 					   __LINE__, &diag);
917 		bbr->rc_timer_first = 0;
918 		bbr->bbr_timer_src = frm;
919 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
920 		bbr_log_hpts_diag(bbr, cts, &diag);
921 	} else if (hpts_timeout) {
922 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
923 					   __LINE__, &diag);
924 		/*
925 		 * We add the flag here as well if the slot is set,
926 		 * since hpts will call in to clear the queue first before
927 		 * calling the output routine (which does our timers).
928 		 * We don't want to set the flag if its just a timer
929 		 * else the arrival of data might (that causes us
930 		 * to send more) might get delayed. Imagine being
931 		 * on a keep-alive timer and a request comes in for
932 		 * more data.
933 		 */
934 		if (slot)
935 			bbr->rc_pacer_started = cts;
936 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
937 		    (bbr->rc_cwnd_limited == 0)) {
938 			/*
939 			 * For a rack timer, don't wake us even
940 			 * if a sack arrives as long as we are
941 			 * not cwnd limited.
942 			 */
943 			bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
944 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
945 		} else {
946 			/* All other timers wake us up */
947 			bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
948 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
949 		}
950 		bbr->bbr_timer_src = frm;
951 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
952 		bbr_log_hpts_diag(bbr, cts, &diag);
953 		bbr->rc_timer_first = 1;
954 	}
955 	bbr->rc_tmr_stopped = 0;
956 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
957 }
958 
959 static void
960 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
961 {
962 	/*
963 	 * We received an ack, and then did not call send or were bounced
964 	 * out due to the hpts was running. Now a timer is up as well, is it
965 	 * the right timer?
966 	 */
967 	struct inpcb *inp;
968 	struct bbr_sendmap *rsm;
969 	uint32_t hpts_timeout;
970 	int tmr_up;
971 
972 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
973 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
974 		return;
975 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
976 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
977 	    (tmr_up == PACE_TMR_RXT)) {
978 		/* Should be an RXT */
979 		return;
980 	}
981 	inp = bbr->rc_inp;
982 	if (rsm == NULL) {
983 		/* Nothing outstanding? */
984 		if (tp->t_flags & TF_DELACK) {
985 			if (tmr_up == PACE_TMR_DELACK)
986 				/*
987 				 * We are supposed to have delayed ack up
988 				 * and we do
989 				 */
990 				return;
991 		} else if (sbavail(&inp->inp_socket->so_snd) &&
992 		    (tmr_up == PACE_TMR_RXT)) {
993 			/*
994 			 * if we hit enobufs then we would expect the
995 			 * possiblity of nothing outstanding and the RXT up
996 			 * (and the hptsi timer).
997 			 */
998 			return;
999 		} else if (((V_tcp_always_keepalive ||
1000 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
1001 			    (tp->t_state <= TCPS_CLOSING)) &&
1002 			    (tmr_up == PACE_TMR_KEEP) &&
1003 		    (tp->snd_max == tp->snd_una)) {
1004 			/* We should have keep alive up and we do */
1005 			return;
1006 		}
1007 	}
1008 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1009 		if ((tp->t_flags & TF_SENTFIN) &&
1010 		    ((tp->snd_max - tp->snd_una) == 1) &&
1011 		    (rsm->r_flags & BBR_HAS_FIN)) {
1012 			/* needs to be a RXT */
1013 			if (tmr_up == PACE_TMR_RXT)
1014 				return;
1015 			else
1016 				goto wrong_timer;
1017 		} else if (tmr_up == PACE_TMR_RACK)
1018 			return;
1019 		else
1020 			goto wrong_timer;
1021 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1022 		/* Rack timer has priority if we have data out */
1023 		return;
1024 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1025 		    ((tmr_up == PACE_TMR_TLP) ||
1026 	    (tmr_up == PACE_TMR_RXT))) {
1027 		/*
1028 		 * Either a TLP or RXT is fine if no sack-passed is in place
1029 		 * and data is outstanding.
1030 		 */
1031 		return;
1032 	} else if (tmr_up == PACE_TMR_DELACK) {
1033 		/*
1034 		 * If the delayed ack was going to go off before the
1035 		 * rtx/tlp/rack timer were going to expire, then that would
1036 		 * be the timer in control. Note we don't check the time
1037 		 * here trusting the code is correct.
1038 		 */
1039 		return;
1040 	}
1041 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1042 	    ((tmr_up == PACE_TMR_RXT) ||
1043 	     (tmr_up == PACE_TMR_TLP) ||
1044 	     (tmr_up == PACE_TMR_RACK))) {
1045 		/*
1046 		 * We have outstanding data and
1047 		 * we *do* have a RACK, TLP or RXT
1048 		 * timer running. We won't restart
1049 		 * anything here since thats probably ok we
1050 		 * will get called with some timer here shortly.
1051 		 */
1052 		return;
1053 	}
1054 	/*
1055 	 * Ok the timer originally started is not what we want now. We will
1056 	 * force the hpts to be stopped if any, and restart with the slot
1057 	 * set to what was in the saved slot.
1058 	 */
1059 wrong_timer:
1060 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1061 		if (inp->inp_in_hpts)
1062 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
1063 		bbr_timer_cancel(bbr, __LINE__, cts);
1064 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1065 		    0);
1066 	} else {
1067 		/*
1068 		 * Output is hptsi so we just need to switch the type of
1069 		 * timer. We don't bother with keep-alive, since when we
1070 		 * jump through the output, it will start the keep-alive if
1071 		 * nothing is sent.
1072 		 *
1073 		 * We only need a delayed-ack added and or the hpts_timeout.
1074 		 */
1075 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1076 		if (tp->t_flags & TF_DELACK) {
1077 			if (hpts_timeout == 0) {
1078 				hpts_timeout = bbr_delack_time;
1079 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1080 			}
1081 			else if (hpts_timeout > bbr_delack_time) {
1082 				hpts_timeout = bbr_delack_time;
1083 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1084 			}
1085 		}
1086 		if (hpts_timeout) {
1087 			if (hpts_timeout > 0x7ffffffe)
1088 				hpts_timeout = 0x7ffffffe;
1089 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1090 		}
1091 	}
1092 }
1093 
1094 int32_t bbr_clear_lost = 0;
1095 
1096 /*
1097  * Considers the two time values now (cts) and earlier.
1098  * If cts is smaller than earlier, we could have
1099  * had a sequence wrap (our counter wraps every
1100  * 70 min or so) or it could be just clock skew
1101  * getting us two differnt time values. Clock skew
1102  * will show up within 10ms or so. So in such
1103  * a case (where cts is behind earlier time by
1104  * less than 10ms) we return 0. Otherwise we
1105  * return the true difference between them.
1106  */
1107 static inline uint32_t
1108 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1109 	/*
1110 	 * Given two timestamps, the current time stamp cts, and some other
1111 	 * time-stamp taken in theory earlier return the difference. The
1112 	 * trick is here sometimes locking will get the other timestamp
1113 	 * after the cts. If this occurs we need to return 0.
1114 	 */
1115 	if (TSTMP_GEQ(cts, earlier_time))
1116 		return (cts - earlier_time);
1117 	/*
1118 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1119 	 * If its more than 10ms difference then we had a time wrap. Else
1120 	 * its just the normal locking foo. I wonder if we should not go to
1121 	 * 64bit TS and get rid of this issue.
1122 	 */
1123 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1124 		return (0);
1125 	/*
1126 	 * Ok the time must have wrapped. So we need to answer a large
1127 	 * amount of time, which the normal subtraction should do.
1128 	 */
1129 	return (cts - earlier_time);
1130 }
1131 
1132 static int
1133 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1134 {
1135 	uint32_t stat;
1136 	int32_t error;
1137 
1138 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1139 	if (error || req->newptr == NULL)
1140 		return error;
1141 
1142 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1143 	if (error)
1144 		return (error);
1145 	if (stat == 1) {
1146 #ifdef BBR_INVARIANTS
1147 		printf("Clearing BBR lost counters\n");
1148 #endif
1149 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1150 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1151 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1152 	} else if (stat == 2) {
1153 #ifdef BBR_INVARIANTS
1154 		printf("Clearing BBR option counters\n");
1155 #endif
1156 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1157 	} else if (stat == 3) {
1158 #ifdef BBR_INVARIANTS
1159 		printf("Clearing BBR stats counters\n");
1160 #endif
1161 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1162 	} else if (stat == 4) {
1163 #ifdef BBR_INVARIANTS
1164 		printf("Clearing BBR out-size counters\n");
1165 #endif
1166 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1167 	}
1168 	bbr_clear_lost = 0;
1169 	return (0);
1170 }
1171 
1172 static void
1173 bbr_init_sysctls(void)
1174 {
1175 	struct sysctl_oid *bbr_probertt;
1176 	struct sysctl_oid *bbr_hptsi;
1177 	struct sysctl_oid *bbr_measure;
1178 	struct sysctl_oid *bbr_cwnd;
1179 	struct sysctl_oid *bbr_timeout;
1180 	struct sysctl_oid *bbr_states;
1181 	struct sysctl_oid *bbr_startup;
1182 	struct sysctl_oid *bbr_policer;
1183 
1184 	/* Probe rtt controls */
1185 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1186 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1187 	    OID_AUTO,
1188 	    "probertt",
1189 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1190 	    "");
1191 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1192 	    SYSCTL_CHILDREN(bbr_probertt),
1193 	    OID_AUTO, "gain", CTLFLAG_RW,
1194 	    &bbr_rttprobe_gain, 192,
1195 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1196 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1197 	    SYSCTL_CHILDREN(bbr_probertt),
1198 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1199 	    &bbr_rtt_probe_cwndtarg, 4,
1200 	    "How many mss's are outstanding during probe-rtt");
1201 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1202 	    SYSCTL_CHILDREN(bbr_probertt),
1203 	    OID_AUTO, "int", CTLFLAG_RW,
1204 	    &bbr_rtt_probe_limit, 4000000,
1205 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1206 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1207 	    SYSCTL_CHILDREN(bbr_probertt),
1208 	    OID_AUTO, "mintime", CTLFLAG_RW,
1209 	    &bbr_rtt_probe_time, 200000,
1210 	    "How many microseconds in probe-rtt");
1211 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1212 	    SYSCTL_CHILDREN(bbr_probertt),
1213 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1214 	    &bbr_filter_len_sec, 6,
1215 	    "How long in seconds does the rttProp filter run?");
1216 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1217 	    SYSCTL_CHILDREN(bbr_probertt),
1218 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1219 	    &bbr_drain_rtt, BBR_SRTT,
1220 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1221 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1222 	    SYSCTL_CHILDREN(bbr_probertt),
1223 	    OID_AUTO, "can_force", CTLFLAG_RW,
1224 	    &bbr_can_force_probertt, 0,
1225 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1226 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1227 	    SYSCTL_CHILDREN(bbr_probertt),
1228 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1229 	    &bbr_probertt_sets_rtt, 0,
1230 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1231 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1232 	    SYSCTL_CHILDREN(bbr_probertt),
1233 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1234 	    &bbr_can_adjust_probertt, 1,
1235 	    "Can we dynamically adjust the probe-rtt limits and times?");
1236 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1237 	    SYSCTL_CHILDREN(bbr_probertt),
1238 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1239 	    &bbr_is_ratio, 0,
1240 	    "is the limit to filter a ratio?");
1241 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1242 	    SYSCTL_CHILDREN(bbr_probertt),
1243 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1244 	    &bbr_prtt_slam_cwnd, 0,
1245 	    "Should we set/recover cwnd?");
1246 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1247 	    SYSCTL_CHILDREN(bbr_probertt),
1248 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1249 	    &bbr_can_use_ts_for_rtt, 1,
1250 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1251 
1252 	/* Pacing controls */
1253 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1254 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1255 	    OID_AUTO,
1256 	    "pacing",
1257 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1258 	    "");
1259 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1260 	    SYSCTL_CHILDREN(bbr_hptsi),
1261 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1262 	    &bbr_allow_hdwr_pacing, 1,
1263 	    "Do we allow hardware pacing?");
1264 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1265 	    SYSCTL_CHILDREN(bbr_hptsi),
1266 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1267 	    &bbr_hardware_pacing_limit, 4000,
1268 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1269 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1270 	    SYSCTL_CHILDREN(bbr_hptsi),
1271 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1272 	    &bbr_hdwr_pace_adjust, 2,
1273 	    "Multiplier to calculated tso size?");
1274 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1275 	    SYSCTL_CHILDREN(bbr_hptsi),
1276 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1277 	    &bbr_hdwr_pace_floor, 1,
1278 	    "Do we invoke the hardware pacing floor?");
1279 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1280 	    SYSCTL_CHILDREN(bbr_hptsi),
1281 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1282 	    &bbr_hdwr_pacing_delay_cnt, 10,
1283 	    "How many packets must be sent after hdwr pacing is enabled");
1284 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1285 	    SYSCTL_CHILDREN(bbr_hptsi),
1286 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1287 	    &bbr_cross_over, 3000000,
1288 	    "What is the point where we cross over to linux like TSO size set");
1289 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1290 	    SYSCTL_CHILDREN(bbr_hptsi),
1291 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1292 	    &bbr_hptsi_segments_delay_tar, 7000,
1293 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1294 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1295 	    SYSCTL_CHILDREN(bbr_hptsi),
1296 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1297 	    &bbr_include_enet_oh, 0,
1298 	    "Do we include the ethernet overhead in calculating pacing delay?");
1299 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1300 	    SYSCTL_CHILDREN(bbr_hptsi),
1301 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1302 	    &bbr_include_ip_oh, 1,
1303 	    "Do we include the IP overhead in calculating pacing delay?");
1304 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1305 	    SYSCTL_CHILDREN(bbr_hptsi),
1306 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1307 	    &bbr_include_tcp_oh, 0,
1308 	    "Do we include the TCP overhead in calculating pacing delay?");
1309 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1310 	    SYSCTL_CHILDREN(bbr_hptsi),
1311 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1312 	    &bbr_google_discount, 10,
1313 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1314 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1315 	    SYSCTL_CHILDREN(bbr_hptsi),
1316 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1317 	    &bbr_all_get_min, 0,
1318 	    "If you are less than a MSS do you just get the min?");
1319 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1320 	    SYSCTL_CHILDREN(bbr_hptsi),
1321 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1322 	    &bbr_hptsi_bytes_min, 1460,
1323 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1324 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1325 	    SYSCTL_CHILDREN(bbr_hptsi),
1326 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1327 	    &bbr_hptsi_segments_max, 6,
1328 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1329 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1330 	    SYSCTL_CHILDREN(bbr_hptsi),
1331 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1332 	    &bbr_hptsi_segments_floor, 1,
1333 	    "Minimum TSO size we will fall too in segments");
1334 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1335 	    SYSCTL_CHILDREN(bbr_hptsi),
1336 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1337 	    &bbr_hptsi_utter_max, 0,
1338 	    "The absolute maximum that any pacing (outside of hardware) can be");
1339 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1340 	    SYSCTL_CHILDREN(bbr_hptsi),
1341 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1342 	    &bbr_hptsi_per_second, 100,
1343 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1344 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1345 	    SYSCTL_CHILDREN(bbr_hptsi),
1346 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1347 	    &bbr_hptsi_max_mul, 1,
1348 	    "The multiplier for pace len max");
1349 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1350 	    SYSCTL_CHILDREN(bbr_hptsi),
1351 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1352 	    &bbr_hptsi_max_div, 2,
1353 	    "The divisor for pace len max");
1354 	/* Measurement controls */
1355 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1356 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1357 	    OID_AUTO,
1358 	    "measure",
1359 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1360 	    "Measurement controls");
1361 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1362 	    SYSCTL_CHILDREN(bbr_measure),
1363 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1364 	    &bbr_initial_bw_bps, 62500,
1365 	    "Minimum initial b/w in bytes per second");
1366 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1367 	    SYSCTL_CHILDREN(bbr_measure),
1368 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1369 	    &bbr_sack_not_required, 0,
1370 	    "Do we allow bbr to run on connections not supporting SACK?");
1371 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1372 	    SYSCTL_CHILDREN(bbr_measure),
1373 	    OID_AUTO, "use_google", CTLFLAG_RW,
1374 	    &bbr_use_google_algo, 0,
1375 	    "Use has close to google V1.0 has possible?");
1376 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1377 	    SYSCTL_CHILDREN(bbr_measure),
1378 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1379 	    &bbr_ts_limiting, 1,
1380 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1381 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1382 	    SYSCTL_CHILDREN(bbr_measure),
1383 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1384 	    &bbr_ts_can_raise, 0,
1385 	    "Can we raise the b/w via timestamp b/w calculation?");
1386 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1387 	    SYSCTL_CHILDREN(bbr_measure),
1388 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1389 	    &bbr_min_usec_delta, 20000,
1390 	    "How long in usec between ts of our sends in ts validation code?");
1391 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1392 	    SYSCTL_CHILDREN(bbr_measure),
1393 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1394 	    &bbr_min_peer_delta, 20,
1395 	    "What min numerical value should be between the peer deltas?");
1396 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1397 	    SYSCTL_CHILDREN(bbr_measure),
1398 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1399 	    &bbr_delta_percent, 150,
1400 	    "What percentage (150 = 15.0) do we allow variance for?");
1401 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1402 	    SYSCTL_CHILDREN(bbr_measure),
1403 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1404 	    &bbr_min_measurements_req, 1,
1405 	    "What is the minimum measurment count we need before we switch to our b/w estimate");
1406 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1407 	    SYSCTL_CHILDREN(bbr_measure),
1408 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1409 	    &bbr_no_pacing_until, 4,
1410 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1411 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1412 	    SYSCTL_CHILDREN(bbr_measure),
1413 	    OID_AUTO, "quanta", CTLFLAG_RW,
1414 	    &bbr_quanta, 2,
1415 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1416 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1417 	    SYSCTL_CHILDREN(bbr_measure),
1418 	    OID_AUTO, "noretran", CTLFLAG_RW,
1419 	    &bbr_no_retran, 0,
1420 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1421 	/* State controls */
1422 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1423 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1424 	    OID_AUTO,
1425 	    "states",
1426 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1427 	    "State controls");
1428 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1429 	    SYSCTL_CHILDREN(bbr_states),
1430 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1431 	    &bbr_uses_idle_restart, 0,
1432 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1433 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1434 	    SYSCTL_CHILDREN(bbr_states),
1435 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1436 	    &bbr_idle_restart_threshold, 100000,
1437 	    "How long must we be idle before we restart??");
1438 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1439 	    SYSCTL_CHILDREN(bbr_states),
1440 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1441 	    &bbr_state_is_pkt_epoch, 0,
1442 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1443 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1444 	    SYSCTL_CHILDREN(bbr_states),
1445 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1446 	    &bbr_rtt_gain_thresh, 0,
1447 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1448 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1449 	    SYSCTL_CHILDREN(bbr_states),
1450 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1451 	    &bbr_drain_floor, 88,
1452 	    "What is the lowest we can drain (pg) too?");
1453 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1454 	    SYSCTL_CHILDREN(bbr_states),
1455 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1456 	    &bbr_state_drain_2_tar, 1,
1457 	    "Do we drain to target in drain substate?");
1458 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1459 	    SYSCTL_CHILDREN(bbr_states),
1460 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1461 	    &bbr_gain_to_target, 1,
1462 	    "Does probe bw gain to target??");
1463 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1464 	    SYSCTL_CHILDREN(bbr_states),
1465 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1466 	    &bbr_gain_gets_extra_too, 1,
1467 	    "Does probe bw gain get the extra time too?");
1468 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1469 	    SYSCTL_CHILDREN(bbr_states),
1470 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1471 	    &bbr_drain_drop_div, 5,
1472 	    "Long drain drop divider?");
1473 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1474 	    SYSCTL_CHILDREN(bbr_states),
1475 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1476 	    &bbr_drain_drop_mul, 4,
1477 	    "Long drain drop multiplier?");
1478 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1479 	    SYSCTL_CHILDREN(bbr_states),
1480 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1481 	    &bbr_rand_ot, 50,
1482 	    "Random discount of the ot?");
1483 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1484 	    SYSCTL_CHILDREN(bbr_states),
1485 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1486 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1487 	    "How many packet-epochs does the b/w delivery rate last?");
1488 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1489 	    SYSCTL_CHILDREN(bbr_states),
1490 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1491 	    &bbr_sub_drain_app_limit, 0,
1492 	    "Does our sub-state drain invoke app limited if its long?");
1493 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1494 	    SYSCTL_CHILDREN(bbr_states),
1495 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1496 	    &bbr_sub_drain_slam_cwnd, 0,
1497 	    "Should we set/recover cwnd for sub-state drain?");
1498 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1499 	    SYSCTL_CHILDREN(bbr_states),
1500 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1501 	    &bbr_slam_cwnd_in_main_drain, 0,
1502 	    "Should we set/recover cwnd for main-state drain?");
1503 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1504 	    SYSCTL_CHILDREN(bbr_states),
1505 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1506 	    &google_allow_early_out, 1,
1507 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1508 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1509 	    SYSCTL_CHILDREN(bbr_states),
1510 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1511 	    &google_consider_lost, 1,
1512 	    "Should we have losses exit gain of probebw in google mode??");
1513 	/* Startup controls */
1514 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1515 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1516 	    OID_AUTO,
1517 	    "startup",
1518 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1519 	    "Startup controls");
1520 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1521 	    SYSCTL_CHILDREN(bbr_startup),
1522 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1523 	    &bbr_sends_full_iwnd, 1,
1524 	    "Do we not pace but burst out initial windows has our TSO size?");
1525 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1526 	    SYSCTL_CHILDREN(bbr_startup),
1527 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1528 	    &bbr_startup_loss_thresh, 2000,
1529 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1530 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1531 	    SYSCTL_CHILDREN(bbr_startup),
1532 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1533 	    &bbr_use_lower_gain_in_startup, 1,
1534 	    "Should we use a lower hptsi gain if we see loss in startup?");
1535 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1536 	    SYSCTL_CHILDREN(bbr_startup),
1537 	    OID_AUTO, "gain", CTLFLAG_RW,
1538 	    &bbr_start_exit, 25,
1539 	    "What gain percent do we need to see to stay in startup??");
1540 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1541 	    SYSCTL_CHILDREN(bbr_startup),
1542 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1543 	    &bbr_low_start_exit, 15,
1544 	    "What gain percent do we need to see to stay in the lower gain startup??");
1545 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1546 	    SYSCTL_CHILDREN(bbr_startup),
1547 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1548 	    &bbr_exit_startup_at_loss, 1,
1549 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1550 	/* CWND controls */
1551 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1552 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1553 	    OID_AUTO,
1554 	    "cwnd",
1555 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1556 	    "Cwnd controls");
1557 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1558 	    SYSCTL_CHILDREN(bbr_cwnd),
1559 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1560 	    &bbr_cwndtarget_rtt_touse, 0,
1561 	    "Target cwnd rtt measurment to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1562 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1563 	    SYSCTL_CHILDREN(bbr_cwnd),
1564 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1565 	    &bbr_cwnd_may_shrink, 0,
1566 	    "Can the cwnd shrink if it would grow to more than the target?");
1567 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1568 	    SYSCTL_CHILDREN(bbr_cwnd),
1569 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1570 	    &bbr_target_cwnd_mult_limit, 8,
1571 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1572 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1573 	    SYSCTL_CHILDREN(bbr_cwnd),
1574 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1575 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1576 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1577 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1578 	    SYSCTL_CHILDREN(bbr_cwnd),
1579 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1580 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1581 	    "What is the min cwnd (rttProp > 1ms)");
1582 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1583 	    SYSCTL_CHILDREN(bbr_cwnd),
1584 	    OID_AUTO, "initwin", CTLFLAG_RW,
1585 	    &bbr_def_init_win, 10,
1586 	    "What is the BBR initial window, if 0 use tcp version");
1587 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1588 	    SYSCTL_CHILDREN(bbr_cwnd),
1589 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1590 	    &bbr_do_red, 600,
1591 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1592 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1593 	    SYSCTL_CHILDREN(bbr_cwnd),
1594 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1595 	    &bbr_red_scale, 20000,
1596 	    "What RTT do we scale with?");
1597 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1598 	    SYSCTL_CHILDREN(bbr_cwnd),
1599 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1600 	    &bbr_red_growth_restrict, 1,
1601 	    "Do we restrict cwnd growth for whats in flight?");
1602 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1603 	    SYSCTL_CHILDREN(bbr_cwnd),
1604 	    OID_AUTO, "red_div", CTLFLAG_RW,
1605 	    &bbr_red_div, 2,
1606 	    "If we reduce whats the divisor?");
1607 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1608 	    SYSCTL_CHILDREN(bbr_cwnd),
1609 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1610 	    &bbr_red_mul, 1,
1611 	    "If we reduce whats the mulitiplier?");
1612 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1613 	    SYSCTL_CHILDREN(bbr_cwnd),
1614 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1615 	    &bbr_target_is_bbunit, 0,
1616 	    "Is the state target the pacing_gain or BBR_UNIT?");
1617 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1618 	    SYSCTL_CHILDREN(bbr_cwnd),
1619 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1620 	    &bbr_drop_limit, 0,
1621 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1622 
1623 	/* Timeout controls */
1624 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1625 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1626 	    OID_AUTO,
1627 	    "timeout",
1628 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1629 	    "Time out controls");
1630 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1631 	    SYSCTL_CHILDREN(bbr_timeout),
1632 	    OID_AUTO, "delack", CTLFLAG_RW,
1633 	    &bbr_delack_time, 100000,
1634 	    "BBR's delayed ack time");
1635 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1636 	    SYSCTL_CHILDREN(bbr_timeout),
1637 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1638 	    &bbr_tlp_type_to_use, 3,
1639 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1640 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1641 	    SYSCTL_CHILDREN(bbr_timeout),
1642 	    OID_AUTO, "persmin", CTLFLAG_RW,
1643 	    &bbr_persist_min, 250000,
1644 	    "What is the minimum time in microseconds between persists");
1645 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1646 	    SYSCTL_CHILDREN(bbr_timeout),
1647 	    OID_AUTO, "persmax", CTLFLAG_RW,
1648 	    &bbr_persist_max, 1000000,
1649 	    "What is the largest delay in microseconds between persists");
1650 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1651 	    SYSCTL_CHILDREN(bbr_timeout),
1652 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1653 	    &bbr_tlp_min, 10000,
1654 	    "TLP Min timeout in usecs");
1655 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1656 	    SYSCTL_CHILDREN(bbr_timeout),
1657 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1658 	    &bbr_delayed_ack_time, 200000,
1659 	    "TLP delayed ack compensation value");
1660 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1661 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1662 	    OID_AUTO, "minrto", CTLFLAG_RW,
1663 	    &bbr_rto_min_ms, 30,
1664 	    "Minimum RTO in ms");
1665 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1666 	    SYSCTL_CHILDREN(bbr_timeout),
1667 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1668 	    &bbr_rto_max_sec, 4,
1669 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1670 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1671 	    SYSCTL_CHILDREN(bbr_timeout),
1672 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1673 	    &bbr_tlp_max_resend, 2,
1674 	    "How many times does TLP retry a single segment or multiple with no ACK");
1675 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1676 	    SYSCTL_CHILDREN(bbr_timeout),
1677 	    OID_AUTO, "minto", CTLFLAG_RW,
1678 	    &bbr_min_to, 1000,
1679 	    "Minimum rack timeout in useconds");
1680 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1681 	    SYSCTL_CHILDREN(bbr_timeout),
1682 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1683 	    &bbr_pkt_delay, 1000,
1684 	    "Extra RACK time (in useconds) besides reordering thresh");
1685 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1686 	    SYSCTL_CHILDREN(bbr_timeout),
1687 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1688 	    &bbr_incr_timers, 1,
1689 	    "Increase the RXT/TLP timer by the pacing time used?");
1690 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1691 	    SYSCTL_CHILDREN(bbr_timeout),
1692 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1693 	    &bbr_marks_rxt_sack_passed, 0,
1694 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1695 	/* Policer controls */
1696 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1697 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1698 	    OID_AUTO,
1699 	    "policer",
1700 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1701 	    "Policer controls");
1702 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1703 	    SYSCTL_CHILDREN(bbr_policer),
1704 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1705 	    &bbr_policer_detection_enabled, 1,
1706 	    "Is policer detection enabled??");
1707 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1708 	    SYSCTL_CHILDREN(bbr_policer),
1709 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1710 	    &bbr_lt_intvl_min_rtts, 4,
1711 	    "Minimum number of PE's?");
1712 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1713 	    SYSCTL_CHILDREN(bbr_policer),
1714 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1715 	    &bbr_lt_bw_diff, (4000/8),
1716 	    "Minimal bw diff?");
1717 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1718 	    SYSCTL_CHILDREN(bbr_policer),
1719 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1720 	    &bbr_lt_bw_ratio, 8,
1721 	    "Minimal bw diff?");
1722 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1723 	    SYSCTL_CHILDREN(bbr_policer),
1724 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1725 	    &bbr_policer_call_from_rack_to, 0,
1726 	    "Do we call the policer detection code from a rack-timeout?");
1727 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1728 	    SYSCTL_CHILDREN(bbr_policer),
1729 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1730 	    &bbr_lt_intvl_fp, 0,
1731 	    "What packet epoch do we do false-postive detection at (0=no)?");
1732 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1733 	    SYSCTL_CHILDREN(bbr_policer),
1734 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1735 	    &bbr_lt_loss_thresh, 196,
1736 	    "Loss threshold 196 = 19.6%?");
1737 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1738 	    SYSCTL_CHILDREN(bbr_policer),
1739 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1740 	    &bbr_lt_fd_thresh, 100,
1741 	    "What percentage is the false detection threshold (150=15.0)?");
1742 	/* All the rest */
1743 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1744 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1745 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1746 	    &bbr_use_rack_resend_cheat, 0,
1747 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1748 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1749 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1750 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1751 	    &bbr_error_base_paceout, 10000,
1752 	    "When we hit an error what is the min to pace out in usec's?");
1753 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1754 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1755 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1756 	    &bbr_max_net_error_cnt, 10,
1757 	    "When we hit this many errors in a row, kill the session?");
1758 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1759 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1760 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1761 	    &bbr_ignore_data_after_close, 1,
1762 	    "Do we hold off sending a RST until all pending data is ack'd");
1763 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1764 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1765 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1766 	    &bbr_resends_use_tso, 0,
1767 	    "Can resends use TSO?");
1768 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1769 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1770 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1771 	    &bbr_sack_block_limit, 128,
1772 	    "When do we start ignoring small sack blocks");
1773 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1774 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1775 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1776 	    &bbr_verbose_logging, 0,
1777 	    "Should BBR black box logging be verbose");
1778 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1779 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1780 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1781 	    &bbr_reorder_thresh, 2,
1782 	    "What factor for rack will be added when seeing reordering (shift right)");
1783 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1784 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1785 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1786 	    &bbr_reorder_fade, 0,
1787 	    "Does reorder detection fade, if so how many ms (0 means never)");
1788 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1789 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1790 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1791 	    &bbr_tlp_thresh, 1,
1792 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1793 	/* Stats and counters */
1794 	/* The pacing counters for hdwr/software can't be in the array */
1795 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1796 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1797 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1798 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1799 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1800 	    &bbr_hdwr_pacing_enobuf,
1801 	    "Total number of enobufs for hardware paced flows");
1802 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1803 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1804 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1805 	    &bbr_nohdwr_pacing_enobuf,
1806 	    "Total number of enobufs for non-hardware paced flows");
1807 
1808 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1809 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1810 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1811 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1812 	    &bbr_flows_whdwr_pacing,
1813 	    "Total number of hardware paced flows");
1814 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1815 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1816 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1817 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1818 	    &bbr_flows_nohdwr_pacing,
1819 	    "Total number of software paced flows");
1820 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1821 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1822 	    OID_AUTO, "stats", CTLFLAG_RD,
1823 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1824 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1825 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1826 	    OID_AUTO, "opts", CTLFLAG_RD,
1827 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1828 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1829 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1830 	    OID_AUTO, "lost", CTLFLAG_RD,
1831 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1832 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1833 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1834 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1835 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1836 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1837 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1838 	    OID_AUTO, "statetime", CTLFLAG_RD,
1839 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1840 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1841 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1842 	    OID_AUTO, "outsize", CTLFLAG_RD,
1843 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1844 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1845 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1846 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1847 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1848 }
1849 
1850 static void
1851 bbr_counter_destroy(void)
1852 {
1853 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1854 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1855 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1856 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1857 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1858 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1859 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1860 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1861 	counter_u64_free(bbr_flows_whdwr_pacing);
1862 	counter_u64_free(bbr_flows_nohdwr_pacing);
1863 
1864 }
1865 
1866 static __inline void
1867 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1868 {
1869 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1870 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1871 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1872 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1873 	l->bw_inuse = bbr_get_bw(bbr);
1874 	l->inflight = ctf_flight_size(bbr->rc_tp,
1875 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1876 	l->applimited = bbr->r_ctl.r_app_limited_until;
1877 	l->delivered = bbr->r_ctl.rc_delivered;
1878 	l->timeStamp = cts;
1879 	l->lost = bbr->r_ctl.rc_lost;
1880 	l->bbr_state = bbr->rc_bbr_state;
1881 	l->bbr_substate = bbr_state_val(bbr);
1882 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1883 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1884 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1885 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1886 	l->inhpts = bbr->rc_inp->inp_in_hpts;
1887 	l->ininput = bbr->rc_inp->inp_in_input;
1888 	l->use_lt_bw = bbr->rc_lt_use_bw;
1889 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1890 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1891 }
1892 
1893 static void
1894 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1895 {
1896 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1897 		union tcp_log_stackspecific log;
1898 
1899 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1900 		log.u_bbr.flex1 = 0;
1901 		log.u_bbr.flex2 = 0;
1902 		log.u_bbr.flex5 = 0;
1903 		log.u_bbr.flex3 = 0;
1904 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1905 		log.u_bbr.flex7 = reason;
1906 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1907 		log.u_bbr.flex8 = 0;
1908 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1909 		    &bbr->rc_inp->inp_socket->so_rcv,
1910 		    &bbr->rc_inp->inp_socket->so_snd,
1911 		    BBR_LOG_BW_RED_EV, 0,
1912 		    0, &log, false, &bbr->rc_tv);
1913 	}
1914 }
1915 
1916 static void
1917 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1918 {
1919 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1920 		union tcp_log_stackspecific log;
1921 
1922 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1923 		log.u_bbr.flex1 = seq;
1924 		log.u_bbr.flex2 = count;
1925 		log.u_bbr.flex8 = mode;
1926 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1927 		    &bbr->rc_inp->inp_socket->so_rcv,
1928 		    &bbr->rc_inp->inp_socket->so_snd,
1929 		    BBR_LOG_LOWGAIN, 0,
1930 		    0, &log, false, &bbr->rc_tv);
1931 	}
1932 }
1933 
1934 static void
1935 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1936     uint8_t reason, uint32_t p_maxseg, int len)
1937 {
1938 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1939 		union tcp_log_stackspecific log;
1940 
1941 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1942 		log.u_bbr.flex1 = p_maxseg;
1943 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1944 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1945 		log.u_bbr.flex4 = reason;
1946 		log.u_bbr.flex5 = bbr->rc_in_persist;
1947 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1948 		log.u_bbr.flex7 = p_maxseg;
1949 		log.u_bbr.flex8 = bbr->rc_in_persist;
1950 		log.u_bbr.pkts_out = 0;
1951 		log.u_bbr.applimited = len;
1952 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1953 		    &bbr->rc_inp->inp_socket->so_rcv,
1954 		    &bbr->rc_inp->inp_socket->so_snd,
1955 		    BBR_LOG_JUSTRET, 0,
1956 		    tlen, &log, false, &bbr->rc_tv);
1957 	}
1958 }
1959 
1960 static void
1961 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1962 {
1963 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1964 		union tcp_log_stackspecific log;
1965 
1966 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1967 		log.u_bbr.flex1 = seq;
1968 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1969 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1970 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1971 		    &bbr->rc_inp->inp_socket->so_rcv,
1972 		    &bbr->rc_inp->inp_socket->so_snd,
1973 		    BBR_LOG_ENTREC, 0,
1974 		    0, &log, false, &bbr->rc_tv);
1975 	}
1976 }
1977 
1978 static void
1979 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)
1980 {
1981 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
1982 		union tcp_log_stackspecific log;
1983 
1984 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1985 		log.u_bbr.flex1 = tso;
1986 		log.u_bbr.flex2 = maxseg;
1987 		log.u_bbr.flex3 = mtu;
1988 		log.u_bbr.flex4 = csum_flags;
1989 		TCP_LOG_EVENTP(tp, NULL,
1990 		    &bbr->rc_inp->inp_socket->so_rcv,
1991 		    &bbr->rc_inp->inp_socket->so_snd,
1992 		    BBR_LOG_MSGSIZE, 0,
1993 		    0, &log, false, &bbr->rc_tv);
1994 	}
1995 }
1996 
1997 static void
1998 bbr_log_flowend(struct tcp_bbr *bbr)
1999 {
2000 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2001 		union tcp_log_stackspecific log;
2002 		struct sockbuf *r, *s;
2003 		struct timeval tv;
2004 
2005 		if (bbr->rc_inp->inp_socket) {
2006 			r = &bbr->rc_inp->inp_socket->so_rcv;
2007 			s = &bbr->rc_inp->inp_socket->so_snd;
2008 		} else {
2009 			r = s = NULL;
2010 		}
2011 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2012 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2013 		    r, s,
2014 		    TCP_LOG_FLOWEND, 0,
2015 		    0, &log, false, &tv);
2016 	}
2017 }
2018 
2019 static void
2020 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2021     uint32_t lost, uint32_t del)
2022 {
2023 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2024 		union tcp_log_stackspecific log;
2025 
2026 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2027 		log.u_bbr.flex1 = lost;
2028 		log.u_bbr.flex2 = del;
2029 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2030 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2031 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2032 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2033 		log.u_bbr.flex7 = line;
2034 		log.u_bbr.flex8 = 0;
2035 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2036 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2037 		    &bbr->rc_inp->inp_socket->so_rcv,
2038 		    &bbr->rc_inp->inp_socket->so_snd,
2039 		    BBR_LOG_PKT_EPOCH, 0,
2040 		    0, &log, false, &bbr->rc_tv);
2041 	}
2042 }
2043 
2044 static void
2045 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2046 {
2047 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2048 		union tcp_log_stackspecific log;
2049 
2050 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2051 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2052 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2053 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2054 		log.u_bbr.flex7 = line;
2055 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2056 		    &bbr->rc_inp->inp_socket->so_rcv,
2057 		    &bbr->rc_inp->inp_socket->so_snd,
2058 		    BBR_LOG_TIME_EPOCH, 0,
2059 		    0, &log, false, &bbr->rc_tv);
2060 	}
2061 }
2062 
2063 static void
2064 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2065 {
2066 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2067 		union tcp_log_stackspecific log;
2068 
2069 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2070 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2071 		log.u_bbr.flex2 = new_tar;
2072 		log.u_bbr.flex3 = line;
2073 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2074 		log.u_bbr.flex5 = bbr_quanta;
2075 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2076 		log.u_bbr.flex7 = bbr->rc_last_options;
2077 		log.u_bbr.flex8 = meth;
2078 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2079 		    &bbr->rc_inp->inp_socket->so_rcv,
2080 		    &bbr->rc_inp->inp_socket->so_snd,
2081 		    BBR_LOG_STATE_TARGET, 0,
2082 		    0, &log, false, &bbr->rc_tv);
2083 	}
2084 
2085 }
2086 
2087 static void
2088 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2089 {
2090 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2091 		union tcp_log_stackspecific log;
2092 
2093 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2094 		log.u_bbr.flex1 = line;
2095 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2096 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2097 		if (bbr_state_is_pkt_epoch)
2098 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2099 		else
2100 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2101 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2102 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2103 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2104 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2105 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2106 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2107 		    &bbr->rc_inp->inp_socket->so_rcv,
2108 		    &bbr->rc_inp->inp_socket->so_snd,
2109 		    BBR_LOG_STATE, 0,
2110 		    0, &log, false, &bbr->rc_tv);
2111 	}
2112 }
2113 
2114 static void
2115 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2116 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2117 {
2118 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2119 		union tcp_log_stackspecific log;
2120 
2121 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2122 		log.u_bbr.flex1 = line;
2123 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2124 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2125 		log.u_bbr.flex4 = applied;
2126 		log.u_bbr.flex5 = rtt;
2127 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2128 		log.u_bbr.flex7 = cond;
2129 		log.u_bbr.flex8 = reas;
2130 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2131 		    &bbr->rc_inp->inp_socket->so_rcv,
2132 		    &bbr->rc_inp->inp_socket->so_snd,
2133 		    BBR_LOG_RTT_SHRINKS, 0,
2134 		    0, &log, false, &bbr->rc_tv);
2135 	}
2136 }
2137 
2138 static void
2139 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2140 {
2141 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2142 		union tcp_log_stackspecific log;
2143 
2144 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2145 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2146 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2147 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2148 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2149 		    &bbr->rc_inp->inp_socket->so_rcv,
2150 		    &bbr->rc_inp->inp_socket->so_snd,
2151 		    BBR_LOG_EXITREC, 0,
2152 		    0, &log, false, &bbr->rc_tv);
2153 	}
2154 }
2155 
2156 static void
2157 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2158     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2159 {
2160 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2161 		union tcp_log_stackspecific log;
2162 
2163 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2164 		log.u_bbr.flex1 = line;
2165 		log.u_bbr.flex2 = prev_acked;
2166 		log.u_bbr.flex3 = bytes_this_ack;
2167 		log.u_bbr.flex4 = chg;
2168 		log.u_bbr.flex5 = th_ack;
2169 		log.u_bbr.flex6 = target;
2170 		log.u_bbr.flex8 = meth;
2171 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2172 		    &bbr->rc_inp->inp_socket->so_rcv,
2173 		    &bbr->rc_inp->inp_socket->so_snd,
2174 		    BBR_LOG_CWND, 0,
2175 		    0, &log, false, &bbr->rc_tv);
2176 	}
2177 }
2178 
2179 static void
2180 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2181 {
2182 	/*
2183 	 * Log the rtt sample we are applying to the srtt algorithm in
2184 	 * useconds.
2185 	 */
2186 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2187 		union tcp_log_stackspecific log;
2188 
2189 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2190 		log.u_bbr.flex1 = rtt;
2191 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2192 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2193 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2194 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2195 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2196 		log.u_bbr.flex6 = tsin;
2197 		log.u_bbr.flex7 = 0;
2198 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2199 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2200 		    &bbr->rc_inp->inp_socket->so_rcv,
2201 		    &bbr->rc_inp->inp_socket->so_snd,
2202 		    TCP_LOG_RTT, 0,
2203 		    0, &log, false, &bbr->rc_tv);
2204 	}
2205 }
2206 
2207 static void
2208 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2209 {
2210 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2211 		union tcp_log_stackspecific log;
2212 
2213 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2214 		log.u_bbr.flex1 = time_in;
2215 		log.u_bbr.flex2 = line;
2216 		log.u_bbr.flex8 = enter_exit;
2217 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2218 		    &bbr->rc_inp->inp_socket->so_rcv,
2219 		    &bbr->rc_inp->inp_socket->so_snd,
2220 		    BBR_LOG_PERSIST, 0,
2221 		    0, &log, false, &bbr->rc_tv);
2222 	}
2223 }
2224 static void
2225 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2226 {
2227 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2228 		union tcp_log_stackspecific log;
2229 
2230 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2231 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2232 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2233 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2234 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2235 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2236 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2237 		    &bbr->rc_inp->inp_socket->so_rcv,
2238 		    &bbr->rc_inp->inp_socket->so_snd,
2239 		    BBR_LOG_ACKCLEAR, 0,
2240 		    0, &log, false, &bbr->rc_tv);
2241 	}
2242 }
2243 
2244 static void
2245 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2246 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2247 {
2248 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2249 		union tcp_log_stackspecific log;
2250 		struct timeval tv;
2251 
2252 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2253 		log.u_bbr.flex1 = nsegs;
2254 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2255 		if (m) {
2256 			struct timespec ts;
2257 
2258 			log.u_bbr.flex3 = m->m_flags;
2259 			if (m->m_flags & M_TSTMP) {
2260 				mbuf_tstmp2timespec(m, &ts);
2261 				tv.tv_sec = ts.tv_sec;
2262 				tv.tv_usec = ts.tv_nsec / 1000;
2263 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2264 			} else {
2265 				log.u_bbr.lt_epoch = 0;
2266 			}
2267 			if (m->m_flags & M_TSTMP_LRO) {
2268 				tv.tv_sec = m->m_pkthdr.rcv_tstmp / 1000000000;
2269 				tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000) / 1000;
2270 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2271 			} else {
2272 				/* No arrival timestamp */
2273 				log.u_bbr.flex5 = 0;
2274 			}
2275 
2276 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2277 		} else {
2278 			log.u_bbr.flex3 = 0;
2279 			log.u_bbr.flex5 = 0;
2280 			log.u_bbr.flex6 = 0;
2281 			log.u_bbr.pkts_out = 0;
2282 		}
2283 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2284 		log.u_bbr.flex7 = bbr->r_wanted_output;
2285 		log.u_bbr.flex8 = bbr->rc_in_persist;
2286 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2287 		    &bbr->rc_inp->inp_socket->so_rcv,
2288 		    &bbr->rc_inp->inp_socket->so_snd,
2289 		    TCP_LOG_IN, 0,
2290 		    tlen, &log, true, &bbr->rc_tv);
2291 	}
2292 }
2293 
2294 static void
2295 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2296 {
2297 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2298 		union tcp_log_stackspecific log;
2299 
2300 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2301 		log.u_bbr.flex1 = did_out;
2302 		log.u_bbr.flex2 = nxt_pkt;
2303 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2304 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2305 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2306 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2307 		log.u_bbr.flex7 = bbr->r_wanted_output;
2308 		log.u_bbr.flex8 = bbr->rc_in_persist;
2309 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2310 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2311 		    &bbr->rc_inp->inp_socket->so_rcv,
2312 		    &bbr->rc_inp->inp_socket->so_snd,
2313 		    BBR_LOG_DOSEG_DONE, 0,
2314 		    0, &log, true, &bbr->rc_tv);
2315 	}
2316 }
2317 
2318 static void
2319 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2320     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2321 {
2322 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2323 		union tcp_log_stackspecific log;
2324 
2325 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2326 		log.u_bbr.flex1 = line;
2327 		log.u_bbr.flex2 = o_len;
2328 		log.u_bbr.flex3 = segcnt;
2329 		log.u_bbr.flex4 = segsiz;
2330 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2331 		    &bbr->rc_inp->inp_socket->so_rcv,
2332 		    &bbr->rc_inp->inp_socket->so_snd,
2333 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2334 		    len, &log, true, &bbr->rc_tv);
2335 	}
2336 }
2337 
2338 static void
2339 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2340 {
2341 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2342 		union tcp_log_stackspecific log;
2343 
2344 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2345 		log.u_bbr.flex1 = timers;
2346 		log.u_bbr.flex2 = ret;
2347 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2348 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2349 		log.u_bbr.flex5 = cts;
2350 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2351 		log.u_bbr.flex8 = hpts_calling;
2352 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2353 		    &bbr->rc_inp->inp_socket->so_rcv,
2354 		    &bbr->rc_inp->inp_socket->so_snd,
2355 		    BBR_LOG_TO_PROCESS, 0,
2356 		    0, &log, false, &bbr->rc_tv);
2357 	}
2358 }
2359 
2360 static void
2361 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2362 {
2363 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2364 		union tcp_log_stackspecific log;
2365 		uint64_t ar;
2366 
2367 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2368 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2369 		log.u_bbr.flex2 = 0;
2370 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2371 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2372 		ar >>= 32;
2373 		ar &= 0x00000000ffffffff;
2374 		log.u_bbr.flex4 = (uint32_t)ar;
2375 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2376 		ar &= 0x00000000ffffffff;
2377 		log.u_bbr.flex5 = (uint32_t)ar;
2378 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2379 		log.u_bbr.flex8 = to_num;
2380 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2381 		    &bbr->rc_inp->inp_socket->so_rcv,
2382 		    &bbr->rc_inp->inp_socket->so_snd,
2383 		    BBR_LOG_RTO, 0,
2384 		    0, &log, false, &bbr->rc_tv);
2385 	}
2386 }
2387 
2388 static void
2389 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2390 {
2391 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2392 		union tcp_log_stackspecific log;
2393 
2394 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2395 		log.u_bbr.flex1 = flex1;
2396 		log.u_bbr.flex2 = flex2;
2397 		log.u_bbr.flex3 = flex3;
2398 		log.u_bbr.flex4 = 0;
2399 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2400 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2401 		log.u_bbr.flex8 = reason;
2402 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2403 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2404 		    &bbr->rc_inp->inp_socket->so_rcv,
2405 		    &bbr->rc_inp->inp_socket->so_snd,
2406 		    BBR_LOG_REDUCE, 0,
2407 		    0, &log, false, &bbr->rc_tv);
2408 	}
2409 }
2410 
2411 static void
2412 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2413 {
2414 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2415 		union tcp_log_stackspecific log;
2416 
2417 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2418 		log.u_bbr.flex1 = diag->p_nxt_slot;
2419 		log.u_bbr.flex2 = diag->p_cur_slot;
2420 		log.u_bbr.flex3 = diag->slot_req;
2421 		log.u_bbr.flex4 = diag->inp_hptsslot;
2422 		log.u_bbr.flex5 = diag->slot_remaining;
2423 		log.u_bbr.flex6 = diag->need_new_to;
2424 		log.u_bbr.flex7 = diag->p_hpts_active;
2425 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2426 		/* Hijack other fields as needed  */
2427 		log.u_bbr.epoch = diag->have_slept;
2428 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2429 		log.u_bbr.pkts_out = diag->co_ret;
2430 		log.u_bbr.applimited = diag->hpts_sleep_time;
2431 		log.u_bbr.delivered = diag->p_prev_slot;
2432 		log.u_bbr.inflight = diag->p_runningslot;
2433 		log.u_bbr.bw_inuse = diag->wheel_slot;
2434 		log.u_bbr.rttProp = diag->wheel_cts;
2435 		log.u_bbr.delRate = diag->maxslots;
2436 		log.u_bbr.cur_del_rate = diag->p_curtick;
2437 		log.u_bbr.cur_del_rate <<= 32;
2438 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2439 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2440 		    &bbr->rc_inp->inp_socket->so_rcv,
2441 		    &bbr->rc_inp->inp_socket->so_snd,
2442 		    BBR_LOG_HPTSDIAG, 0,
2443 		    0, &log, false, &bbr->rc_tv);
2444 	}
2445 }
2446 
2447 static void
2448 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2449     uint32_t thresh, uint32_t to)
2450 {
2451 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2452 		union tcp_log_stackspecific log;
2453 
2454 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2455 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2456 		log.u_bbr.flex2 = time_since_sent;
2457 		log.u_bbr.flex3 = srtt;
2458 		log.u_bbr.flex4 = thresh;
2459 		log.u_bbr.flex5 = to;
2460 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2461 		log.u_bbr.flex8 = mode;
2462 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2463 		    &bbr->rc_inp->inp_socket->so_rcv,
2464 		    &bbr->rc_inp->inp_socket->so_snd,
2465 		    BBR_LOG_TIMERPREP, 0,
2466 		    0, &log, false, &bbr->rc_tv);
2467 	}
2468 }
2469 
2470 static void
2471 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2472     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2473 {
2474 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2475 		union tcp_log_stackspecific log;
2476 
2477 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2478 		log.u_bbr.flex1 = usecs;
2479 		log.u_bbr.flex2 = len;
2480 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2481 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2482 		if (override)
2483 			log.u_bbr.flex5 = (1 << 2);
2484 		else
2485 			log.u_bbr.flex5 = 0;
2486 		log.u_bbr.flex6 = override;
2487 		log.u_bbr.flex7 = gain;
2488 		log.u_bbr.flex8 = mod;
2489 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2490 		    &bbr->rc_inp->inp_socket->so_rcv,
2491 		    &bbr->rc_inp->inp_socket->so_snd,
2492 		    BBR_LOG_HPTSI_CALC, 0,
2493 		    len, &log, false, &bbr->rc_tv);
2494 	}
2495 }
2496 
2497 static void
2498 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2499 {
2500 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2501 		union tcp_log_stackspecific log;
2502 
2503 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2504 
2505 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2506 		log.u_bbr.flex2 = to;
2507 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2508 		log.u_bbr.flex4 = slot;
2509 		log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2510 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2511 		log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2512 		log.u_bbr.flex8 = which;
2513 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2514 		    &bbr->rc_inp->inp_socket->so_rcv,
2515 		    &bbr->rc_inp->inp_socket->so_snd,
2516 		    BBR_LOG_TIMERSTAR, 0,
2517 		    0, &log, false, &bbr->rc_tv);
2518 	}
2519 }
2520 
2521 static void
2522 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)
2523 {
2524 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2525 		union tcp_log_stackspecific log;
2526 
2527 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2528 		log.u_bbr.flex1 = thresh;
2529 		log.u_bbr.flex2 = lro;
2530 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2531 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2532 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2533 		log.u_bbr.flex6 = srtt;
2534 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2535 		log.u_bbr.flex8 = frm;
2536 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2537 		    &bbr->rc_inp->inp_socket->so_rcv,
2538 		    &bbr->rc_inp->inp_socket->so_snd,
2539 		    BBR_LOG_THRESH_CALC, 0,
2540 		    0, &log, false, &bbr->rc_tv);
2541 	}
2542 }
2543 
2544 static void
2545 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2546 {
2547 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2548 		union tcp_log_stackspecific log;
2549 
2550 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2551 		log.u_bbr.flex1 = line;
2552 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2553 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2554 		log.u_bbr.flex4 = bbr->rc_in_persist;
2555 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2556 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2557 		log.u_bbr.flex8 = hpts_removed;
2558 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2559 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2560 		    &bbr->rc_inp->inp_socket->so_rcv,
2561 		    &bbr->rc_inp->inp_socket->so_snd,
2562 		    BBR_LOG_TIMERCANC, 0,
2563 		    0, &log, false, &bbr->rc_tv);
2564 	}
2565 }
2566 
2567 static void
2568 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2569 {
2570 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2571 		union tcp_log_stackspecific log;
2572 
2573 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2574 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2575 		log.u_bbr.flex2 = (peer_delta >> 32);
2576 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2577 		log.u_bbr.flex4 = (delta >> 32);
2578 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2579 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2580 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2581 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2582 		    &bbr->rc_inp->inp_socket->so_rcv,
2583 		    &bbr->rc_inp->inp_socket->so_snd,
2584 		    BBR_LOG_TSTMP_VAL, 0,
2585 		    0, &log, false, &bbr->rc_tv);
2586 	}
2587 }
2588 
2589 static void
2590 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)
2591 {
2592 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2593 		union tcp_log_stackspecific log;
2594 
2595 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2596 		log.u_bbr.flex1 = tsosz;
2597 		log.u_bbr.flex2 = tls;
2598 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2599 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2600 		log.u_bbr.flex5 = old_val;
2601 		log.u_bbr.flex6 = maxseg;
2602 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2603 		log.u_bbr.flex7 <<= 1;
2604 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2605 		if (hdwr)
2606 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2607 		else
2608 			log.u_bbr.flex8 = bbr->rc_use_google;
2609 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2610 		    &bbr->rc_inp->inp_socket->so_rcv,
2611 		    &bbr->rc_inp->inp_socket->so_snd,
2612 		    BBR_LOG_BBRTSO, 0,
2613 		    0, &log, false, &bbr->rc_tv);
2614 	}
2615 }
2616 
2617 static void
2618 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2619 		      uint32_t flags, uint32_t line)
2620 {
2621 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2622 		union tcp_log_stackspecific log;
2623 
2624 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2625 		log.u_bbr.flex1 = line;
2626 		log.u_bbr.flex2 = rsm->r_start;
2627 		log.u_bbr.flex3 = rsm->r_end;
2628 		log.u_bbr.flex4 = rsm->r_delivered;
2629 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2630 		log.u_bbr.flex6 = rsm->r_dupack;
2631 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2632 		log.u_bbr.flex8 = rsm->r_flags;
2633 		/* Hijack the pkts_out fids */
2634 		log.u_bbr.applimited = flags;
2635 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2636 		    &bbr->rc_inp->inp_socket->so_rcv,
2637 		    &bbr->rc_inp->inp_socket->so_snd,
2638 		    BBR_RSM_CLEARED, 0,
2639 		    0, &log, false, &bbr->rc_tv);
2640 	}
2641 }
2642 
2643 static void
2644 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2645     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2646     uint32_t flex6, uint32_t pkts_out, int flex7,
2647     uint32_t flex4, uint32_t flex1)
2648 {
2649 
2650 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2651 		union tcp_log_stackspecific log;
2652 
2653 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2654 		log.u_bbr.flex1 = flex1;
2655 		log.u_bbr.flex2 = flex2;
2656 		log.u_bbr.flex3 = flex3;
2657 		log.u_bbr.flex4 = flex4;
2658 		log.u_bbr.flex5 = flex5;
2659 		log.u_bbr.flex6 = flex6;
2660 		log.u_bbr.flex7 = flex7;
2661 		/* Hijack the pkts_out fids */
2662 		log.u_bbr.pkts_out = pkts_out;
2663 		log.u_bbr.flex8 = flex8;
2664 		if (bbr->rc_ack_was_delayed)
2665 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2666 		else
2667 			log.u_bbr.epoch = 0;
2668 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2669 		    &bbr->rc_inp->inp_socket->so_rcv,
2670 		    &bbr->rc_inp->inp_socket->so_snd,
2671 		    BBR_LOG_BBRUPD, 0,
2672 		    flex2, &log, false, &bbr->rc_tv);
2673 	}
2674 }
2675 
2676 static void
2677 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2678 	uint32_t newbw, uint32_t obw, uint32_t diff,
2679 	uint32_t tim)
2680 {
2681 	if (/*bbr_verbose_logging && */(bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2682 		union tcp_log_stackspecific log;
2683 
2684 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2685 		log.u_bbr.flex1 = reason;
2686 		log.u_bbr.flex2 = newbw;
2687 		log.u_bbr.flex3 = obw;
2688 		log.u_bbr.flex4 = diff;
2689 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2690 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2691 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2692 		log.u_bbr.pkts_out = tim;
2693 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2694 		if (bbr->rc_lt_use_bw == 0)
2695 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2696 		else
2697 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2698 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2699 		    &bbr->rc_inp->inp_socket->so_rcv,
2700 		    &bbr->rc_inp->inp_socket->so_snd,
2701 		    BBR_LOG_BWSAMP, 0,
2702 		    0, &log, false, &bbr->rc_tv);
2703 	}
2704 }
2705 
2706 static inline void
2707 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2708 {
2709 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2710 		union tcp_log_stackspecific log;
2711 
2712 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2713 		log.u_bbr.flex1 = line;
2714 		log.u_bbr.flex2 = tick;
2715 		log.u_bbr.flex3 = tp->t_maxunacktime;
2716 		log.u_bbr.flex4 = tp->t_acktime;
2717 		log.u_bbr.flex8 = event;
2718 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2719 		    &bbr->rc_inp->inp_socket->so_rcv,
2720 		    &bbr->rc_inp->inp_socket->so_snd,
2721 		    BBR_LOG_PROGRESS, 0,
2722 		    0, &log, false, &bbr->rc_tv);
2723 	}
2724 }
2725 
2726 static void
2727 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2728 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2729 			 int error)
2730 {
2731 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2732 		union tcp_log_stackspecific log;
2733 
2734 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2735 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2736 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2737 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2738 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2739 		log.u_bbr.bw_inuse = rate;
2740 		log.u_bbr.flex5 = line;
2741 		log.u_bbr.flex6 = error;
2742 		log.u_bbr.flex8 = bbr->skip_gain;
2743 		log.u_bbr.flex8 <<= 1;
2744 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2745 		log.u_bbr.flex8 <<= 1;
2746 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2747 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2748 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2749 		    &bbr->rc_inp->inp_socket->so_rcv,
2750 		    &bbr->rc_inp->inp_socket->so_snd,
2751 		    BBR_LOG_HDWR_PACE, 0,
2752 		    0, &log, false, &bbr->rc_tv);
2753 	}
2754 }
2755 
2756 static void
2757 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)
2758 {
2759 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2760 		union tcp_log_stackspecific log;
2761 
2762 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2763 		log.u_bbr.flex1 = slot;
2764 		log.u_bbr.flex2 = del_by;
2765 		log.u_bbr.flex3 = prev_delay;
2766 		log.u_bbr.flex4 = line;
2767 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2768 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2769 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2770 		log.u_bbr.flex8 = bbr->rc_in_persist;
2771 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2772 		    &bbr->rc_inp->inp_socket->so_rcv,
2773 		    &bbr->rc_inp->inp_socket->so_snd,
2774 		    BBR_LOG_BBRSND, 0,
2775 		    len, &log, false, &bbr->rc_tv);
2776 	}
2777 }
2778 
2779 static void
2780 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)
2781 {
2782 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2783 		union tcp_log_stackspecific log;
2784 
2785 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2786 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2787 		log.u_bbr.flex2 = 0;
2788 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2789 		log.u_bbr.flex4 = end;
2790 		log.u_bbr.flex5 = seq;
2791 		log.u_bbr.flex6 = t;
2792 		log.u_bbr.flex7 = match;
2793 		log.u_bbr.flex8 = flags;
2794 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2795 		    &bbr->rc_inp->inp_socket->so_rcv,
2796 		    &bbr->rc_inp->inp_socket->so_snd,
2797 		    BBR_LOG_BBRRTT, 0,
2798 		    0, &log, false, &bbr->rc_tv);
2799 	}
2800 }
2801 
2802 static void
2803 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2804 {
2805 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2806 		union tcp_log_stackspecific log;
2807 
2808 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2809 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2810 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2811 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2812 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2813 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2814 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2815 		log.u_bbr.flex7 = 0;
2816 		log.u_bbr.flex8 = entry_method;
2817 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2818 		    &bbr->rc_inp->inp_socket->so_rcv,
2819 		    &bbr->rc_inp->inp_socket->so_snd,
2820 		    BBR_LOG_EXIT_GAIN, 0,
2821 		    0, &log, false, &bbr->rc_tv);
2822 	}
2823 }
2824 
2825 static void
2826 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2827 {
2828 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2829 		union tcp_log_stackspecific log;
2830 
2831 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2832 		/* R-HU */
2833 		log.u_bbr.flex1 = 0;
2834 		log.u_bbr.flex2 = 0;
2835 		log.u_bbr.flex3 = 0;
2836 		log.u_bbr.flex4 = 0;
2837 		log.u_bbr.flex7 = 0;
2838 		log.u_bbr.flex8 = settings_desired;
2839 
2840 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2841 		    &bbr->rc_inp->inp_socket->so_rcv,
2842 		    &bbr->rc_inp->inp_socket->so_snd,
2843 		    BBR_LOG_SETTINGS_CHG, 0,
2844 		    0, &log, false, &bbr->rc_tv);
2845 	}
2846 }
2847 
2848 /*
2849  * Returns the bw from the our filter.
2850  */
2851 static inline uint64_t
2852 bbr_get_full_bw(struct tcp_bbr *bbr)
2853 {
2854 	uint64_t bw;
2855 
2856 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2857 
2858 	return (bw);
2859 }
2860 
2861 static inline void
2862 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2863 {
2864 	uint64_t calclr;
2865 	uint32_t lost, del;
2866 
2867 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2868 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2869 	else
2870 		lost = 0;
2871 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2872 	if (lost == 0)  {
2873 		calclr = 0;
2874 	} else if (del) {
2875 		calclr = lost;
2876 		calclr *= (uint64_t)1000;
2877 		calclr /= (uint64_t)del;
2878 	} else {
2879 		/* Nothing delivered? 100.0% loss */
2880 		calclr = 1000;
2881 	}
2882 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2883 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2884 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2885 	bbr->r_ctl.rc_pkt_epoch++;
2886 	if (bbr->rc_no_pacing &&
2887 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2888 		bbr->rc_no_pacing = 0;
2889 		tcp_bbr_tso_size_check(bbr, cts);
2890 	}
2891 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2892 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2893 	/* What was our loss rate */
2894 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2895 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2896 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2897 }
2898 
2899 static inline void
2900 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2901 {
2902 	uint32_t epoch_time;
2903 
2904 	/* Tick the RTT clock */
2905 	bbr->r_ctl.rc_rtt_epoch++;
2906 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2907 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2908 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2909 }
2910 
2911 static inline void
2912 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2913 {
2914 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2915 		bbr->rc_is_pkt_epoch_now = 1;
2916 	}
2917 }
2918 
2919 /*
2920  * Returns the bw from either the b/w filter
2921  * or from the lt_bw (if the connection is being
2922  * policed).
2923  */
2924 static inline uint64_t
2925 __bbr_get_bw(struct tcp_bbr *bbr)
2926 {
2927 	uint64_t bw, min_bw;
2928 	uint64_t rtt;
2929 	int gm_measure_cnt = 1;
2930 
2931 	/*
2932 	 * For startup we make, like google, a
2933 	 * minimum b/w. This is generated from the
2934 	 * IW and the rttProp. We do fall back to srtt
2935 	 * if for some reason (initial handshake) we don't
2936 	 * have a rttProp. We, in the worst case, fall back
2937 	 * to the configured min_bw (rc_initial_hptsi_bw).
2938 	 */
2939 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2940 		/* Attempt first to use rttProp */
2941 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2942 		if (rtt && (rtt < 0xffffffff)) {
2943 measure:
2944 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2945 				((uint64_t)1000000);
2946 			min_bw /= rtt;
2947 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2948 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2949 			}
2950 
2951 		} else if (bbr->rc_tp->t_srtt != 0) {
2952 			/* No rttProp, use srtt? */
2953 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2954 			goto measure;
2955 		} else {
2956 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2957 		}
2958 	} else
2959 		min_bw = 0;
2960 
2961 	if ((bbr->rc_past_init_win == 0) &&
2962 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2963 		bbr->rc_past_init_win = 1;
2964 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2965 		gm_measure_cnt = 0;
2966 	if (gm_measure_cnt &&
2967 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2968 	     (bbr->rc_past_init_win == 0))) {
2969 		/* For google we use our guess rate until we get 1 measurement */
2970 
2971 use_initial_window:
2972 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2973 		if (rtt && (rtt < 0xffffffff)) {
2974 			/*
2975 			 * We have an RTT measurment. Use that in
2976 			 * combination with our initial window to calculate
2977 			 * a b/w.
2978 			 */
2979 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2980 				((uint64_t)1000000);
2981 			bw /= rtt;
2982 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2983 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2984 			}
2985 		} else {
2986 			/* Drop back to the 40 and punt to a default */
2987 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2988 		}
2989 		if (bw < 1)
2990 			/* Probably should panic */
2991 			bw = 1;
2992 		if (bw > min_bw)
2993 			return (bw);
2994 		else
2995 			return (min_bw);
2996 	}
2997 	if (bbr->rc_lt_use_bw)
2998 		bw = bbr->r_ctl.rc_lt_bw;
2999 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
3000 		bw = bbr->r_ctl.red_bw;
3001 	else
3002 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3003 	if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
3004 		/*
3005 		 * Enforce user set rate limit, keep in mind that
3006 		 * t_peakrate_thr is in B/s already
3007 		 */
3008 		bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3009 	}
3010 	if (bw == 0) {
3011 		/* We should not be at 0, go to the initial window then  */
3012 		goto use_initial_window;
3013 	}
3014 	if (bw < 1)
3015 		/* Probably should panic */
3016 		bw = 1;
3017 	if (bw < min_bw)
3018 		bw = min_bw;
3019 	return (bw);
3020 }
3021 
3022 static inline uint64_t
3023 bbr_get_bw(struct tcp_bbr *bbr)
3024 {
3025 	uint64_t bw;
3026 
3027 	bw = __bbr_get_bw(bbr);
3028 	return (bw);
3029 }
3030 
3031 static inline void
3032 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3033 {
3034 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3035 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3036 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3037 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3038 }
3039 
3040 static inline void
3041 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3042 {
3043 	bbr->rc_lt_is_sampling = 0;
3044 	bbr->rc_lt_use_bw = 0;
3045 	bbr->r_ctl.rc_lt_bw = 0;
3046 	bbr_reset_lt_bw_interval(bbr, cts);
3047 }
3048 
3049 static inline void
3050 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3051 {
3052 	uint64_t diff;
3053 
3054 	/* Do we have a previous sample? */
3055 	if (bbr->r_ctl.rc_lt_bw) {
3056 		/* Get the diff in bytes per second */
3057 		if (bbr->r_ctl.rc_lt_bw > bw)
3058 			diff = bbr->r_ctl.rc_lt_bw - bw;
3059 		else
3060 			diff = bw - bbr->r_ctl.rc_lt_bw;
3061 		if ((diff <= bbr_lt_bw_diff) ||
3062 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3063 			/* Consider us policed */
3064 			uint32_t saved_bw;
3065 
3066 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3067 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3068 			bbr->rc_lt_use_bw = 1;
3069 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3070 			/*
3071 			 * Use pkt based epoch for measuring length of
3072 			 * policer up
3073 			 */
3074 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3075 			/*
3076 			 * reason 4 is we need to start consider being
3077 			 * policed
3078 			 */
3079 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3080 			return;
3081 		}
3082 	}
3083 	bbr->r_ctl.rc_lt_bw = bw;
3084 	bbr_reset_lt_bw_interval(bbr, cts);
3085 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3086 }
3087 
3088 static void
3089 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3090 {
3091 	uint32_t ran, deduct;
3092 
3093 	ran = arc4random_uniform(bbr_rand_ot);
3094 	if (ran) {
3095 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3096 		bbr->r_ctl.rc_level_state_extra -= deduct;
3097 	}
3098 }
3099 /*
3100  * Return randomly the starting state
3101  * to use in probebw.
3102  */
3103 static uint8_t
3104 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3105 {
3106 	uint32_t ran;
3107 	uint8_t ret_val;
3108 
3109 	/* Initialize the offset to 0 */
3110 	bbr->r_ctl.rc_exta_time_gd = 0;
3111 	bbr->rc_hit_state_1 = 0;
3112 	bbr->r_ctl.rc_level_state_extra = 0;
3113 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3114 	/*
3115 	 * The math works funny here :) the return value is used to set the
3116 	 * substate and then the state change is called which increments by
3117 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3118 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3119 	 * we return 1 - 7, so we dont return 0 and end up starting in
3120 	 * state 1 (DRAIN).
3121 	 */
3122 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3123 	/* Set an epoch */
3124 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3125 		bbr_set_epoch(bbr, cts, __LINE__);
3126 
3127 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3128 	return (ret_val);
3129 }
3130 
3131 static void
3132 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3133 {
3134 	uint32_t diff, d_time;
3135 	uint64_t del_time, bw, lost, delivered;
3136 
3137 	if (bbr->r_use_policer == 0)
3138 		return;
3139 	if (bbr->rc_lt_use_bw) {
3140 		/* We are using lt bw do we stop yet? */
3141 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3142 		if (diff > bbr_lt_bw_max_rtts) {
3143 			/* Reset it all */
3144 reset_all:
3145 			bbr_reset_lt_bw_sampling(bbr, cts);
3146 			if (bbr->rc_filled_pipe) {
3147 				bbr_set_epoch(bbr, cts, __LINE__);
3148 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3149 				bbr_substate_change(bbr, cts, __LINE__, 0);
3150 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3151 				bbr_log_type_statechange(bbr, cts, __LINE__);
3152 			} else {
3153 				/*
3154 				 * This should not happen really
3155 				 * unless we remove the startup/drain
3156 				 * restrictions above.
3157 				 */
3158 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3159 				bbr_set_epoch(bbr, cts, __LINE__);
3160 				bbr->r_ctl.rc_bbr_state_time = cts;
3161 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3162 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3163 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3164 				bbr_set_state_target(bbr, __LINE__);
3165 				bbr_log_type_statechange(bbr, cts, __LINE__);
3166 			}
3167 			/* reason 0 is to stop using lt-bw */
3168 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3169 			return;
3170 		}
3171 		if (bbr_lt_intvl_fp == 0) {
3172 			/* Not doing false-postive detection */
3173 			return;
3174 		}
3175 		/* False positive detection */
3176 		if (diff == bbr_lt_intvl_fp) {
3177 			/* At bbr_lt_intvl_fp we record the lost */
3178 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3179 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3180 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3181 			/* Now is our loss rate still high? */
3182 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3183 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3184 			if ((delivered == 0) ||
3185 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3186 				/* No still below our threshold */
3187 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3188 			} else {
3189 				/* Yikes its still high, it must be a false positive */
3190 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3191 				goto reset_all;
3192 			}
3193 		}
3194 		return;
3195 	}
3196 	/*
3197 	 * Wait for the first loss before sampling, to let the policer
3198 	 * exhaust its tokens and estimate the steady-state rate allowed by
3199 	 * the policer. Starting samples earlier includes bursts that
3200 	 * over-estimate the bw.
3201 	 */
3202 	if (bbr->rc_lt_is_sampling == 0) {
3203 		/* reason 1 is to begin doing the sampling  */
3204 		if (loss_detected == 0)
3205 			return;
3206 		bbr_reset_lt_bw_interval(bbr, cts);
3207 		bbr->rc_lt_is_sampling = 1;
3208 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3209 		return;
3210 	}
3211 	/* Now how long were we delivering long term last> */
3212 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3213 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3214 	else
3215 		d_time = 0;
3216 
3217 	/* To avoid underestimates, reset sampling if we run out of data. */
3218 	if (bbr->r_ctl.r_app_limited_until) {
3219 		/* Can not measure in app-limited state */
3220 		bbr_reset_lt_bw_sampling(bbr, cts);
3221 		/* reason 2 is to reset sampling due to app limits  */
3222 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3223 		return;
3224 	}
3225 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3226 	if (diff < bbr_lt_intvl_min_rtts) {
3227 		/*
3228 		 * need more samples (we don't
3229 		 * start on a round like linux so
3230 		 * we need 1 more).
3231 		 */
3232 		/* 6 is not_enough time or no-loss */
3233 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3234 		return;
3235 	}
3236 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3237 		/*
3238 		 * For now if we wait too long, reset all sampling. We need
3239 		 * to do some research here, its possible that we should
3240 		 * base this on how much loss as occurred.. something like
3241 		 * if its under 10% (or some thresh) reset all otherwise
3242 		 * don't.  Thats for phase II I guess.
3243 		 */
3244 		bbr_reset_lt_bw_sampling(bbr, cts);
3245  		/* reason 3 is to reset sampling due too long of sampling */
3246 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3247 		return;
3248 	}
3249 	/*
3250 	 * End sampling interval when a packet is lost, so we estimate the
3251 	 * policer tokens were exhausted. Stopping the sampling before the
3252 	 * tokens are exhausted under-estimates the policed rate.
3253 	 */
3254 	if (loss_detected == 0) {
3255 		/* 6 is not_enough time or no-loss */
3256 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3257 		return;
3258 	}
3259 	/* Calculate packets lost and delivered in sampling interval. */
3260 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3261 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3262 	if ((delivered == 0) ||
3263 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3264 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3265 		return;
3266 	}
3267 	if (d_time < 1000) {
3268 		/* Not enough time. wait */
3269 		/* 6 is not_enough time or no-loss */
3270 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3271 		return;
3272 	}
3273 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3274 		/* Too long */
3275 		bbr_reset_lt_bw_sampling(bbr, cts);
3276  		/* reason 3 is to reset sampling due too long of sampling */
3277 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3278 		return;
3279 	}
3280 	del_time = d_time;
3281 	bw = delivered;
3282 	bw *= (uint64_t)USECS_IN_SECOND;
3283 	bw /= del_time;
3284 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3285 }
3286 
3287 /*
3288  * Allocate a sendmap from our zone.
3289  */
3290 static struct bbr_sendmap *
3291 bbr_alloc(struct tcp_bbr *bbr)
3292 {
3293 	struct bbr_sendmap *rsm;
3294 
3295 	BBR_STAT_INC(bbr_to_alloc);
3296 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3297 	if (rsm) {
3298 		bbr->r_ctl.rc_num_maps_alloced++;
3299 		return (rsm);
3300 	}
3301 	if (bbr->r_ctl.rc_free_cnt) {
3302 		BBR_STAT_INC(bbr_to_alloc_emerg);
3303 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3304 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3305 		bbr->r_ctl.rc_free_cnt--;
3306 		return (rsm);
3307 	}
3308 	BBR_STAT_INC(bbr_to_alloc_failed);
3309 	return (NULL);
3310 }
3311 
3312 static struct bbr_sendmap *
3313 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3314 {
3315 	if ((V_tcp_map_entries_limit > 0) &&
3316 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3317 		BBR_STAT_INC(bbr_alloc_limited);
3318 		if (!bbr->alloc_limit_reported) {
3319 			bbr->alloc_limit_reported = 1;
3320 			BBR_STAT_INC(bbr_alloc_limited_conns);
3321 		}
3322 		return (NULL);
3323 	}
3324 	return (bbr_alloc(bbr));
3325 }
3326 
3327 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3328 static struct bbr_sendmap *
3329 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3330 {
3331 	struct bbr_sendmap *rsm;
3332 
3333 	if (limit_type) {
3334 		/* currently there is only one limit type */
3335 		if (V_tcp_map_split_limit > 0 &&
3336 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3337 			BBR_STAT_INC(bbr_split_limited);
3338 			if (!bbr->alloc_limit_reported) {
3339 				bbr->alloc_limit_reported = 1;
3340 				BBR_STAT_INC(bbr_alloc_limited_conns);
3341 			}
3342 			return (NULL);
3343 		}
3344 	}
3345 
3346 	/* allocate and mark in the limit type, if set */
3347 	rsm = bbr_alloc(bbr);
3348 	if (rsm != NULL && limit_type) {
3349 		rsm->r_limit_type = limit_type;
3350 		bbr->r_ctl.rc_num_split_allocs++;
3351 	}
3352 	return (rsm);
3353 }
3354 
3355 static void
3356 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3357 {
3358 	if (rsm->r_limit_type) {
3359 		/* currently there is only one limit type */
3360 		bbr->r_ctl.rc_num_split_allocs--;
3361 	}
3362 	if (rsm->r_is_smallmap)
3363 		bbr->r_ctl.rc_num_small_maps_alloced--;
3364 	if (bbr->r_ctl.rc_tlp_send == rsm)
3365 		bbr->r_ctl.rc_tlp_send = NULL;
3366 	if (bbr->r_ctl.rc_resend == rsm) {
3367 		bbr->r_ctl.rc_resend = NULL;
3368 	}
3369 	if (bbr->r_ctl.rc_next == rsm)
3370 		bbr->r_ctl.rc_next = NULL;
3371 	if (bbr->r_ctl.rc_sacklast == rsm)
3372 		bbr->r_ctl.rc_sacklast = NULL;
3373 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3374 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3375 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3376 		rsm->r_limit_type = 0;
3377 		bbr->r_ctl.rc_free_cnt++;
3378 		return;
3379 	}
3380 	bbr->r_ctl.rc_num_maps_alloced--;
3381 	uma_zfree(bbr_zone, rsm);
3382 }
3383 
3384 /*
3385  * Returns the BDP.
3386  */
3387 static uint64_t
3388 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3389 	/*
3390 	 * Calculate the bytes in flight needed given the bw (in bytes per
3391 	 * second) and the specifyed rtt in useconds. We need to put out the
3392 	 * returned value per RTT to match that rate. Gain will normally
3393 	 * raise it up from there.
3394 	 *
3395 	 * This should not overflow as long as the bandwidth is below 1
3396 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3397 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3398 	 */
3399 	uint64_t usec_per_sec;
3400 
3401 	usec_per_sec = USECS_IN_SECOND;
3402 	return ((rtt * bw) / usec_per_sec);
3403 }
3404 
3405 /*
3406  * Return the initial cwnd.
3407  */
3408 static uint32_t
3409 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3410 {
3411 	uint32_t i_cwnd;
3412 
3413 	if (bbr->rc_init_win) {
3414 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3415 	} else if (V_tcp_initcwnd_segments)
3416 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3417 		    max(2 * tp->t_maxseg, 14600));
3418 	else if (V_tcp_do_rfc3390)
3419 		i_cwnd = min(4 * tp->t_maxseg,
3420 		    max(2 * tp->t_maxseg, 4380));
3421 	else {
3422 		/* Per RFC5681 Section 3.1 */
3423 		if (tp->t_maxseg > 2190)
3424 			i_cwnd = 2 * tp->t_maxseg;
3425 		else if (tp->t_maxseg > 1095)
3426 			i_cwnd = 3 * tp->t_maxseg;
3427 		else
3428 			i_cwnd = 4 * tp->t_maxseg;
3429 	}
3430 	return (i_cwnd);
3431 }
3432 
3433 /*
3434  * Given a specified gain, return the target
3435  * cwnd based on that gain.
3436  */
3437 static uint32_t
3438 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3439 {
3440 	uint64_t bdp, rtt;
3441 	uint32_t cwnd;
3442 
3443 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3444 	    (bbr_get_full_bw(bbr) == 0)) {
3445 		/* No measurements yet */
3446 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3447 	}
3448 	/*
3449 	 * Get bytes per RTT needed (rttProp is normally in
3450 	 * bbr_cwndtarget_rtt_touse)
3451 	 */
3452 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3453 	/* Get the bdp from the two values */
3454 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3455 	/* Now apply the gain */
3456 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3457 
3458 	return (cwnd);
3459 }
3460 
3461 static uint32_t
3462 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3463 {
3464 	uint32_t cwnd, mss;
3465 
3466 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3467 	/* Get the base cwnd with gain rounded to a mss */
3468 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3469 	/*
3470 	 * Add in N (2 default since we do not have a
3471 	 * fq layer to trap packets in) quanta's per the I-D
3472 	 * section 4.2.3.2 quanta adjust.
3473 	 */
3474 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3475 	if (bbr->rc_use_google) {
3476 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3477 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3478 			/*
3479 			 * The linux implementation adds
3480 			 * an extra 2 x mss in gain cycle which
3481 			 * is documented no-where except in the code.
3482 			 * so we add more for Neal undocumented feature
3483 			 */
3484 			cwnd += 2 * mss;
3485 		}
3486  		if ((cwnd / mss) & 0x1) {
3487 			/* Round up for odd num mss */
3488 			cwnd += mss;
3489 		}
3490 	}
3491 	/* Are we below the min cwnd? */
3492 	if (cwnd < get_min_cwnd(bbr))
3493 		return (get_min_cwnd(bbr));
3494 	return (cwnd);
3495 }
3496 
3497 static uint16_t
3498 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3499 {
3500 	if (gain < 1)
3501 		gain = 1;
3502 	return (gain);
3503 }
3504 
3505 static uint32_t
3506 bbr_get_header_oh(struct tcp_bbr *bbr)
3507 {
3508 	int seg_oh;
3509 
3510 	seg_oh = 0;
3511 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3512 		/* Do we include TCP overhead? */
3513 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3514 	}
3515 	if (bbr->r_ctl.rc_inc_ip_oh) {
3516 		/* Do we include IP overhead? */
3517 #ifdef INET6
3518 		if (bbr->r_is_v6) {
3519 			seg_oh += sizeof(struct ip6_hdr);
3520 		} else
3521 #endif
3522 		{
3523 
3524 #ifdef INET
3525 			seg_oh += sizeof(struct ip);
3526 #endif
3527 		}
3528 	}
3529 	if (bbr->r_ctl.rc_inc_enet_oh) {
3530 		/* Do we include the ethernet overhead?  */
3531 		seg_oh += sizeof(struct ether_header);
3532 	}
3533 	return(seg_oh);
3534 }
3535 
3536 static uint32_t
3537 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3538 {
3539 	uint64_t divor, res, tim;
3540 
3541 	if (useconds_time == 0)
3542 		return (0);
3543 	gain = bbr_gain_adjust(bbr, gain);
3544 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3545 	tim = useconds_time;
3546 	res = (tim * bw * gain) / divor;
3547 	if (res == 0)
3548 		res = 1;
3549 	return ((uint32_t)res);
3550 }
3551 
3552 /*
3553  * Given a gain and a length return the delay in useconds that
3554  * should be used to evenly space out packets
3555  * on the connection (based on the gain factor).
3556  */
3557 static uint32_t
3558 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3559 {
3560 	uint64_t bw, lentim, res;
3561 	uint32_t usecs, srtt, over = 0;
3562 	uint32_t seg_oh, num_segs, maxseg;
3563 
3564 	if (len == 0)
3565 		return (0);
3566 
3567 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3568 	num_segs = (len + maxseg - 1) / maxseg;
3569 	if (bbr->rc_use_google == 0) {
3570 		seg_oh = bbr_get_header_oh(bbr);
3571 		len += (num_segs * seg_oh);
3572 	}
3573 	gain = bbr_gain_adjust(bbr, gain);
3574 	bw = bbr_get_bw(bbr);
3575 	if (bbr->rc_use_google) {
3576 		uint64_t cbw;
3577 
3578 		/*
3579 		 * Reduce the b/w by the google discount
3580 		 * factor 10 = 1%.
3581 		 */
3582 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3583 		cbw /= (uint64_t)1000;
3584 		/* We don't apply a discount if it results in 0 */
3585 		if (cbw > 0)
3586 			bw = cbw;
3587 	}
3588 	lentim = ((uint64_t)len *
3589 		  (uint64_t)USECS_IN_SECOND *
3590 		  (uint64_t)BBR_UNIT);
3591 	res = lentim / ((uint64_t)gain * bw);
3592 	if (res == 0)
3593 		res = 1;
3594 	usecs = (uint32_t)res;
3595 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3596 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3597 	    (bbr->rc_use_google == 0) &&
3598 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3599 		/*
3600 		 * We cannot let the delay be more than 1/2 the srtt time.
3601 		 * Otherwise we cannot pace out or send properly.
3602 		 */
3603 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3604 		BBR_STAT_INC(bbr_hpts_min_time);
3605 	}
3606 	if (!nolog)
3607 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3608 	return (usecs);
3609 }
3610 
3611 static void
3612 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3613 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3614 {
3615 	INP_WLOCK_ASSERT(tp->t_inpcb);
3616 	uint64_t bw;
3617 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3618 	int32_t meth;
3619 
3620 #ifdef STATS
3621 	if ((tp->t_flags & TF_GPUTINPROG) &&
3622 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3623 		/*
3624 		 * Strech acks and compressed acks will cause this to
3625 		 * oscillate but we are doing it the same way as the main
3626 		 * stack so it will be compariable (though possibly not
3627 		 * ideal).
3628 		 */
3629 		int32_t cgput;
3630 		int64_t gput, time_stamp;
3631 
3632 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3633 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3634 		cgput = gput / time_stamp;
3635 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3636 					 cgput);
3637 		if (tp->t_stats_gput_prev > 0)
3638 			stats_voi_update_abs_s32(tp->t_stats,
3639 						 VOI_TCP_GPUT_ND,
3640 						 ((gput - tp->t_stats_gput_prev) * 100) /
3641 						 tp->t_stats_gput_prev);
3642 		tp->t_flags &= ~TF_GPUTINPROG;
3643 		tp->t_stats_gput_prev = cgput;
3644 	}
3645 #endif
3646 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3647 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3648 		/* We don't change anything in probe-rtt */
3649 		return;
3650 	}
3651 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3652 	saved_bytes = bytes_this_ack;
3653 	bytes_this_ack += sack_changed;
3654 	if (bytes_this_ack > prev_acked) {
3655 		bytes_this_ack -= prev_acked;
3656 		/*
3657 		 * A byte ack'd gives us a full mss
3658 		 * to be like linux i.e. they count packets.
3659 		 */
3660 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3661 			bytes_this_ack = maxseg;
3662 	} else {
3663 		/* Unlikely */
3664 		bytes_this_ack = 0;
3665 	}
3666 	cwnd = tp->snd_cwnd;
3667 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3668 	if (bw)
3669 		target_cwnd = bbr_get_target_cwnd(bbr,
3670 						  bw,
3671 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3672 	else
3673 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3674 	if (IN_RECOVERY(tp->t_flags) &&
3675 	    (bbr->bbr_prev_in_rec == 0)) {
3676 		/*
3677 		 * We are entering recovery and
3678 		 * thus packet conservation.
3679 		 */
3680 		bbr->pkt_conservation = 1;
3681 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3682 		cwnd = ctf_flight_size(tp,
3683 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3684 			bytes_this_ack;
3685 	}
3686 	if (IN_RECOVERY(tp->t_flags)) {
3687 		uint32_t flight;
3688 
3689 		bbr->bbr_prev_in_rec = 1;
3690 		if (cwnd > losses) {
3691 			cwnd -= losses;
3692 			if (cwnd < maxseg)
3693 				cwnd = maxseg;
3694 		} else
3695 			cwnd = maxseg;
3696 		flight = ctf_flight_size(tp,
3697 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3698 		bbr_log_type_cwndupd(bbr, flight, 0,
3699 				     losses, 10, 0, 0, line);
3700 		if (bbr->pkt_conservation) {
3701 			uint32_t time_in;
3702 
3703 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3704 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3705 			else
3706 				time_in = 0;
3707 
3708 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3709 				/* Clear packet conservation after an rttProp */
3710 				bbr->pkt_conservation = 0;
3711 			} else {
3712 				if ((flight + bytes_this_ack) > cwnd)
3713 					cwnd = flight + bytes_this_ack;
3714 				if (cwnd < get_min_cwnd(bbr))
3715 					cwnd = get_min_cwnd(bbr);
3716 				tp->snd_cwnd = cwnd;
3717 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3718 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3719 				return;
3720 			}
3721 		}
3722 	} else
3723 		bbr->bbr_prev_in_rec = 0;
3724 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3725 		bbr->r_ctl.restrict_growth--;
3726 		if (bytes_this_ack > maxseg)
3727 			bytes_this_ack = maxseg;
3728 	}
3729 	if (bbr->rc_filled_pipe) {
3730 		/*
3731 		 * Here we have exited startup and filled the pipe. We will
3732 		 * thus allow the cwnd to shrink to the target. We hit here
3733 		 * mostly.
3734 		 */
3735 		uint32_t s_cwnd;
3736 
3737 		meth = 2;
3738 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3739 		if (s_cwnd > cwnd)
3740 			cwnd = s_cwnd;
3741 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3742 			cwnd = s_cwnd;
3743 	} else {
3744 		/*
3745 		 * Here we are still in startup, we increase cwnd by what
3746 		 * has been acked.
3747 		 */
3748 		if ((cwnd < target_cwnd) ||
3749 		    (bbr->rc_past_init_win == 0)) {
3750 			meth = 3;
3751 			cwnd += bytes_this_ack;
3752 		} else {
3753 			/*
3754 			 * Method 4 means we are at target so no gain in
3755 			 * startup and past the initial window.
3756 			 */
3757 			meth = 4;
3758 		}
3759 	}
3760 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3761 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3762 }
3763 
3764 static void
3765 tcp_bbr_partialack(struct tcpcb *tp)
3766 {
3767 	struct tcp_bbr *bbr;
3768 
3769 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3770 	INP_WLOCK_ASSERT(tp->t_inpcb);
3771 	if (ctf_flight_size(tp,
3772 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3773 	    tp->snd_cwnd) {
3774 		bbr->r_wanted_output = 1;
3775 	}
3776 }
3777 
3778 static void
3779 bbr_post_recovery(struct tcpcb *tp)
3780 {
3781 	struct tcp_bbr *bbr;
3782 	uint32_t  flight;
3783 
3784 	INP_WLOCK_ASSERT(tp->t_inpcb);
3785 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3786 	/*
3787 	 * Here we just exit recovery.
3788 	 */
3789 	EXIT_RECOVERY(tp->t_flags);
3790 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3791 	bbr->r_recovery_bw = 0;
3792 	tp->snd_recover = tp->snd_una;
3793 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3794 	bbr->pkt_conservation = 0;
3795 	if (bbr->rc_use_google == 0) {
3796 		/*
3797 		 * For non-google mode lets
3798 		 * go ahead and make sure we clear
3799 		 * the recovery state so if we
3800 		 * bounce back in to recovery we
3801 		 * will do PC.
3802 		 */
3803 		bbr->bbr_prev_in_rec = 0;
3804 	}
3805 	bbr_log_type_exit_rec(bbr);
3806 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3807 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3808 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3809 	} else {
3810 		/* For probe-rtt case lets fix up its saved_cwnd */
3811 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3812 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3813 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3814 		}
3815 	}
3816 	flight = ctf_flight_size(tp,
3817 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3818 	if ((bbr->rc_use_google == 0) &&
3819 	    bbr_do_red) {
3820 		uint64_t val, lr2use;
3821 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3822 		uint32_t *cwnd_p;
3823 
3824 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3825 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3826 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3827 			ratio = (uint32_t)val;
3828 		} else
3829 			ratio = 1000;
3830 
3831 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3832 				     bbr->r_ctl.recovery_lr, 21,
3833 				     ratio,
3834 				     bbr->r_ctl.rc_red_cwnd_pe,
3835 				     __LINE__);
3836 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3837 			goto done;
3838 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3839 		     bbr_prtt_slam_cwnd) ||
3840 		    (bbr_sub_drain_slam_cwnd &&
3841 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3842 		     bbr->rc_hit_state_1 &&
3843 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3844 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3845 		     bbr_slam_cwnd_in_main_drain)) {
3846 			/*
3847 			 * Here we must poke at the saved cwnd
3848 			 * as well as the cwnd.
3849 			 */
3850 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3851 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3852 		} else {
3853  			cwnd = tp->snd_cwnd;
3854 			cwnd_p = &tp->snd_cwnd;
3855 		}
3856 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3857 		/* Add the overall lr with the recovery lr */
3858 		if (bbr->r_ctl.rc_lost == 0)
3859 			lr2use = 0;
3860 		else if (bbr->r_ctl.rc_delivered == 0)
3861 			lr2use = 1000;
3862 		else {
3863 			lr2use = bbr->r_ctl.rc_lost * 1000;
3864 			lr2use /= bbr->r_ctl.rc_delivered;
3865 		}
3866 		lr2use += bbr->r_ctl.recovery_lr;
3867 		acks_inflight = (flight / (maxseg * 2));
3868 		if (bbr_red_scale) {
3869 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3870 			lr2use /= bbr_red_scale;
3871 			if ((bbr_red_growth_restrict) &&
3872 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3873 			    bbr->r_ctl.restrict_growth += acks_inflight;
3874 		}
3875 		if (lr2use) {
3876 			val = (uint64_t)cwnd * lr2use;
3877 			val /= 1000;
3878 			if (cwnd > val)
3879 				newcwnd = roundup((cwnd - val), maxseg);
3880 			else
3881 				newcwnd = maxseg;
3882 		} else {
3883 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3884 			val /= (uint64_t)bbr_red_div;
3885 			newcwnd = roundup((uint32_t)val, maxseg);
3886 		}
3887 		/* with standard delayed acks how many acks can I expect? */
3888 		if (bbr_drop_limit == 0) {
3889 			/*
3890 			 * Anticpate how much we will
3891 			 * raise the cwnd based on the acks.
3892 			 */
3893 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3894 				/* We do enforce the min (with the acks) */
3895 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3896 			}
3897 		} else {
3898 			/*
3899 			 * A strict drop limit of N is is inplace
3900 			 */
3901 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3902 				newcwnd = bbr_drop_limit * maxseg;
3903 			}
3904 		}
3905 		/* For the next N acks do we restrict the growth */
3906 		*cwnd_p = newcwnd;
3907 		if (tp->snd_cwnd > newcwnd)
3908 			tp->snd_cwnd = newcwnd;
3909 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3910 				     (uint32_t)lr2use,
3911 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3912 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3913 	}
3914 done:
3915 	bbr->r_ctl.recovery_lr = 0;
3916 	if (flight <= tp->snd_cwnd) {
3917 		bbr->r_wanted_output = 1;
3918 	}
3919 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3920 }
3921 
3922 static void
3923 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3924 {
3925 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3926 	/* Limit the drop in b/w to 1/2 our current filter. */
3927 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3928 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3929 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3930 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3931 	tcp_bbr_tso_size_check(bbr, cts);
3932 }
3933 
3934 static void
3935 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3936 {
3937 	struct tcp_bbr *bbr;
3938 
3939 	INP_WLOCK_ASSERT(tp->t_inpcb);
3940 #ifdef STATS
3941 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3942 #endif
3943 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3944 	switch (type) {
3945 	case CC_NDUPACK:
3946 		if (!IN_RECOVERY(tp->t_flags)) {
3947 			tp->snd_recover = tp->snd_max;
3948 			/* Start a new epoch */
3949 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3950 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3951 				/*
3952 				 * Move forward the lt epoch
3953 				 * so it won't count the truncated
3954 				 * epoch.
3955 				 */
3956 				bbr->r_ctl.rc_lt_epoch++;
3957 			}
3958 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3959 				/*
3960 				 * Just like the policer detection code
3961 				 * if we are in startup we must push
3962 				 * forward the last startup epoch
3963 				 * to hide the truncated PE.
3964 				 */
3965 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3966 			}
3967 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3968 			ENTER_RECOVERY(tp->t_flags);
3969 			bbr->rc_tlp_rtx_out = 0;
3970 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3971 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3972 			if (bbr->rc_inp->inp_in_hpts &&
3973 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3974 				/*
3975 				 * When we enter recovery, we need to restart
3976 				 * any timers. This may mean we gain an agg
3977 				 * early, which will be made up for at the last
3978 				 * rxt out.
3979 				 */
3980 				bbr->rc_timer_first = 1;
3981 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3982 			}
3983 			/*
3984 			 * Calculate a new cwnd based on to the current
3985 			 * delivery rate with no gain. We get the bdp
3986 			 * without gaining it up like we normally would and
3987 			 * we use the last cur_del_rate.
3988 			 */
3989 			if ((bbr->rc_use_google == 0) &&
3990 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3991 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3992 				tp->snd_cwnd = ctf_flight_size(tp,
3993 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3994 					(tp->t_maxseg - bbr->rc_last_options);
3995 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3996 					/* We always gate to min cwnd */
3997 					tp->snd_cwnd = get_min_cwnd(bbr);
3998 				}
3999 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
4000 			}
4001 			bbr_log_type_enter_rec(bbr, rsm->r_start);
4002 		}
4003 		break;
4004 	case CC_RTO_ERR:
4005 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
4006 		/* RTO was unnecessary, so reset everything. */
4007 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
4008 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
4009 			tp->snd_cwnd = tp->snd_cwnd_prev;
4010 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
4011 			tp->snd_recover = tp->snd_recover_prev;
4012 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
4013 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
4014 		}
4015 		tp->t_badrxtwin = 0;
4016 		break;
4017 	}
4018 }
4019 
4020 /*
4021  * Indicate whether this ack should be delayed.  We can delay the ack if
4022  * following conditions are met:
4023  *	- There is no delayed ack timer in progress.
4024  *	- Our last ack wasn't a 0-sized window. We never want to delay
4025  *	  the ack that opens up a 0-sized window.
4026  *	- LRO wasn't used for this segment. We make sure by checking that the
4027  *	  segment size is not larger than the MSS.
4028  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4029  *	  connection.
4030  *	- The data being acked is less than a full segment (a stretch ack
4031  *        of more than a segment we should ack.
4032  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4033  */
4034 #define DELAY_ACK(tp, bbr, nsegs)				\
4035 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4036 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4037 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4038 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4039 
4040 /*
4041  * Return the lowest RSM in the map of
4042  * packets still in flight that is not acked.
4043  * This should normally find on the first one
4044  * since we remove packets from the send
4045  * map after they are marked ACKED.
4046  */
4047 static struct bbr_sendmap *
4048 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4049 {
4050 	struct bbr_sendmap *rsm;
4051 
4052 	/*
4053 	 * Walk the time-order transmitted list looking for an rsm that is
4054 	 * not acked. This will be the one that was sent the longest time
4055 	 * ago that is still outstanding.
4056 	 */
4057 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4058 		if (rsm->r_flags & BBR_ACKED) {
4059 			continue;
4060 		}
4061 		goto finish;
4062 	}
4063 finish:
4064 	return (rsm);
4065 }
4066 
4067 static struct bbr_sendmap *
4068 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4069 {
4070 	struct bbr_sendmap *prsm;
4071 
4072 	/*
4073 	 * Walk the sequence order list backward until we hit and arrive at
4074 	 * the highest seq not acked. In theory when this is called it
4075 	 * should be the last segment (which it was not).
4076 	 */
4077 	prsm = rsm;
4078 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4079 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4080 			continue;
4081 		}
4082 		return (prsm);
4083 	}
4084 	return (NULL);
4085 }
4086 
4087 /*
4088  * Returns to the caller the number of microseconds that
4089  * the packet can be outstanding before we think we
4090  * should have had an ack returned.
4091  */
4092 static uint32_t
4093 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4094 {
4095 	/*
4096 	 * lro is the flag we use to determine if we have seen reordering.
4097 	 * If it gets set we have seen reordering. The reorder logic either
4098 	 * works in one of two ways:
4099 	 *
4100 	 * If reorder-fade is configured, then we track the last time we saw
4101 	 * re-ordering occur. If we reach the point where enough time as
4102 	 * passed we no longer consider reordering has occuring.
4103 	 *
4104 	 * Or if reorder-face is 0, then once we see reordering we consider
4105 	 * the connection to alway be subject to reordering and just set lro
4106 	 * to 1.
4107 	 *
4108 	 * In the end if lro is non-zero we add the extra time for
4109 	 * reordering in.
4110 	 */
4111 	int32_t lro;
4112 	uint32_t thresh, t_rxtcur;
4113 
4114 	if (srtt == 0)
4115 		srtt = 1;
4116 	if (bbr->r_ctl.rc_reorder_ts) {
4117 		if (bbr->r_ctl.rc_reorder_fade) {
4118 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4119 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4120 				if (lro == 0) {
4121 					/*
4122 					 * No time as passed since the last
4123 					 * reorder, mark it as reordering.
4124 					 */
4125 					lro = 1;
4126 				}
4127 			} else {
4128 				/* Negative time? */
4129 				lro = 0;
4130 			}
4131 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4132 				/* Turn off reordering seen too */
4133 				bbr->r_ctl.rc_reorder_ts = 0;
4134 				lro = 0;
4135 			}
4136 		} else {
4137 			/* Reodering does not fade */
4138 			lro = 1;
4139 		}
4140 	} else {
4141 		lro = 0;
4142 	}
4143 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4144 	if (lro) {
4145 		/* It must be set, if not you get 1/4 rtt */
4146 		if (bbr->r_ctl.rc_reorder_shift)
4147 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4148 		else
4149 			thresh += (srtt >> 2);
4150 	} else {
4151 		thresh += 1000;
4152 	}
4153 	/* We don't let the rack timeout be above a RTO */
4154 	if ((bbr->rc_tp)->t_srtt == 0)
4155 		t_rxtcur = BBR_INITIAL_RTO;
4156 	else
4157 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4158 	if (thresh > t_rxtcur) {
4159 		thresh = t_rxtcur;
4160 	}
4161 	/* And we don't want it above the RTO max either */
4162 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4163 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4164 	}
4165 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4166 	return (thresh);
4167 }
4168 
4169 /*
4170  * Return to the caller the amount of time in mico-seconds
4171  * that should be used for the TLP timer from the last
4172  * send time of this packet.
4173  */
4174 static uint32_t
4175 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4176     struct bbr_sendmap *rsm, uint32_t srtt,
4177     uint32_t cts)
4178 {
4179 	uint32_t thresh, len, maxseg, t_rxtcur;
4180 	struct bbr_sendmap *prsm;
4181 
4182 	if (srtt == 0)
4183 		srtt = 1;
4184 	if (bbr->rc_tlp_threshold)
4185 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4186 	else
4187 		thresh = (srtt * 2);
4188 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4189 	/* Get the previous sent packet, if any  */
4190 	len = rsm->r_end - rsm->r_start;
4191 
4192 	/* 2.1 behavior */
4193 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4194 	if (prsm && (len <= maxseg)) {
4195 		/*
4196 		 * Two packets outstanding, thresh should be (2*srtt) +
4197 		 * possible inter-packet delay (if any).
4198 		 */
4199 		uint32_t inter_gap = 0;
4200 		int idx, nidx;
4201 
4202 		idx = rsm->r_rtr_cnt - 1;
4203 		nidx = prsm->r_rtr_cnt - 1;
4204 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4205 			/* Yes it was sent later (or at the same time) */
4206 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4207 		}
4208 		thresh += inter_gap;
4209 	} else if (len <= maxseg) {
4210 		/*
4211 		 * Possibly compensate for delayed-ack.
4212 		 */
4213 		uint32_t alt_thresh;
4214 
4215 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4216 		if (alt_thresh > thresh)
4217 			thresh = alt_thresh;
4218 	}
4219 	/* Not above the current  RTO */
4220 	if (tp->t_srtt == 0)
4221 		t_rxtcur = BBR_INITIAL_RTO;
4222 	else
4223 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4224 
4225 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4226 	/* Not above an RTO */
4227 	if (thresh > t_rxtcur) {
4228 		thresh = t_rxtcur;
4229 	}
4230 	/* Not above a RTO max */
4231 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4232 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4233 	}
4234 	/* And now apply the user TLP min */
4235 	if (thresh < bbr_tlp_min) {
4236 		thresh = bbr_tlp_min;
4237 	}
4238 	return (thresh);
4239 }
4240 
4241 /*
4242  * Return one of three RTTs to use (in microseconds).
4243  */
4244 static __inline uint32_t
4245 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4246 {
4247 	uint32_t f_rtt;
4248 	uint32_t srtt;
4249 
4250 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4251 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4252 		/* We have no rtt at all */
4253 		if (bbr->rc_tp->t_srtt == 0)
4254 			f_rtt = BBR_INITIAL_RTO;
4255 		else
4256 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4257 		/*
4258 		 * Since we don't know how good the rtt is apply a
4259 		 * delayed-ack min
4260 		 */
4261 		if (f_rtt < bbr_delayed_ack_time) {
4262 			f_rtt = bbr_delayed_ack_time;
4263 		}
4264 	}
4265 	/* Take the filter version or last measured pkt-rtt */
4266 	if (rtt_type == BBR_RTT_PROP) {
4267 		srtt = f_rtt;
4268 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4269 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4270 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4271 		} else {
4272 			/* No pkt rtt yet */
4273 			srtt = f_rtt;
4274 		}
4275 	} else if (rtt_type == BBR_RTT_RACK) {
4276 		srtt = bbr->r_ctl.rc_last_rtt;
4277 		/* We need to add in any internal delay for our timer */
4278 		if (bbr->rc_ack_was_delayed)
4279 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4280 	} else if (rtt_type == BBR_SRTT) {
4281 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4282 	} else {
4283 		/* TSNH */
4284 		srtt = f_rtt;
4285 #ifdef BBR_INVARIANTS
4286 		panic("Unknown rtt request type %d", rtt_type);
4287 #endif
4288 	}
4289 	return (srtt);
4290 }
4291 
4292 static int
4293 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4294 {
4295 	uint32_t thresh;
4296 
4297 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4298 				      cts, rsm);
4299 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4300 		/* It is lost (past time) */
4301 		return (1);
4302 	}
4303 	return (0);
4304 }
4305 
4306 /*
4307  * Return a sendmap if we need to retransmit something.
4308  */
4309 static struct bbr_sendmap *
4310 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4311 {
4312 	/*
4313 	 * Check to see that we don't need to fall into recovery. We will
4314 	 * need to do so if our oldest transmit is past the time we should
4315 	 * have had an ack.
4316 	 */
4317 
4318 	struct bbr_sendmap *rsm;
4319 	int32_t idx;
4320 
4321 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4322 		/* Nothing outstanding that we know of */
4323 		return (NULL);
4324 	}
4325 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4326 	if (rsm == NULL) {
4327 		/* Nothing in the transmit map */
4328 		return (NULL);
4329 	}
4330 	if (tp->t_flags & TF_SENTFIN) {
4331 		/* Fin restricted, don't find anything once a fin is sent */
4332 		return (NULL);
4333 	}
4334 	if (rsm->r_flags & BBR_ACKED) {
4335 		/*
4336 		 * Ok the first one is acked (this really should not happen
4337 		 * since we remove the from the tmap once they are acked)
4338 		 */
4339 		rsm = bbr_find_lowest_rsm(bbr);
4340 		if (rsm == NULL)
4341 			return (NULL);
4342 	}
4343 	idx = rsm->r_rtr_cnt - 1;
4344 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4345 		/* Send timestamp is the same or less? can't be ready */
4346 		return (NULL);
4347 	}
4348 	/* Get our RTT time */
4349 	if (bbr_is_lost(bbr, rsm, cts) &&
4350 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4351 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4352 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4353 			rsm->r_flags |= BBR_MARKED_LOST;
4354 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4355 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4356 		}
4357 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4358 #ifdef BBR_INVARIANTS
4359 		if ((rsm->r_end - rsm->r_start) == 0)
4360 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4361 #endif
4362 		return (rsm);
4363 	}
4364 	return (NULL);
4365 }
4366 
4367 /*
4368  * RACK Timer, here we simply do logging and house keeping.
4369  * the normal bbr_output_wtime() function will call the
4370  * appropriate thing to check if we need to do a RACK retransmit.
4371  * We return 1, saying don't proceed with bbr_output_wtime only
4372  * when all timers have been stopped (destroyed PCB?).
4373  */
4374 static int
4375 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4376 {
4377 	/*
4378 	 * This timer simply provides an internal trigger to send out data.
4379 	 * The check_recovery_mode call will see if there are needed
4380 	 * retransmissions, if so we will enter fast-recovery. The output
4381 	 * call may or may not do the same thing depending on sysctl
4382 	 * settings.
4383 	 */
4384 	uint32_t lost;
4385 
4386 	if (bbr->rc_all_timers_stopped) {
4387 		return (1);
4388 	}
4389 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4390 		/* Its not time yet */
4391 		return (0);
4392 	}
4393 	BBR_STAT_INC(bbr_to_tot);
4394 	lost = bbr->r_ctl.rc_lost;
4395 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4396 		bbr_set_state(tp, bbr, 0);
4397 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4398 	if (bbr->r_ctl.rc_resend == NULL) {
4399 		/* Lets do the check here */
4400 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4401 	}
4402 	if (bbr_policer_call_from_rack_to)
4403 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4404 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4405 	return (0);
4406 }
4407 
4408 static __inline void
4409 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4410 {
4411 	int idx;
4412 
4413 	nrsm->r_start = start;
4414 	nrsm->r_end = rsm->r_end;
4415 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4416 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4417 	nrsm->r_flags = rsm->r_flags;
4418 	/* We don't transfer forward the SYN flag */
4419 	nrsm->r_flags &= ~BBR_HAS_SYN;
4420 	/* We move forward the FIN flag, not that this should happen */
4421 	rsm->r_flags &= ~BBR_HAS_FIN;
4422 	nrsm->r_dupack = rsm->r_dupack;
4423 	nrsm->r_rtr_bytes = 0;
4424 	nrsm->r_is_gain = rsm->r_is_gain;
4425 	nrsm->r_is_drain = rsm->r_is_drain;
4426 	nrsm->r_delivered = rsm->r_delivered;
4427 	nrsm->r_ts_valid = rsm->r_ts_valid;
4428 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4429 	nrsm->r_del_time = rsm->r_del_time;
4430 	nrsm->r_app_limited = rsm->r_app_limited;
4431 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4432 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4433 	/* We split a piece the lower section looses any just_ret flag. */
4434 	nrsm->r_bbr_state = rsm->r_bbr_state;
4435 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4436 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4437 	}
4438 	rsm->r_end = nrsm->r_start;
4439 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4440 	idx /= 8;
4441 	/* Check if we got too small */
4442 	if ((rsm->r_is_smallmap == 0) &&
4443 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4444 		bbr->r_ctl.rc_num_small_maps_alloced++;
4445 		rsm->r_is_smallmap = 1;
4446 	}
4447 	/* Check the new one as well */
4448 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4449 		bbr->r_ctl.rc_num_small_maps_alloced++;
4450 		nrsm->r_is_smallmap = 1;
4451 	}
4452 }
4453 
4454 static int
4455 bbr_sack_mergable(struct bbr_sendmap *at,
4456 		  uint32_t start, uint32_t end)
4457 {
4458 	/*
4459 	 * Given a sack block defined by
4460 	 * start and end, and a current postion
4461 	 * at. Return 1 if either side of at
4462 	 * would show that the block is mergable
4463 	 * to that side. A block to be mergable
4464 	 * must have overlap with the start/end
4465 	 * and be in the SACK'd state.
4466 	 */
4467 	struct bbr_sendmap *l_rsm;
4468 	struct bbr_sendmap *r_rsm;
4469 
4470 	/* first get the either side blocks */
4471 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4472 	r_rsm = TAILQ_NEXT(at, r_next);
4473 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4474 		/* Potentially mergeable */
4475 		if ((l_rsm->r_end == start) ||
4476 		    (SEQ_LT(start, l_rsm->r_end) &&
4477 		     SEQ_GT(end, l_rsm->r_end))) {
4478 			    /*
4479 			     * map blk   |------|
4480 			     * sack blk         |------|
4481 			     * <or>
4482 			     * map blk   |------|
4483 			     * sack blk      |------|
4484 			     */
4485 			    return (1);
4486 		    }
4487 	}
4488 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4489 		/* Potentially mergeable */
4490 		if ((r_rsm->r_start == end) ||
4491 		    (SEQ_LT(start, r_rsm->r_start) &&
4492 		     SEQ_GT(end, r_rsm->r_start))) {
4493 			/*
4494 			 * map blk          |---------|
4495 			 * sack blk    |----|
4496 			 * <or>
4497 			 * map blk          |---------|
4498 			 * sack blk    |-------|
4499 			 */
4500 			return (1);
4501 		}
4502 	}
4503 	return (0);
4504 }
4505 
4506 static struct bbr_sendmap *
4507 bbr_merge_rsm(struct tcp_bbr *bbr,
4508 	      struct bbr_sendmap *l_rsm,
4509 	      struct bbr_sendmap *r_rsm)
4510 {
4511 	/*
4512 	 * We are merging two ack'd RSM's,
4513 	 * the l_rsm is on the left (lower seq
4514 	 * values) and the r_rsm is on the right
4515 	 * (higher seq value). The simplest way
4516 	 * to merge these is to move the right
4517 	 * one into the left. I don't think there
4518 	 * is any reason we need to try to find
4519 	 * the oldest (or last oldest retransmitted).
4520 	 */
4521 	l_rsm->r_end = r_rsm->r_end;
4522 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4523 		l_rsm->r_dupack = r_rsm->r_dupack;
4524 	if (r_rsm->r_rtr_bytes)
4525 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4526 	if (r_rsm->r_in_tmap) {
4527 		/* This really should not happen */
4528 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4529 	}
4530 	if (r_rsm->r_app_limited)
4531 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4532 	/* Now the flags */
4533 	if (r_rsm->r_flags & BBR_HAS_FIN)
4534 		l_rsm->r_flags |= BBR_HAS_FIN;
4535 	if (r_rsm->r_flags & BBR_TLP)
4536 		l_rsm->r_flags |= BBR_TLP;
4537 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4538 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4539 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4540 		/* This really should not happen */
4541 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4542 	}
4543 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4544 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4545 		/* Transfer the split limit to the map we free */
4546 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4547 		l_rsm->r_limit_type = 0;
4548 	}
4549 	bbr_free(bbr, r_rsm);
4550 	return(l_rsm);
4551 }
4552 
4553 /*
4554  * TLP Timer, here we simply setup what segment we want to
4555  * have the TLP expire on, the normal bbr_output_wtime() will then
4556  * send it out.
4557  *
4558  * We return 1, saying don't proceed with bbr_output_wtime only
4559  * when all timers have been stopped (destroyed PCB?).
4560  */
4561 static int
4562 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4563 {
4564 	/*
4565 	 * Tail Loss Probe.
4566 	 */
4567 	struct bbr_sendmap *rsm = NULL;
4568 	struct socket *so;
4569 	uint32_t amm;
4570 	uint32_t out, avail;
4571 	uint32_t maxseg;
4572 	int collapsed_win = 0;
4573 
4574 	if (bbr->rc_all_timers_stopped) {
4575 		return (1);
4576 	}
4577 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4578 		/* Its not time yet */
4579 		return (0);
4580 	}
4581 	if (ctf_progress_timeout_check(tp, true)) {
4582 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4583 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4584 		return (1);
4585 	}
4586 	/* Did we somehow get into persists? */
4587 	if (bbr->rc_in_persist) {
4588 		return (0);
4589 	}
4590 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4591 		bbr_set_state(tp, bbr, 0);
4592 	BBR_STAT_INC(bbr_tlp_tot);
4593 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4594 	/*
4595 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4596 	 * need to figure out how to force a full MSS segment out.
4597 	 */
4598 	so = tp->t_inpcb->inp_socket;
4599 	avail = sbavail(&so->so_snd);
4600 	out = ctf_outstanding(tp);
4601 	if (out > tp->snd_wnd) {
4602 		/* special case, we need a retransmission */
4603 		collapsed_win = 1;
4604 		goto need_retran;
4605 	}
4606 	if (avail > out) {
4607 		/* New data is available */
4608 		amm = avail - out;
4609 		if (amm > maxseg) {
4610 			amm = maxseg;
4611 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4612 			/* not enough to fill a MTU and no-delay is off */
4613 			goto need_retran;
4614 		}
4615 		/* Set the send-new override */
4616 		if ((out + amm) <= tp->snd_wnd) {
4617 			bbr->rc_tlp_new_data = 1;
4618 		} else {
4619 			goto need_retran;
4620 		}
4621 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4622 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4623 		bbr->r_ctl.rc_tlp_send = NULL;
4624 		/* cap any slots */
4625 		BBR_STAT_INC(bbr_tlp_newdata);
4626 		goto send;
4627 	}
4628 need_retran:
4629 	/*
4630 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4631 	 * optionally the first un-acked segment.
4632 	 */
4633 	if (collapsed_win == 0) {
4634 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4635 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4636 			rsm = bbr_find_high_nonack(bbr, rsm);
4637 		}
4638 		if (rsm == NULL) {
4639 			goto restore;
4640 		}
4641 	} else {
4642 		/*
4643 		 * We must find the last segment
4644 		 * that was acceptable by the client.
4645 		 */
4646 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4647 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4648 				/* Found one */
4649 				break;
4650 			}
4651 		}
4652 		if (rsm == NULL) {
4653 			/* None? if so send the first */
4654 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4655 			if (rsm == NULL)
4656 				goto restore;
4657 		}
4658 	}
4659 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4660 		/*
4661 		 * We need to split this the last segment in two.
4662 		 */
4663 		struct bbr_sendmap *nrsm;
4664 
4665 		nrsm = bbr_alloc_full_limit(bbr);
4666 		if (nrsm == NULL) {
4667 			/*
4668 			 * We can't get memory to split, we can either just
4669 			 * not split it. Or retransmit the whole piece, lets
4670 			 * do the large send (BTLP :-) ).
4671 			 */
4672 			goto go_for_it;
4673 		}
4674 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4675 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4676 		if (rsm->r_in_tmap) {
4677 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4678 			nrsm->r_in_tmap = 1;
4679 		}
4680 		rsm->r_flags &= (~BBR_HAS_FIN);
4681 		rsm = nrsm;
4682 	}
4683 go_for_it:
4684 	bbr->r_ctl.rc_tlp_send = rsm;
4685 	bbr->rc_tlp_rtx_out = 1;
4686 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4687 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4688 		tp->t_rxtshift++;
4689 	} else {
4690 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4691 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4692 	}
4693 send:
4694 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4695 		/*
4696 		 * Can't [re]/transmit a segment we have retranmitted the
4697 		 * max times. We need the retransmit timer to take over.
4698 		 */
4699 restore:
4700 		bbr->rc_tlp_new_data = 0;
4701 		bbr->r_ctl.rc_tlp_send = NULL;
4702 		if (rsm)
4703 			rsm->r_flags &= ~BBR_TLP;
4704 		BBR_STAT_INC(bbr_tlp_retran_fail);
4705 		return (0);
4706 	} else if (rsm) {
4707 		rsm->r_flags |= BBR_TLP;
4708 	}
4709 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4710 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4711 		/*
4712 		 * We have retransmitted to many times for TLP. Switch to
4713 		 * the regular RTO timer
4714 		 */
4715 		goto restore;
4716 	}
4717 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4718 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4719 	return (0);
4720 }
4721 
4722 /*
4723  * Delayed ack Timer, here we simply need to setup the
4724  * ACK_NOW flag and remove the DELACK flag. From there
4725  * the output routine will send the ack out.
4726  *
4727  * We only return 1, saying don't proceed, if all timers
4728  * are stopped (destroyed PCB?).
4729  */
4730 static int
4731 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4732 {
4733 	if (bbr->rc_all_timers_stopped) {
4734 		return (1);
4735 	}
4736 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4737 	tp->t_flags &= ~TF_DELACK;
4738 	tp->t_flags |= TF_ACKNOW;
4739 	KMOD_TCPSTAT_INC(tcps_delack);
4740 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4741 	return (0);
4742 }
4743 
4744 /*
4745  * Here we send a KEEP-ALIVE like probe to the
4746  * peer, we do not send data.
4747  *
4748  * We only return 1, saying don't proceed, if all timers
4749  * are stopped (destroyed PCB?).
4750  */
4751 static int
4752 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4753 {
4754 	struct tcptemp *t_template;
4755 	int32_t retval = 1;
4756 
4757 	if (bbr->rc_all_timers_stopped) {
4758 		return (1);
4759 	}
4760 	if (bbr->rc_in_persist == 0)
4761 		return (0);
4762 	KASSERT(tp->t_inpcb != NULL,
4763 	    ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
4764 	/*
4765 	 * Persistence timer into zero window. Force a byte to be output, if
4766 	 * possible.
4767 	 */
4768 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4769 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4770 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4771 	/*
4772 	 * Have we exceeded the user specified progress time?
4773 	 */
4774 	if (ctf_progress_timeout_check(tp, true)) {
4775 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4776 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4777 		goto out;
4778 	}
4779 	/*
4780 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4781 	 * window is closed.  After a full backoff, drop the connection if
4782 	 * the idle time (no responses to probes) reaches the maximum
4783 	 * backoff that we would use if retransmitting.
4784 	 */
4785 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4786 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4787 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4788 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4789 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4790 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4791 		goto out;
4792 	}
4793 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4794 	    tp->snd_una == tp->snd_max) {
4795 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4796 		retval = 0;
4797 		goto out;
4798 	}
4799 	/*
4800 	 * If the user has closed the socket then drop a persisting
4801 	 * connection after a much reduced timeout.
4802 	 */
4803 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4804 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4805 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4806 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4807 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4808 		goto out;
4809 	}
4810 	t_template = tcpip_maketemplate(bbr->rc_inp);
4811 	if (t_template) {
4812 		tcp_respond(tp, t_template->tt_ipgen,
4813 			    &t_template->tt_t, (struct mbuf *)NULL,
4814 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4815 		/* This sends an ack */
4816 		if (tp->t_flags & TF_DELACK)
4817 			tp->t_flags &= ~TF_DELACK;
4818 		free(t_template, M_TEMP);
4819 	}
4820 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4821 		tp->t_rxtshift++;
4822 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4823 out:
4824 	return (retval);
4825 }
4826 
4827 /*
4828  * If a keepalive goes off, we had no other timers
4829  * happening. We always return 1 here since this
4830  * routine either drops the connection or sends
4831  * out a segment with respond.
4832  */
4833 static int
4834 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4835 {
4836 	struct tcptemp *t_template;
4837 	struct inpcb *inp;
4838 
4839 	if (bbr->rc_all_timers_stopped) {
4840 		return (1);
4841 	}
4842 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4843 	inp = tp->t_inpcb;
4844 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4845 	/*
4846 	 * Keep-alive timer went off; send something or drop connection if
4847 	 * idle for too long.
4848 	 */
4849 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4850 	if (tp->t_state < TCPS_ESTABLISHED)
4851 		goto dropit;
4852 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4853 	    tp->t_state <= TCPS_CLOSING) {
4854 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4855 			goto dropit;
4856 		/*
4857 		 * Send a packet designed to force a response if the peer is
4858 		 * up and reachable: either an ACK if the connection is
4859 		 * still alive, or an RST if the peer has closed the
4860 		 * connection due to timeout or reboot. Using sequence
4861 		 * number tp->snd_una-1 causes the transmitted zero-length
4862 		 * segment to lie outside the receive window; by the
4863 		 * protocol spec, this requires the correspondent TCP to
4864 		 * respond.
4865 		 */
4866 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4867 		t_template = tcpip_maketemplate(inp);
4868 		if (t_template) {
4869 			tcp_respond(tp, t_template->tt_ipgen,
4870 			    &t_template->tt_t, (struct mbuf *)NULL,
4871 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4872 			free(t_template, M_TEMP);
4873 		}
4874 	}
4875 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4876 	return (1);
4877 dropit:
4878 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4879 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4880 	tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
4881 	return (1);
4882 }
4883 
4884 /*
4885  * Retransmit helper function, clear up all the ack
4886  * flags and take care of important book keeping.
4887  */
4888 static void
4889 bbr_remxt_tmr(struct tcpcb *tp)
4890 {
4891 	/*
4892 	 * The retransmit timer went off, all sack'd blocks must be
4893 	 * un-acked.
4894 	 */
4895 	struct bbr_sendmap *rsm, *trsm = NULL;
4896 	struct tcp_bbr *bbr;
4897 	uint32_t cts, lost;
4898 
4899 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4900 	cts = tcp_get_usecs(&bbr->rc_tv);
4901 	lost = bbr->r_ctl.rc_lost;
4902 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4903 		bbr_set_state(tp, bbr, 0);
4904 
4905 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4906 		if (rsm->r_flags & BBR_ACKED) {
4907 			uint32_t old_flags;
4908 
4909 			rsm->r_dupack = 0;
4910 			if (rsm->r_in_tmap == 0) {
4911 				/* We must re-add it back to the tlist */
4912 				if (trsm == NULL) {
4913 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4914 				} else {
4915 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4916 				}
4917 				rsm->r_in_tmap = 1;
4918 			}
4919 			old_flags = rsm->r_flags;
4920 			rsm->r_flags |= BBR_RXT_CLEARED;
4921 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4922 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4923 		} else {
4924 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4925 			    (rsm->r_start == tp->snd_una)) {
4926 				/*
4927 				 * Special case for TCP FO. Where
4928 				 * we sent more data beyond the snd_max.
4929 				 * We don't mark that as lost and stop here.
4930 				 */
4931 				break;
4932 			}
4933 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4934 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4935 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4936 			}
4937 			if (bbr_marks_rxt_sack_passed) {
4938 				/*
4939 				 * With this option, we will rack out
4940 				 * in 1ms increments the rest of the packets.
4941 				 */
4942 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4943 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4944 			} else {
4945 				/*
4946 				 * With this option we only mark them lost
4947 				 * and remove all sack'd markings. We will run
4948 				 * another RXT or a TLP. This will cause
4949 				 * us to eventually send more based on what
4950 				 * ack's come in.
4951 				 */
4952 				rsm->r_flags |= BBR_MARKED_LOST;
4953 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4954 				rsm->r_flags &= ~BBR_SACK_PASSED;
4955 			}
4956 		}
4957 		trsm = rsm;
4958 	}
4959 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4960 	/* Clear the count (we just un-acked them) */
4961 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4962 	bbr->rc_tlp_new_data = 0;
4963 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4964 	/* zap the behindness on a rxt */
4965 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4966 	bbr->r_agg_early_set = 0;
4967 	bbr->r_ctl.rc_agg_early = 0;
4968 	bbr->rc_tlp_rtx_out = 0;
4969 	bbr->r_ctl.rc_sacked = 0;
4970 	bbr->r_ctl.rc_sacklast = NULL;
4971 	bbr->r_timer_override = 1;
4972 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4973 }
4974 
4975 /*
4976  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4977  * we will setup to retransmit the lowest seq number outstanding.
4978  */
4979 static int
4980 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4981 {
4982 	int32_t rexmt;
4983 	int32_t retval = 0;
4984 	bool isipv6;
4985 
4986 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4987 	if (bbr->rc_all_timers_stopped) {
4988 		return (1);
4989 	}
4990 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4991 	    (tp->snd_una == tp->snd_max)) {
4992 		/* Nothing outstanding .. nothing to do */
4993 		return (0);
4994 	}
4995 	/*
4996 	 * Retransmission timer went off.  Message has not been acked within
4997 	 * retransmit interval.  Back off to a longer retransmit interval
4998 	 * and retransmit one segment.
4999 	 */
5000 	if (ctf_progress_timeout_check(tp, true)) {
5001 		retval = 1;
5002 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
5003 		tcp_set_inp_to_drop(bbr->rc_inp, ETIMEDOUT);
5004 		goto out;
5005 	}
5006 	bbr_remxt_tmr(tp);
5007 	if ((bbr->r_ctl.rc_resend == NULL) ||
5008 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
5009 		/*
5010 		 * If the rwnd collapsed on
5011 		 * the one we are retransmitting
5012 		 * it does not count against the
5013 		 * rxt count.
5014 		 */
5015 		tp->t_rxtshift++;
5016 	}
5017 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5018 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
5019 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
5020 		retval = 1;
5021 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
5022 		tcp_set_inp_to_drop(bbr->rc_inp,
5023 		    (tp->t_softerror ? (uint16_t) tp->t_softerror : ETIMEDOUT));
5024 		goto out;
5025 	}
5026 	if (tp->t_state == TCPS_SYN_SENT) {
5027 		/*
5028 		 * If the SYN was retransmitted, indicate CWND to be limited
5029 		 * to 1 segment in cc_conn_init().
5030 		 */
5031 		tp->snd_cwnd = 1;
5032 	} else if (tp->t_rxtshift == 1) {
5033 		/*
5034 		 * first retransmit; record ssthresh and cwnd so they can be
5035 		 * recovered if this turns out to be a "bad" retransmit. A
5036 		 * retransmit is considered "bad" if an ACK for this segment
5037 		 * is received within RTT/2 interval; the assumption here is
5038 		 * that the ACK was already in flight.  See "On Estimating
5039 		 * End-to-End Network Path Properties" by Allman and Paxson
5040 		 * for more details.
5041 		 */
5042 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5043 		if (!IN_RECOVERY(tp->t_flags)) {
5044 			tp->snd_cwnd_prev = tp->snd_cwnd;
5045 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5046 			tp->snd_recover_prev = tp->snd_recover;
5047 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5048 			tp->t_flags |= TF_PREVVALID;
5049 		} else {
5050 			tp->t_flags &= ~TF_PREVVALID;
5051 		}
5052 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5053 	} else {
5054 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5055 		tp->t_flags &= ~TF_PREVVALID;
5056 	}
5057 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5058 	if ((tp->t_state == TCPS_SYN_SENT) ||
5059 	    (tp->t_state == TCPS_SYN_RECEIVED))
5060 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5061 	else
5062 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5063 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5064 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5065 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5066 	/*
5067 	 * We enter the path for PLMTUD if connection is established or, if
5068 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5069 	 * amount of data we send is very small, we could send it in couple
5070 	 * of packets and process straight to FIN. In that case we won't
5071 	 * catch ESTABLISHED state.
5072 	 */
5073 #ifdef INET6
5074 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) ? true : false;
5075 #else
5076 	isipv6 = false;
5077 #endif
5078 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5079 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5080 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5081 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5082 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5083 		/*
5084 		 * Idea here is that at each stage of mtu probe (usually,
5085 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5086 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5087 		 * should take care of that.
5088 		 */
5089 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5090 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5091 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5092 		    tp->t_rxtshift % 2 == 0)) {
5093 			/*
5094 			 * Enter Path MTU Black-hole Detection mechanism: -
5095 			 * Disable Path MTU Discovery (IP "DF" bit). -
5096 			 * Reduce MTU to lower value than what we negotiated
5097 			 * with peer.
5098 			 */
5099 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5100 				/*
5101 				 * Record that we may have found a black
5102 				 * hole.
5103 				 */
5104 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5105 				/* Keep track of previous MSS. */
5106 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5107 			}
5108 			/*
5109 			 * Reduce the MSS to blackhole value or to the
5110 			 * default in an attempt to retransmit.
5111 			 */
5112 #ifdef INET6
5113 			isipv6 = bbr->r_is_v6;
5114 			if (isipv6 &&
5115 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5116 				/* Use the sysctl tuneable blackhole MSS. */
5117 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5118 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5119 			} else if (isipv6) {
5120 				/* Use the default MSS. */
5121 				tp->t_maxseg = V_tcp_v6mssdflt;
5122 				/*
5123 				 * Disable Path MTU Discovery when we switch
5124 				 * to minmss.
5125 				 */
5126 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5127 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5128 			}
5129 #endif
5130 #if defined(INET6) && defined(INET)
5131 			else
5132 #endif
5133 #ifdef INET
5134 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5135 				/* Use the sysctl tuneable blackhole MSS. */
5136 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5137 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5138 			} else {
5139 				/* Use the default MSS. */
5140 				tp->t_maxseg = V_tcp_mssdflt;
5141 				/*
5142 				 * Disable Path MTU Discovery when we switch
5143 				 * to minmss.
5144 				 */
5145 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5146 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5147 			}
5148 #endif
5149 		} else {
5150 			/*
5151 			 * If further retransmissions are still unsuccessful
5152 			 * with a lowered MTU, maybe this isn't a blackhole
5153 			 * and we restore the previous MSS and blackhole
5154 			 * detection flags. The limit '6' is determined by
5155 			 * giving each probe stage (1448, 1188, 524) 2
5156 			 * chances to recover.
5157 			 */
5158 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5159 			    (tp->t_rxtshift >= 6)) {
5160 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5161 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5162 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5163 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5164 			}
5165 		}
5166 	}
5167 	/*
5168 	 * Disable RFC1323 and SACK if we haven't got any response to our
5169 	 * third SYN to work-around some broken terminal servers (most of
5170 	 * which have hopefully been retired) that have bad VJ header
5171 	 * compression code which trashes TCP segments containing
5172 	 * unknown-to-them TCP options.
5173 	 */
5174 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5175 	    (tp->t_rxtshift == 3))
5176 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5177 	/*
5178 	 * If we backed off this far, our srtt estimate is probably bogus.
5179 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5180 	 * move the current srtt into rttvar to keep the current retransmit
5181 	 * times until then.
5182 	 */
5183 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5184 #ifdef INET6
5185 		if (bbr->r_is_v6)
5186 			in6_losing(tp->t_inpcb);
5187 		else
5188 #endif
5189 			in_losing(tp->t_inpcb);
5190 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5191 		tp->t_srtt = 0;
5192 	}
5193 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5194 	tp->snd_recover = tp->snd_max;
5195 	tp->t_flags |= TF_ACKNOW;
5196 	tp->t_rtttime = 0;
5197 out:
5198 	return (retval);
5199 }
5200 
5201 static int
5202 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5203 {
5204 	int32_t ret = 0;
5205 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5206 
5207 	if (timers == 0) {
5208 		return (0);
5209 	}
5210 	if (tp->t_state == TCPS_LISTEN) {
5211 		/* no timers on listen sockets */
5212 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5213 			return (0);
5214 		return (1);
5215 	}
5216 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5217 		uint32_t left;
5218 
5219 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5220 			ret = -1;
5221 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5222 			return (0);
5223 		}
5224 		if (hpts_calling == 0) {
5225 			ret = -2;
5226 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5227 			return (0);
5228 		}
5229 		/*
5230 		 * Ok our timer went off early and we are not paced false
5231 		 * alarm, go back to sleep.
5232 		 */
5233 		left = bbr->r_ctl.rc_timer_exp - cts;
5234 		ret = -3;
5235 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5236 		tcp_hpts_insert(tp->t_inpcb, HPTS_USEC_TO_SLOTS(left));
5237 		return (1);
5238 	}
5239 	bbr->rc_tmr_stopped = 0;
5240 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5241 	if (timers & PACE_TMR_DELACK) {
5242 		ret = bbr_timeout_delack(tp, bbr, cts);
5243 	} else if (timers & PACE_TMR_PERSIT) {
5244 		ret = bbr_timeout_persist(tp, bbr, cts);
5245 	} else if (timers & PACE_TMR_RACK) {
5246 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5247 		ret = bbr_timeout_rack(tp, bbr, cts);
5248 	} else if (timers & PACE_TMR_TLP) {
5249 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5250 		ret = bbr_timeout_tlp(tp, bbr, cts);
5251 	} else if (timers & PACE_TMR_RXT) {
5252 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5253 		ret = bbr_timeout_rxt(tp, bbr, cts);
5254 	} else if (timers & PACE_TMR_KEEP) {
5255 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5256 	}
5257 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5258 	return (ret);
5259 }
5260 
5261 static void
5262 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5263 {
5264 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5265 		uint8_t hpts_removed = 0;
5266 
5267 		if (bbr->rc_inp->inp_in_hpts &&
5268 		    (bbr->rc_timer_first == 1)) {
5269 			/*
5270 			 * If we are canceling timer's when we have the
5271 			 * timer ahead of the output being paced. We also
5272 			 * must remove ourselves from the hpts.
5273 			 */
5274 			hpts_removed = 1;
5275 			tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
5276 			if (bbr->r_ctl.rc_last_delay_val) {
5277 				/* Update the last hptsi delay too */
5278 				uint32_t time_since_send;
5279 
5280 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5281 					time_since_send = cts - bbr->rc_pacer_started;
5282 				else
5283 					time_since_send = 0;
5284 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5285 					/* Cut down our slot time */
5286 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5287 				} else {
5288 					bbr->r_ctl.rc_last_delay_val = 0;
5289 				}
5290 				bbr->rc_pacer_started = cts;
5291 			}
5292 		}
5293 		bbr->rc_timer_first = 0;
5294 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5295 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5296 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5297 	}
5298 }
5299 
5300 static void
5301 bbr_timer_stop(struct tcpcb *tp, uint32_t timer_type)
5302 {
5303 	struct tcp_bbr *bbr;
5304 
5305 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5306 	bbr->rc_all_timers_stopped = 1;
5307 	return;
5308 }
5309 
5310 /*
5311  * stop all timers always returning 0.
5312  */
5313 static int
5314 bbr_stopall(struct tcpcb *tp)
5315 {
5316 	return (0);
5317 }
5318 
5319 static void
5320 bbr_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
5321 {
5322 	return;
5323 }
5324 
5325 /*
5326  * return true if a bbr timer (rack or tlp) is active.
5327  */
5328 static int
5329 bbr_timer_active(struct tcpcb *tp, uint32_t timer_type)
5330 {
5331 	return (0);
5332 }
5333 
5334 static uint32_t
5335 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5336 {
5337 	struct bbr_sendmap *rsm;
5338 
5339 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5340 	if ((rsm == NULL) || (u_rsm == rsm))
5341 		return (cts);
5342 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5343 }
5344 
5345 static void
5346 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5347      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5348 {
5349 	int32_t idx;
5350 
5351 	rsm->r_rtr_cnt++;
5352 	rsm->r_dupack = 0;
5353 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5354 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5355 		rsm->r_flags |= BBR_OVERMAX;
5356 	}
5357 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5358 		/* Take off the collapsed flag at rxt */
5359 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5360 	}
5361 	if (rsm->r_flags & BBR_MARKED_LOST) {
5362 		/* We have retransmitted, its no longer lost */
5363 		rsm->r_flags &= ~BBR_MARKED_LOST;
5364 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5365 	}
5366 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5367 		/*
5368 		 * We hit a RXT timer on it and
5369 		 * we cleared the "acked" flag.
5370 		 * We now have it going back into
5371 		 * flight, we can remove the cleared
5372 		 * flag and possibly do accounting on
5373 		 * this piece.
5374 		 */
5375 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5376 	}
5377 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5378 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5379 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5380 	}
5381 	idx = rsm->r_rtr_cnt - 1;
5382 	rsm->r_tim_lastsent[idx] = cts;
5383 	rsm->r_pacing_delay = pacing_time;
5384 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5385 	rsm->r_ts_valid = bbr->rc_ts_valid;
5386 	if (bbr->rc_ts_valid)
5387 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5388 	if (bbr->r_ctl.r_app_limited_until)
5389 		rsm->r_app_limited = 1;
5390 	else
5391 		rsm->r_app_limited = 0;
5392 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5393 		rsm->r_bbr_state = bbr_state_val(bbr);
5394 	else
5395 		rsm->r_bbr_state = 8;
5396 	if (rsm->r_flags & BBR_ACKED) {
5397 		/* Problably MTU discovery messing with us */
5398 		uint32_t old_flags;
5399 
5400 		old_flags = rsm->r_flags;
5401 		rsm->r_flags &= ~BBR_ACKED;
5402 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5403 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5404 		if (bbr->r_ctl.rc_sacked == 0)
5405 			bbr->r_ctl.rc_sacklast = NULL;
5406 	}
5407 	if (rsm->r_in_tmap) {
5408 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5409 	}
5410 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5411 	rsm->r_in_tmap = 1;
5412 	if (rsm->r_flags & BBR_SACK_PASSED) {
5413 		/* We have retransmitted due to the SACK pass */
5414 		rsm->r_flags &= ~BBR_SACK_PASSED;
5415 		rsm->r_flags |= BBR_WAS_SACKPASS;
5416 	}
5417 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5418 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5419 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5420 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5421 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5422 		rsm->r_is_gain = 1;
5423 		rsm->r_is_drain = 0;
5424 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5425 		rsm->r_is_drain = 1;
5426 		rsm->r_is_gain = 0;
5427 	} else {
5428 		rsm->r_is_drain = 0;
5429 		rsm->r_is_gain = 0;
5430 	}
5431 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5432 }
5433 
5434 /*
5435  * Returns 0, or the sequence where we stopped
5436  * updating. We also update the lenp to be the amount
5437  * of data left.
5438  */
5439 
5440 static uint32_t
5441 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5442     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5443 {
5444 	/*
5445 	 * We (re-)transmitted starting at rsm->r_start for some length
5446 	 * (possibly less than r_end.
5447 	 */
5448 	struct bbr_sendmap *nrsm;
5449 	uint32_t c_end;
5450 	int32_t len;
5451 
5452 	len = *lenp;
5453 	c_end = rsm->r_start + len;
5454 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5455 		/*
5456 		 * We retransmitted the whole piece or more than the whole
5457 		 * slopping into the next rsm.
5458 		 */
5459 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5460 		if (c_end == rsm->r_end) {
5461 			*lenp = 0;
5462 			return (0);
5463 		} else {
5464 			int32_t act_len;
5465 
5466 			/* Hangs over the end return whats left */
5467 			act_len = rsm->r_end - rsm->r_start;
5468 			*lenp = (len - act_len);
5469 			return (rsm->r_end);
5470 		}
5471 		/* We don't get out of this block. */
5472 	}
5473 	/*
5474 	 * Here we retransmitted less than the whole thing which means we
5475 	 * have to split this into what was transmitted and what was not.
5476 	 */
5477 	nrsm = bbr_alloc_full_limit(bbr);
5478 	if (nrsm == NULL) {
5479 		*lenp = 0;
5480 		return (0);
5481 	}
5482 	/*
5483 	 * So here we are going to take the original rsm and make it what we
5484 	 * retransmitted. nrsm will be the tail portion we did not
5485 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5486 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5487 	 * 1, 6 and the new piece will be 6, 11.
5488 	 */
5489 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5490 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5491 	nrsm->r_dupack = 0;
5492 	if (rsm->r_in_tmap) {
5493 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5494 		nrsm->r_in_tmap = 1;
5495 	}
5496 	rsm->r_flags &= (~BBR_HAS_FIN);
5497 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5498 	*lenp = 0;
5499 	return (0);
5500 }
5501 
5502 static uint64_t
5503 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5504 {
5505 	uint64_t bw;
5506 
5507 	bw = bbr_get_bw(bbr);
5508 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5509 	bw /= (uint64_t)BBR_UNIT;
5510 	return(bw);
5511 }
5512 
5513 static void
5514 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5515 		       uint64_t act_rate, uint64_t rate_wanted)
5516 {
5517 	/*
5518 	 * We could not get a full gains worth
5519 	 * of rate.
5520 	 */
5521 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5522 		/* we can't even get the real rate */
5523 		uint64_t red;
5524 
5525 		bbr->skip_gain = 1;
5526 		bbr->gain_is_limited = 0;
5527 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5528 		if (red)
5529 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5530 	} else {
5531 		/* We can use a lower gain */
5532 		bbr->skip_gain = 0;
5533 		bbr->gain_is_limited = 1;
5534 	}
5535 }
5536 
5537 static void
5538 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5539 {
5540 	const struct tcp_hwrate_limit_table *nrte;
5541 	int error, rate = -1;
5542 
5543 	if (bbr->r_ctl.crte == NULL)
5544 		return;
5545 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5546 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5547 		/* Lost our routes? */
5548 		/* Clear the way for a re-attempt */
5549 		bbr->bbr_attempt_hdwr_pace = 0;
5550 lost_rate:
5551 		bbr->gain_is_limited = 0;
5552 		bbr->skip_gain = 0;
5553 		bbr->bbr_hdrw_pacing = 0;
5554 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5555 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5556 		tcp_bbr_tso_size_check(bbr, cts);
5557 		return;
5558 	}
5559 	rate = bbr_get_hardware_rate(bbr);
5560 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5561 				   bbr->rc_tp,
5562 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5563 				   rate,
5564 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5565 				   &error, NULL);
5566 	if (nrte == NULL) {
5567 		goto lost_rate;
5568 	}
5569 	if (nrte != bbr->r_ctl.crte) {
5570 		bbr->r_ctl.crte = nrte;
5571 		if (error == 0)  {
5572 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5573 			if (bbr->r_ctl.crte->rate < rate) {
5574 				/* We have a problem */
5575 				bbr_setup_less_of_rate(bbr, cts,
5576 						       bbr->r_ctl.crte->rate, rate);
5577 			} else {
5578 				/* We are good */
5579 				bbr->gain_is_limited = 0;
5580 				bbr->skip_gain = 0;
5581 			}
5582 		} else {
5583 			/* A failure should release the tag */
5584 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5585 			bbr->gain_is_limited = 0;
5586 			bbr->skip_gain = 0;
5587 			bbr->bbr_hdrw_pacing = 0;
5588 		}
5589 		bbr_type_log_hdwr_pacing(bbr,
5590 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5591 					 rate,
5592 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5593 					 __LINE__,
5594 					 cts,
5595 					 error);
5596 	}
5597 }
5598 
5599 static void
5600 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5601 {
5602 	/*
5603 	 * If we have hardware pacing support
5604 	 * we need to factor that in for our
5605 	 * TSO size.
5606 	 */
5607 	const struct tcp_hwrate_limit_table *rlp;
5608 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5609 
5610 	if ((bbr->bbr_hdrw_pacing == 0) ||
5611 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5612 	    (bbr->r_ctl.crte == NULL))
5613 		return;
5614 	if (bbr->hw_pacing_set == 0) {
5615 		/* Not yet by the hdwr pacing count delay */
5616 		return;
5617 	}
5618 	if (bbr_hdwr_pace_adjust == 0) {
5619 		/* No adjustment */
5620 		return;
5621 	}
5622 	rlp = bbr->r_ctl.crte;
5623 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5624 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5625 	else
5626 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5627 	/*
5628 	 * So lets first get the
5629 	 * time we will take between
5630 	 * TSO sized sends currently without
5631 	 * hardware help.
5632 	 */
5633 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5634 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5635 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5636 	hdwr_delay *= rlp->time_between;
5637 	if (cur_delay > hdwr_delay)
5638 		delta = cur_delay - hdwr_delay;
5639 	else
5640 		delta = 0;
5641 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5642 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5643 			     1);
5644 	if (delta &&
5645 	    (delta < (max(rlp->time_between,
5646 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5647 		/*
5648 		 * Now lets divide by the pacing
5649 		 * time between each segment the
5650 		 * hardware sends rounding up and
5651 		 * derive a bytes from that. We multiply
5652 		 * that by bbr_hdwr_pace_adjust to get
5653 		 * more bang for our buck.
5654 		 *
5655 		 * The goal is to have the software pacer
5656 		 * waiting no more than an additional
5657 		 * pacing delay if we can (without the
5658 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5659 		 */
5660 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5661 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5662 		seg_sz *= bbr_hdwr_pace_adjust;
5663 		if (bbr_hdwr_pace_floor &&
5664 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5665 			/* Currently hardware paces
5666 			 * out rs_min_seg segments at a time.
5667 			 * We need to make sure we always send at least
5668 			 * a full burst of bbr_hdwr_pace_floor down.
5669 			 */
5670 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5671 		}
5672 		seg_sz *= maxseg;
5673 	} else if (delta == 0) {
5674 		/*
5675 		 * The highest pacing rate is
5676 		 * above our b/w gained. This means
5677 		 * we probably are going quite fast at
5678 		 * the hardware highest rate. Lets just multiply
5679 		 * the calculated TSO size by the
5680 		 * multiplier factor (its probably
5681 		 * 4 segments in the default config for
5682 		 * mlx).
5683 		 */
5684 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5685 		if (bbr_hdwr_pace_floor &&
5686 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5687 			/* Currently hardware paces
5688 			 * out rs_min_seg segments at a time.
5689 			 * We need to make sure we always send at least
5690 			 * a full burst of bbr_hdwr_pace_floor down.
5691 			 */
5692 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5693 		}
5694 	} else {
5695 		/*
5696 		 * The pacing time difference is so
5697 		 * big that the hardware will
5698 		 * pace out more rapidly then we
5699 		 * really want and then we
5700 		 * will have a long delay. Lets just keep
5701 		 * the same TSO size so its as if
5702 		 * we were not using hdwr pacing (we
5703 		 * just gain a bit of spacing from the
5704 		 * hardware if seg_sz > 1).
5705 		 */
5706 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5707 	}
5708 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5709 		new_tso = seg_sz;
5710 	else
5711 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5712 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5713 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5714 
5715 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5716 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5717 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5718 	}
5719 }
5720 
5721 static void
5722 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5723 {
5724 	uint64_t bw;
5725 	uint32_t old_tso = 0, new_tso;
5726 	uint32_t maxseg, bytes;
5727 	uint32_t tls_seg=0;
5728 	/*
5729 	 * Google/linux uses the following algorithm to determine
5730 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5731 	 *
5732 	 *  bytes = bw_in_bytes_per_second / 1000
5733 	 *  bytes = min(bytes, 64k)
5734 	 *  tso_segs = bytes / MSS
5735 	 *  if (bw < 1.2Mbs)
5736 	 *      min_tso_segs = 1
5737 	 *  else
5738 	 *	min_tso_segs = 2
5739 	 * tso_segs = max(tso_segs, min_tso_segs)
5740 	 *
5741 	 * * Note apply a device specific limit (we apply this in the
5742 	 *   tcp_m_copym).
5743 	 * Note that before the initial measurement is made google bursts out
5744 	 * a full iwnd just like new-reno/cubic.
5745 	 *
5746 	 * We do not use this algorithm. Instead we
5747 	 * use a two phased approach:
5748 	 *
5749 	 *  if ( bw <= per-tcb-cross-over)
5750 	 *     goal_tso =  calculate how much with this bw we
5751 	 *                 can send in goal-time seconds.
5752 	 *     if (goal_tso > mss)
5753 	 *         seg = goal_tso / mss
5754 	 *         tso = seg * mss
5755 	 *     else
5756 	 *         tso = mss
5757 	 *     if (tso > per-tcb-max)
5758 	 *         tso = per-tcb-max
5759 	 *  else if ( bw > 512Mbps)
5760 	 *     tso = max-tso (64k/mss)
5761 	 *  else
5762 	 *     goal_tso = bw / per-tcb-divsor
5763 	 *     seg = (goal_tso + mss-1)/mss
5764 	 *     tso = seg * mss
5765 	 *
5766 	 * if (tso < per-tcb-floor)
5767 	 *    tso = per-tcb-floor
5768 	 * if (tso > per-tcb-utter_max)
5769 	 *    tso = per-tcb-utter_max
5770 	 *
5771 	 * Note the default per-tcb-divisor is 1000 (same as google).
5772 	 * the goal cross over is 30Mbps however. To recreate googles
5773 	 * algorithm you need to set:
5774 	 *
5775 	 * cross-over = 23,168,000 bps
5776 	 * goal-time = 18000
5777 	 * per-tcb-max = 2
5778 	 * per-tcb-divisor = 1000
5779 	 * per-tcb-floor = 1
5780 	 *
5781 	 * This will get you "google bbr" behavior with respect to tso size.
5782 	 *
5783 	 * Note we do set anything TSO size until we are past the initial
5784 	 * window. Before that we gnerally use either a single MSS
5785 	 * or we use the full IW size (so we burst a IW at a time)
5786 	 */
5787 
5788 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5789 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5790 	} else {
5791 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5792 	}
5793 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5794 	if (bbr->rc_past_init_win == 0) {
5795 		/*
5796 		 * Not enough data has been acknowledged to make a
5797 		 * judgement. Set up the initial TSO based on if we
5798 		 * are sending a full IW at once or not.
5799 		 */
5800 		if (bbr->rc_use_google)
5801 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5802 		else if (bbr->bbr_init_win_cheat)
5803 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5804 		else
5805 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5806 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5807 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5808 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5809 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5810 		}
5811 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5812 			bbr_adjust_for_hw_pacing(bbr, cts);
5813 		return;
5814 	}
5815 	/**
5816 	 * Now lets set the TSO goal based on our delivery rate in
5817 	 * bytes per second. Note we only do this if
5818 	 * we have acked at least the initial cwnd worth of data.
5819 	 */
5820 	bw = bbr_get_bw(bbr);
5821 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5822 	     (bbr->rc_use_google == 0)) {
5823 		/* We clamp to one MSS in recovery */
5824 		new_tso = maxseg;
5825 	} else if (bbr->rc_use_google) {
5826 		int min_tso_segs;
5827 
5828 		/* Google considers the gain too */
5829 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5830 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5831 			bw /= BBR_UNIT;
5832 		}
5833 		bytes = bw / 1024;
5834 		if (bytes > (64 * 1024))
5835 			bytes = 64 * 1024;
5836 		new_tso = bytes / maxseg;
5837 		if (bw < ONE_POINT_TWO_MEG)
5838 			min_tso_segs = 1;
5839 		else
5840 			min_tso_segs = 2;
5841 		if (new_tso < min_tso_segs)
5842 			new_tso = min_tso_segs;
5843 		new_tso *= maxseg;
5844 	} else if (bbr->rc_no_pacing) {
5845 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5846 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5847 		/*
5848 		 * Calculate the worse case b/w TSO if we are inserting no
5849 		 * more than a delay_target number of TSO's.
5850 		 */
5851 		uint32_t tso_len, min_tso;
5852 
5853 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5854 		if (tso_len > maxseg) {
5855 			new_tso = tso_len / maxseg;
5856 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5857 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5858 			new_tso *= maxseg;
5859 		} else {
5860 			/*
5861 			 * less than a full sized frame yikes.. long rtt or
5862 			 * low bw?
5863 			 */
5864 			min_tso = bbr_minseg(bbr);
5865 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5866 				new_tso = rounddown(tso_len, min_tso);
5867 			else
5868 				new_tso = min_tso;
5869 		}
5870 	} else if (bw > FIVETWELVE_MBPS) {
5871 		/*
5872 		 * This guy is so fast b/w wise that we can TSO as large as
5873 		 * possible of segments that the NIC will allow.
5874 		 */
5875 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5876 	} else {
5877 		/*
5878 		 * This formula is based on attempting to send a segment or
5879 		 * more every bbr_hptsi_per_second. The default is 1000
5880 		 * which means you are targeting what you can send every 1ms
5881 		 * based on the peers bw.
5882 		 *
5883 		 * If the number drops to say 500, then you are looking more
5884 		 * at 2ms and you will raise how much we send in a single
5885 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5886 		 * trade off of course is you will send more at once and
5887 		 * thus tend to clump up the sends into larger "bursts"
5888 		 * building a queue.
5889 		 */
5890 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5891 		new_tso = roundup(bw, (uint64_t)maxseg);
5892 		/*
5893 		 * Gate the floor to match what our lower than 48Mbps
5894 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5895 		 * becomes the floor for this calculation.
5896 		 */
5897 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5898 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5899 	}
5900 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5901 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5902 	if (new_tso > PACE_MAX_IP_BYTES)
5903 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5904 	/* Enforce an utter maximum. */
5905 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5906 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5907 	}
5908 	if (old_tso != new_tso) {
5909 		/* Only log changes */
5910 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5911 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5912 	}
5913 	/* We have hardware pacing! */
5914 	bbr_adjust_for_hw_pacing(bbr, cts);
5915 }
5916 
5917 static void
5918 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5919     uint32_t seq_out, uint8_t th_flags, int32_t err, uint32_t cts,
5920     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5921     struct sockbuf *sb)
5922 {
5923 
5924 	struct bbr_sendmap *rsm, *nrsm;
5925 	register uint32_t snd_max, snd_una;
5926 	uint32_t pacing_time;
5927 	/*
5928 	 * Add to the RACK log of packets in flight or retransmitted. If
5929 	 * there is a TS option we will use the TS echoed, if not we will
5930 	 * grab a TS.
5931 	 *
5932 	 * Retransmissions will increment the count and move the ts to its
5933 	 * proper place. Note that if options do not include TS's then we
5934 	 * won't be able to effectively use the ACK for an RTT on a retran.
5935 	 *
5936 	 * Notes about r_start and r_end. Lets consider a send starting at
5937 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5938 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5939 	 * This means that r_end is actually the first sequence for the next
5940 	 * slot (11).
5941 	 *
5942 	 */
5943 	INP_WLOCK_ASSERT(tp->t_inpcb);
5944 	if (err) {
5945 		/*
5946 		 * We don't log errors -- we could but snd_max does not
5947 		 * advance in this case either.
5948 		 */
5949 		return;
5950 	}
5951 	if (th_flags & TH_RST) {
5952 		/*
5953 		 * We don't log resets and we return immediately from
5954 		 * sending
5955 		 */
5956 		*abandon = 1;
5957 		return;
5958 	}
5959 	snd_una = tp->snd_una;
5960 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5961 		/*
5962 		 * The call to bbr_log_output is made before bumping
5963 		 * snd_max. This means we can record one extra byte on a SYN
5964 		 * or FIN if seq_out is adding more on and a FIN is present
5965 		 * (and we are not resending).
5966 		 */
5967 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5968 			len++;
5969 		if (th_flags & TH_FIN)
5970 			len++;
5971 	}
5972 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5973 		/* Are sending an old segment to induce an ack (keep-alive)? */
5974 		return;
5975 	}
5976 	if (SEQ_LT(seq_out, snd_una)) {
5977 		/* huh? should we panic? */
5978 		uint32_t end;
5979 
5980 		end = seq_out + len;
5981 		seq_out = snd_una;
5982 		len = end - seq_out;
5983 	}
5984 	snd_max = tp->snd_max;
5985 	if (len == 0) {
5986 		/* We don't log zero window probes */
5987 		return;
5988 	}
5989 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5990 	/* First question is it a retransmission? */
5991 	if (seq_out == snd_max) {
5992 again:
5993 		rsm = bbr_alloc(bbr);
5994 		if (rsm == NULL) {
5995 			return;
5996 		}
5997 		rsm->r_flags = 0;
5998 		if (th_flags & TH_SYN)
5999 			rsm->r_flags |= BBR_HAS_SYN;
6000 		if (th_flags & TH_FIN)
6001 			rsm->r_flags |= BBR_HAS_FIN;
6002 		rsm->r_tim_lastsent[0] = cts;
6003 		rsm->r_rtr_cnt = 1;
6004 		rsm->r_rtr_bytes = 0;
6005 		rsm->r_start = seq_out;
6006 		rsm->r_end = rsm->r_start + len;
6007 		rsm->r_dupack = 0;
6008 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
6009 		rsm->r_pacing_delay = pacing_time;
6010 		rsm->r_ts_valid = bbr->rc_ts_valid;
6011 		if (bbr->rc_ts_valid)
6012 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
6013 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
6014 		if (bbr->r_ctl.r_app_limited_until)
6015 			rsm->r_app_limited = 1;
6016 		else
6017 			rsm->r_app_limited = 0;
6018 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
6019 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
6020 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
6021 		/*
6022 		 * Here we must also add in this rsm since snd_max
6023 		 * is updated after we return from a new send.
6024 		 */
6025 		rsm->r_flight_at_send += len;
6026 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
6027 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
6028 		rsm->r_in_tmap = 1;
6029 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
6030 			rsm->r_bbr_state = bbr_state_val(bbr);
6031 		else
6032 			rsm->r_bbr_state = 8;
6033 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
6034 			rsm->r_is_gain = 1;
6035 			rsm->r_is_drain = 0;
6036 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6037 			rsm->r_is_drain = 1;
6038 			rsm->r_is_gain = 0;
6039 		} else {
6040 			rsm->r_is_drain = 0;
6041 			rsm->r_is_gain = 0;
6042 		}
6043 		return;
6044 	}
6045 	/*
6046 	 * If we reach here its a retransmission and we need to find it.
6047 	 */
6048 more:
6049 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6050 		rsm = hintrsm;
6051 		hintrsm = NULL;
6052 	} else if (bbr->r_ctl.rc_next) {
6053 		/* We have a hint from a previous run */
6054 		rsm = bbr->r_ctl.rc_next;
6055 	} else {
6056 		/* No hints sorry */
6057 		rsm = NULL;
6058 	}
6059 	if ((rsm) && (rsm->r_start == seq_out)) {
6060 		/*
6061 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6062 		 * likely case.
6063 		 */
6064 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6065 		if (len == 0) {
6066 			return;
6067 		} else {
6068 			goto more;
6069 		}
6070 	}
6071 	/* Ok it was not the last pointer go through it the hard way. */
6072 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6073 		if (rsm->r_start == seq_out) {
6074 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6075 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6076 			if (len == 0) {
6077 				return;
6078 			} else {
6079 				continue;
6080 			}
6081 		}
6082 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6083 			/* Transmitted within this piece */
6084 			/*
6085 			 * Ok we must split off the front and then let the
6086 			 * update do the rest
6087 			 */
6088 			nrsm = bbr_alloc_full_limit(bbr);
6089 			if (nrsm == NULL) {
6090 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6091 				return;
6092 			}
6093 			/*
6094 			 * copy rsm to nrsm and then trim the front of rsm
6095 			 * to not include this part.
6096 			 */
6097 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6098 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6099 			if (rsm->r_in_tmap) {
6100 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6101 				nrsm->r_in_tmap = 1;
6102 			}
6103 			rsm->r_flags &= (~BBR_HAS_FIN);
6104 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6105 			if (len == 0) {
6106 				return;
6107 			}
6108 		}
6109 	}
6110 	/*
6111 	 * Hmm not found in map did they retransmit both old and on into the
6112 	 * new?
6113 	 */
6114 	if (seq_out == tp->snd_max) {
6115 		goto again;
6116 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6117 #ifdef BBR_INVARIANTS
6118 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6119 		    seq_out, len, tp->snd_una, tp->snd_max);
6120 		printf("Starting Dump of all rack entries\n");
6121 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6122 			printf("rsm:%p start:%u end:%u\n",
6123 			    rsm, rsm->r_start, rsm->r_end);
6124 		}
6125 		printf("Dump complete\n");
6126 		panic("seq_out not found rack:%p tp:%p",
6127 		    bbr, tp);
6128 #endif
6129 	} else {
6130 #ifdef BBR_INVARIANTS
6131 		/*
6132 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6133 		 * flag)
6134 		 */
6135 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6136 		    seq_out, len, tp->snd_max, tp);
6137 #endif
6138 	}
6139 }
6140 
6141 static void
6142 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6143 {
6144 	/*
6145 	 * Collapse timeout back the cum-ack moved.
6146 	 */
6147 	tp->t_rxtshift = 0;
6148 	tp->t_softerror = 0;
6149 }
6150 
6151 static void
6152 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6153 {
6154 	bbr->rtt_valid = 1;
6155 	bbr->r_ctl.cur_rtt = rtt_usecs;
6156 	bbr->r_ctl.ts_in = tsin;
6157 	if (rsm_send_time)
6158 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6159 }
6160 
6161 static void
6162 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6163 {
6164 	/**
6165 	 * We have in our bbr control:
6166 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6167 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6168 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6169 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6170 	 *
6171 	 * Now we can calculate the time between the sends by doing:
6172 	 *
6173 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6174 	 *
6175 	 * And the peer's time between receiving them by doing:
6176 	 *
6177 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6178 	 *
6179 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6180 	 * We also may find that we can't use the timestamps if say we see
6181 	 * that the peer_delta indicates that though we may have taken 10ms to
6182 	 * pace out the data, it only saw 1ms between the two packets. This would
6183 	 * indicate that somewhere on the path is a batching entity that is giving
6184 	 * out time-slices of the actual b/w. This would mean we could not use
6185 	 * reliably the peers timestamps.
6186 	 *
6187 	 * We expect delta > peer_delta initially. Until we figure out the
6188 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6189 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6190 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6191 	 * put a 1 there. If the value is faster then ours, we will disable the
6192 	 * use of timestamps (though we could revist this later if we find it to be not
6193 	 * just an isolated one or two flows)).
6194 	 *
6195 	 * To detect the batching middle boxes we will come up with our compensation and
6196 	 * if with it in place, we find the peer is drastically off (by some margin) in
6197 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6198 	 *
6199 	 */
6200 	uint64_t delta, peer_delta, delta_up;
6201 
6202 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6203 	if (delta < bbr_min_usec_delta) {
6204 		/*
6205 		 * Have not seen a min amount of time
6206 		 * between our send times so we can
6207 		 * make a determination of the timestamp
6208 		 * yet.
6209 		 */
6210 		return;
6211 	}
6212 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6213 	if (peer_delta < bbr_min_peer_delta) {
6214 		/*
6215 		 * We may have enough in the form of
6216 		 * our delta but the peers number
6217 		 * has not changed that much. It could
6218 		 * be its clock ratio is such that
6219 		 * we need more data (10ms tick) or
6220 		 * there may be other compression scenarios
6221 		 * going on. In any event we need the
6222 		 * spread to be larger.
6223 		 */
6224 		return;
6225 	}
6226 	/* Ok lets first see which way our delta is going */
6227 	if (peer_delta > delta) {
6228 		/* Very unlikely, the peer without
6229 		 * compensation shows that it saw
6230 		 * the two sends arrive further apart
6231 		 * then we saw then in micro-seconds.
6232 		 */
6233 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6234 			/* well it looks like the peer is a micro-second clock. */
6235 			bbr->rc_ts_clock_set = 1;
6236 			bbr->r_ctl.bbr_peer_tsratio = 1;
6237 		} else {
6238 			bbr->rc_ts_cant_be_used = 1;
6239 			bbr->rc_ts_clock_set = 1;
6240 		}
6241 		return;
6242 	}
6243 	/* Ok we know that the peer_delta is smaller than our send distance */
6244 	bbr->rc_ts_clock_set = 1;
6245 	/* First question is it within the percentage that they are using usec time? */
6246 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6247 	if ((peer_delta + delta_up) >= delta) {
6248 		/* Its a usec clock */
6249 		bbr->r_ctl.bbr_peer_tsratio = 1;
6250 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6251 		return;
6252 	}
6253 	/* Ok if not usec, what about 10usec (though unlikely)? */
6254 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6255 	if (((peer_delta * 10) + delta_up) >= delta) {
6256 		bbr->r_ctl.bbr_peer_tsratio = 10;
6257 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6258 		return;
6259 	}
6260 	/* And what about 100usec (though again unlikely)? */
6261 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6262 	if (((peer_delta * 100) + delta_up) >= delta) {
6263 		bbr->r_ctl.bbr_peer_tsratio = 100;
6264 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6265 		return;
6266 	}
6267 	/* And how about 1 msec (the most likely one)? */
6268 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6269 	if (((peer_delta * 1000) + delta_up) >= delta) {
6270 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6271 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6272 		return;
6273 	}
6274 	/* Ok if not msec could it be 10 msec? */
6275 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6276 	if (((peer_delta * 10000) + delta_up) >= delta) {
6277 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6278 		return;
6279 	}
6280 	/* If we fall down here the clock tick so slowly we can't use it */
6281 	bbr->rc_ts_cant_be_used = 1;
6282 	bbr->r_ctl.bbr_peer_tsratio = 0;
6283 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6284 }
6285 
6286 /*
6287  * Collect new round-trip time estimate
6288  * and update averages and current timeout.
6289  */
6290 static void
6291 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6292 {
6293 	int32_t delta;
6294 	uint32_t rtt, tsin;
6295 	int32_t rtt_ticks;
6296 
6297 	if (bbr->rtt_valid == 0)
6298 		/* No valid sample */
6299 		return;
6300 
6301 	rtt = bbr->r_ctl.cur_rtt;
6302 	tsin = bbr->r_ctl.ts_in;
6303 	if (bbr->rc_prtt_set_ts) {
6304 		/*
6305 		 * We are to force feed the rttProp filter due
6306 		 * to an entry into PROBE_RTT. This assures
6307 		 * that the times are sync'd between when we
6308 		 * go into PROBE_RTT and the filter expiration.
6309 		 *
6310 		 * Google does not use a true filter, so they do
6311 		 * this implicitly since they only keep one value
6312 		 * and when they enter probe-rtt they update the
6313 		 * value to the newest rtt.
6314 		 */
6315 		uint32_t rtt_prop;
6316 
6317 		bbr->rc_prtt_set_ts = 0;
6318 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6319 		if (rtt > rtt_prop)
6320 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6321 		else
6322 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6323 	}
6324 	if (bbr->rc_ack_was_delayed)
6325 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6326 
6327 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6328 		bbr->r_ctl.rc_lowest_rtt = rtt;
6329 	bbr_log_rtt_sample(bbr, rtt, tsin);
6330 	if (bbr->r_init_rtt) {
6331 		/*
6332 		 * The initial rtt is not-trusted, nuke it and lets get
6333 		 * our first valid measurement in.
6334 		 */
6335 		bbr->r_init_rtt = 0;
6336 		tp->t_srtt = 0;
6337 	}
6338 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6339 		/*
6340 		 * So we have not yet figured out
6341 		 * what the peers TSTMP value is
6342 		 * in (most likely ms). We need a
6343 		 * series of cum-ack's to determine
6344 		 * this reliably.
6345 		 */
6346 		if (bbr->rc_ack_is_cumack) {
6347 			if (bbr->rc_ts_data_set) {
6348 				/* Lets attempt to determine the timestamp granularity. */
6349 				bbr_make_timestamp_determination(bbr);
6350 			} else {
6351 				bbr->rc_ts_data_set = 1;
6352 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6353 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6354 			}
6355 		} else {
6356 			/*
6357 			 * We have to have consecutive acks
6358 			 * reset any "filled" state to none.
6359 			 */
6360 			bbr->rc_ts_data_set = 0;
6361 		}
6362 	}
6363 	/* Round it up */
6364 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6365 	if (rtt_ticks == 0)
6366 		rtt_ticks = 1;
6367 	if (tp->t_srtt != 0) {
6368 		/*
6369 		 * srtt is stored as fixed point with 5 bits after the
6370 		 * binary point (i.e., scaled by 8).  The following magic is
6371 		 * equivalent to the smoothing algorithm in rfc793 with an
6372 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6373 		 * Adjust rtt to origin 0.
6374 		 */
6375 
6376 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6377 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6378 
6379 		tp->t_srtt += delta;
6380 		if (tp->t_srtt <= 0)
6381 			tp->t_srtt = 1;
6382 
6383 		/*
6384 		 * We accumulate a smoothed rtt variance (actually, a
6385 		 * smoothed mean difference), then set the retransmit timer
6386 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6387 		 * is stored as fixed point with 4 bits after the binary
6388 		 * point (scaled by 16).  The following is equivalent to
6389 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6390 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6391 		 * wired-in beta.
6392 		 */
6393 		if (delta < 0)
6394 			delta = -delta;
6395 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6396 		tp->t_rttvar += delta;
6397 		if (tp->t_rttvar <= 0)
6398 			tp->t_rttvar = 1;
6399 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
6400 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6401 	} else {
6402 		/*
6403 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6404 		 * variance to half the rtt (so our first retransmit happens
6405 		 * at 3*rtt).
6406 		 */
6407 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6408 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6409 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6410 	}
6411 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6412 	tp->t_rttupdated++;
6413 #ifdef STATS
6414 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6415 #endif
6416 	/*
6417 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6418 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6419 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6420 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6421 	 * uncertainty in the firing of the timer.  The bias will give us
6422 	 * exactly the 1.5 tick we need.  But, because the bias is
6423 	 * statistical, we have to test that we don't drop below the minimum
6424 	 * feasible timer (which is 2 ticks).
6425 	 */
6426 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6427 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6428 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6429 
6430 	/*
6431 	 * We received an ack for a packet that wasn't retransmitted; it is
6432 	 * probably safe to discard any error indications we've received
6433 	 * recently.  This isn't quite right, but close enough for now (a
6434 	 * route might have failed after we sent a segment, and the return
6435 	 * path might not be symmetrical).
6436 	 */
6437 	tp->t_softerror = 0;
6438 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6439 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6440 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6441 }
6442 
6443 static void
6444 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6445 {
6446 	bbr->r_ctl.rc_rtt_shrinks = cts;
6447 	if (bbr_can_force_probertt &&
6448 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6449 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6450 		/*
6451 		 * We should enter probe-rtt its been too long
6452 		 * since we have been there.
6453 		 */
6454 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6455 	} else
6456 		bbr_check_probe_rtt_limits(bbr, cts);
6457 }
6458 
6459 static void
6460 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6461 {
6462 	uint64_t orig_bw;
6463 
6464 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6465 		/* We never apply a zero measurment */
6466 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6467 				    0, 0, 0, 0, 0, 0);
6468 		return;
6469 	}
6470 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6471 		bbr->r_ctl.r_measurement_count++;
6472 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6473 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6474 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6475 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6476 			    0, 0, 0, 0, 0, 0);
6477 	if (orig_bw &&
6478 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6479 		if (bbr->bbr_hdrw_pacing) {
6480 			/*
6481 			 * Apply a new rate to the hardware
6482 			 * possibly.
6483 			 */
6484 			bbr_update_hardware_pacing_rate(bbr, cts);
6485 		}
6486 		bbr_set_state_target(bbr, __LINE__);
6487 		tcp_bbr_tso_size_check(bbr, cts);
6488 		if (bbr->r_recovery_bw)  {
6489 			bbr_setup_red_bw(bbr, cts);
6490 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6491 		}
6492 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6493 		tcp_bbr_tso_size_check(bbr, cts);
6494 }
6495 
6496 static void
6497 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6498 {
6499 	if (bbr->rc_in_persist == 0) {
6500 		/* We log only when not in persist */
6501 		/* Translate to a Bytes Per Second */
6502 		uint64_t tim, bw, ts_diff, ts_bw;
6503 		uint32_t upper, lower, delivered;
6504 
6505 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6506 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6507 		else
6508 			tim = 1;
6509 		/*
6510 		 * Now that we have processed the tim (skipping the sample
6511 		 * or possibly updating the time, go ahead and
6512 		 * calculate the cdr.
6513 		 */
6514 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6515 		bw = (uint64_t)delivered;
6516 		bw *= (uint64_t)USECS_IN_SECOND;
6517 		bw /= tim;
6518 		if (bw == 0) {
6519 			/* We must have a calculatable amount */
6520 			return;
6521 		}
6522 		upper = (bw >> 32) & 0x00000000ffffffff;
6523 		lower = bw & 0x00000000ffffffff;
6524 		/*
6525 		 * If we are using this b/w shove it in now so we
6526 		 * can see in the trace viewer if it gets over-ridden.
6527 		 */
6528 		if (rsm->r_ts_valid &&
6529 		    bbr->rc_ts_valid &&
6530 		    bbr->rc_ts_clock_set &&
6531 		    (bbr->rc_ts_cant_be_used == 0) &&
6532 		    bbr->rc_use_ts_limit) {
6533 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6534 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6535 			if ((delivered == 0) ||
6536 			    (rtt < 1000)) {
6537 				/* Can't use the ts */
6538 				bbr_log_type_bbrupd(bbr, 61, cts,
6539 						    ts_diff,
6540 						    bbr->r_ctl.last_inbound_ts,
6541 						    rsm->r_del_ack_ts, 0,
6542 						    0, 0, 0, delivered);
6543 			} else {
6544 				ts_bw = (uint64_t)delivered;
6545 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6546 				ts_bw /= ts_diff;
6547 				bbr_log_type_bbrupd(bbr, 62, cts,
6548 						    (ts_bw >> 32),
6549 						    (ts_bw & 0xffffffff), 0, 0,
6550 						    0, 0, ts_diff, delivered);
6551 				if ((bbr->ts_can_raise) &&
6552 				    (ts_bw > bw)) {
6553 					bbr_log_type_bbrupd(bbr, 8, cts,
6554 							    delivered,
6555 							    ts_diff,
6556 							    (bw >> 32),
6557 							    (bw & 0x00000000ffffffff),
6558 							    0, 0, 0, 0);
6559 					bw = ts_bw;
6560 				} else if (ts_bw && (ts_bw < bw)) {
6561 					bbr_log_type_bbrupd(bbr, 7, cts,
6562 							    delivered,
6563 							    ts_diff,
6564 							    (bw >> 32),
6565 							    (bw & 0x00000000ffffffff),
6566 							    0, 0, 0, 0);
6567 					bw = ts_bw;
6568 				}
6569 			}
6570 		}
6571 		if (rsm->r_first_sent_time &&
6572 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6573 			uint64_t sbw, sti;
6574 			/*
6575 			 * We use what was in flight at the time of our
6576 			 * send  and the size of this send to figure
6577 			 * out what we have been sending at (amount).
6578 			 * For the time we take from the time of
6579 			 * the send of the first send outstanding
6580 			 * until this send plus this sends pacing
6581 			 * time. This gives us a good calculation
6582 			 * as to the rate we have been sending at.
6583 			 */
6584 
6585 			sbw = (uint64_t)(rsm->r_flight_at_send);
6586 			sbw *= (uint64_t)USECS_IN_SECOND;
6587 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6588 			sti += rsm->r_pacing_delay;
6589 			sbw /= sti;
6590 			if (sbw < bw) {
6591 				bbr_log_type_bbrupd(bbr, 6, cts,
6592 						    delivered,
6593 						    (uint32_t)sti,
6594 						    (bw >> 32),
6595 						    (uint32_t)bw,
6596 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6597 						    (uint32_t)sbw);
6598 				bw = sbw;
6599 			}
6600 		}
6601 		/* Use the google algorithm for b/w measurements */
6602 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6603 		if ((rsm->r_app_limited == 0) ||
6604 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6605 			tcp_bbr_commit_bw(bbr, cts);
6606 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6607 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6608 		}
6609 	}
6610 }
6611 
6612 static void
6613 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6614 {
6615 	if (bbr->rc_in_persist == 0) {
6616 		/* We log only when not in persist */
6617 		/* Translate to a Bytes Per Second */
6618 		uint64_t tim, bw;
6619 		uint32_t upper, lower, delivered;
6620 		int no_apply = 0;
6621 
6622 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6623 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6624 		else
6625 			tim = 1;
6626 		/*
6627 		 * Now that we have processed the tim (skipping the sample
6628 		 * or possibly updating the time, go ahead and
6629 		 * calculate the cdr.
6630 		 */
6631 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6632 		bw = (uint64_t)delivered;
6633 		bw *= (uint64_t)USECS_IN_SECOND;
6634 		bw /= tim;
6635 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6636 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6637 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6638 
6639 			no_apply = 1;
6640 		}
6641 		upper = (bw >> 32) & 0x00000000ffffffff;
6642 		lower = bw & 0x00000000ffffffff;
6643 		/*
6644 		 * If we are using this b/w shove it in now so we
6645 		 * can see in the trace viewer if it gets over-ridden.
6646 		 */
6647 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6648 		/* Gate by the sending rate */
6649 		if (rsm->r_first_sent_time &&
6650 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6651 			uint64_t sbw, sti;
6652 			/*
6653 			 * We use what was in flight at the time of our
6654 			 * send  and the size of this send to figure
6655 			 * out what we have been sending at (amount).
6656 			 * For the time we take from the time of
6657 			 * the send of the first send outstanding
6658 			 * until this send plus this sends pacing
6659 			 * time. This gives us a good calculation
6660 			 * as to the rate we have been sending at.
6661 			 */
6662 
6663 			sbw = (uint64_t)(rsm->r_flight_at_send);
6664 			sbw *= (uint64_t)USECS_IN_SECOND;
6665 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6666 			sti += rsm->r_pacing_delay;
6667 			sbw /= sti;
6668 			if (sbw < bw) {
6669 				bbr_log_type_bbrupd(bbr, 6, cts,
6670 						    delivered,
6671 						    (uint32_t)sti,
6672 						    (bw >> 32),
6673 						    (uint32_t)bw,
6674 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6675 						    (uint32_t)sbw);
6676 				bw = sbw;
6677 			}
6678 			if ((sti > tim) &&
6679 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6680 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6681 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6682 				no_apply = 1;
6683 			} else
6684 				no_apply = 0;
6685 		}
6686 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6687 		if ((no_apply == 0) &&
6688 		    ((rsm->r_app_limited == 0) ||
6689 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6690 			tcp_bbr_commit_bw(bbr, cts);
6691 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6692 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6693 		}
6694 	}
6695 }
6696 
6697 static void
6698 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6699     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6700 {
6701 	uint64_t old_rttprop;
6702 
6703 	/* Update our delivery time and amount */
6704 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6705 	bbr->r_ctl.rc_del_time = cts;
6706 	if (rtt == 0) {
6707 		/*
6708 		 * 0 means its a retransmit, for now we don't use these for
6709 		 * the rest of BBR.
6710 		 */
6711 		return;
6712 	}
6713 	if ((bbr->rc_use_google == 0) &&
6714 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6715 	    (match != BBR_RTT_BY_TIMESTAMP)){
6716 		/*
6717 		 * We get a lot of rtt updates, lets not pay attention to
6718 		 * any that are not an exact match. That way we don't have
6719 		 * to worry about timestamps and the whole nonsense of
6720 		 * unsure if its a retransmission etc (if we ever had the
6721 		 * timestamp fixed to always have the last thing sent this
6722 		 * would not be a issue).
6723 		 */
6724 		return;
6725 	}
6726 	if ((bbr_no_retran && bbr->rc_use_google) &&
6727 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6728 	    (match != BBR_RTT_BY_TIMESTAMP)){
6729 		/*
6730 		 * We only do measurements in google mode
6731 		 * with bbr_no_retran on for sure things.
6732 		 */
6733 		return;
6734 	}
6735 	/* Only update srtt if we know by exact match */
6736 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6737 	if (ack_type == BBR_CUM_ACKED)
6738 		bbr->rc_ack_is_cumack = 1;
6739 	else
6740 		bbr->rc_ack_is_cumack = 0;
6741 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6742 	/*
6743 	 * Note the following code differs to the original
6744 	 * BBR spec. It calls for <= not <. However after a
6745 	 * long discussion in email with Neal, he acknowledged
6746 	 * that it should be < than so that we will have flows
6747 	 * going into probe-rtt (we were seeing cases where that
6748 	 * did not happen and caused ugly things to occur). We
6749 	 * have added this agreed upon fix to our code base.
6750 	 */
6751 	if (rtt < old_rttprop) {
6752 		/* Update when we last saw a rtt drop */
6753 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6754 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6755 	}
6756 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6757 	    match, rsm->r_start, rsm->r_flags);
6758 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6759 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6760 		/*
6761 		 * The RTT-prop moved, reset the target (may be a
6762 		 * nop for some states).
6763 		 */
6764 		bbr_set_state_target(bbr, __LINE__);
6765 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6766 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6767 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6768 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6769 			/* It went up */
6770 			bbr_check_probe_rtt_limits(bbr, cts);
6771 	}
6772 	if ((bbr->rc_use_google == 0) &&
6773 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6774 		/*
6775 		 * We don't do b/w update with
6776 		 * these since they are not really
6777 		 * reliable.
6778 		 */
6779 		return;
6780 	}
6781 	if (bbr->r_ctl.r_app_limited_until &&
6782 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6783 		/* We are no longer app-limited */
6784 		bbr->r_ctl.r_app_limited_until = 0;
6785 	}
6786 	if (bbr->rc_use_google) {
6787 		bbr_google_measurement(bbr, rsm, rtt, cts);
6788 	} else {
6789 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6790 	}
6791 }
6792 
6793 /*
6794  * Convert a timestamp that the main stack
6795  * uses (milliseconds) into one that bbr uses
6796  * (microseconds). Return that converted timestamp.
6797  */
6798 static uint32_t
6799 bbr_ts_convert(uint32_t cts) {
6800 	uint32_t sec, msec;
6801 
6802 	sec = cts / MS_IN_USEC;
6803 	msec = cts - (MS_IN_USEC * sec);
6804 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6805 }
6806 
6807 /*
6808  * Return 0 if we did not update the RTT time, return
6809  * 1 if we did.
6810  */
6811 static int
6812 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6813     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6814 {
6815 	int32_t i;
6816 	uint32_t t, uts = 0;
6817 
6818 	if ((rsm->r_flags & BBR_ACKED) ||
6819 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6820 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6821 		/* Already done */
6822 		return (0);
6823 	}
6824 	if (rsm->r_rtt_not_allowed) {
6825 		/* Not allowed */
6826 		return (0);
6827 	}
6828 	if (rsm->r_rtr_cnt == 1) {
6829 		/*
6830 		 * Only one transmit. Hopefully the normal case.
6831 		 */
6832 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6833 			t = cts - rsm->r_tim_lastsent[0];
6834 		else
6835 			t = 1;
6836 		if ((int)t <= 0)
6837 			t = 1;
6838 		bbr->r_ctl.rc_last_rtt = t;
6839 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6840 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6841 		return (1);
6842 	}
6843 	/* Convert to usecs */
6844 	if ((bbr_can_use_ts_for_rtt == 1) &&
6845 	    (bbr->rc_use_google == 1) &&
6846 	    (ack_type == BBR_CUM_ACKED) &&
6847 	    (to->to_flags & TOF_TS) &&
6848 	    (to->to_tsecr != 0)) {
6849 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6850 		if (t < 1)
6851 			t = 1;
6852 		t *= MS_IN_USEC;
6853 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6854 				    BBR_RTT_BY_TIMESTAMP,
6855 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6856 				    ack_type, to);
6857 		return (1);
6858 	}
6859 	uts = bbr_ts_convert(to->to_tsecr);
6860 	if ((to->to_flags & TOF_TS) &&
6861 	    (to->to_tsecr != 0) &&
6862 	    (ack_type == BBR_CUM_ACKED) &&
6863 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6864 		/*
6865 		 * Now which timestamp does it match? In this block the ACK
6866 		 * may be coming from a previous transmission.
6867 		 */
6868 		uint32_t fudge;
6869 
6870 		fudge = BBR_TIMER_FUDGE;
6871 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6872 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6873 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6874 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6875 					t = cts - rsm->r_tim_lastsent[i];
6876 				else
6877 					t = 1;
6878 				if ((int)t <= 0)
6879 					t = 1;
6880 				bbr->r_ctl.rc_last_rtt = t;
6881 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6882 						    rsm->r_tim_lastsent[i], ack_type, to);
6883 				if ((i + 1) < rsm->r_rtr_cnt) {
6884 					/* Likely */
6885 					return (0);
6886 				} else if (rsm->r_flags & BBR_TLP) {
6887 					bbr->rc_tlp_rtx_out = 0;
6888 				}
6889 				return (1);
6890 			}
6891 		}
6892 		/* Fall through if we can't find a matching timestamp */
6893 	}
6894 	/*
6895 	 * Ok its a SACK block that we retransmitted. or a windows
6896 	 * machine without timestamps. We can tell nothing from the
6897 	 * time-stamp since its not there or the time the peer last
6898 	 * recieved a segment that moved forward its cum-ack point.
6899 	 *
6900 	 * Lets look at the last retransmit and see what we can tell
6901 	 * (with BBR for space we only keep 2 note we have to keep
6902 	 * at least 2 so the map can not be condensed more).
6903 	 */
6904 	i = rsm->r_rtr_cnt - 1;
6905 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6906 		t = cts - rsm->r_tim_lastsent[i];
6907 	else
6908 		goto not_sure;
6909 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6910 		/*
6911 		 * We retransmitted and the ack came back in less
6912 		 * than the smallest rtt we have observed in the
6913 		 * windowed rtt. We most likey did an improper
6914 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6915 		 * the rack-draft.
6916 		 *
6917 		 * Use the prior transmission to update all the
6918 		 * information as long as there is only one prior
6919 		 * transmission.
6920 		 */
6921 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6922 #ifdef BBR_INVARIANTS
6923 			if (rsm->r_rtr_cnt == 1)
6924 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6925 #endif
6926 			i = rsm->r_rtr_cnt - 2;
6927 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6928 				t = cts - rsm->r_tim_lastsent[i];
6929 			else
6930 				t = 1;
6931 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6932 					    rsm->r_tim_lastsent[i], ack_type, to);
6933 			return (0);
6934 		} else {
6935 			/*
6936 			 * Too many prior transmissions, just
6937 			 * updated BBR delivered
6938 			 */
6939 not_sure:
6940 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6941 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6942 		}
6943 	} else {
6944 		/*
6945 		 * We retransmitted it and the retransmit did the
6946 		 * job.
6947 		 */
6948 		if (rsm->r_flags & BBR_TLP)
6949 			bbr->rc_tlp_rtx_out = 0;
6950 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6951 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6952 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6953 		else
6954 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6955 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6956 		return (1);
6957 	}
6958 	return (0);
6959 }
6960 
6961 /*
6962  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6963  */
6964 static void
6965 bbr_log_sack_passed(struct tcpcb *tp,
6966     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6967 {
6968 	struct bbr_sendmap *nrsm;
6969 
6970 	nrsm = rsm;
6971 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6972 	    bbr_head, r_tnext) {
6973 		if (nrsm == rsm) {
6974 			/* Skip orginal segment he is acked */
6975 			continue;
6976 		}
6977 		if (nrsm->r_flags & BBR_ACKED) {
6978 			/* Skip ack'd segments */
6979 			continue;
6980 		}
6981 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6982 			/*
6983 			 * We found one that is already marked
6984 			 * passed, we have been here before and
6985 			 * so all others below this are marked.
6986 			 */
6987 			break;
6988 		}
6989 		BBR_STAT_INC(bbr_sack_passed);
6990 		nrsm->r_flags |= BBR_SACK_PASSED;
6991 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6992 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6993 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6994 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6995 			nrsm->r_flags |= BBR_MARKED_LOST;
6996 		}
6997 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6998 	}
6999 }
7000 
7001 /*
7002  * Returns the number of bytes that were
7003  * newly ack'd by sack blocks.
7004  */
7005 static uint32_t
7006 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
7007     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
7008 {
7009 	int32_t times = 0;
7010 	uint32_t start, end, maxseg, changed = 0;
7011 	struct bbr_sendmap *rsm, *nrsm;
7012 	int32_t used_ref = 1;
7013 	uint8_t went_back = 0, went_fwd = 0;
7014 
7015 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7016 	start = sack->start;
7017 	end = sack->end;
7018 	rsm = *prsm;
7019 	if (rsm == NULL)
7020 		used_ref = 0;
7021 
7022 	/* Do we locate the block behind where we last were? */
7023 	if (rsm && SEQ_LT(start, rsm->r_start)) {
7024 		went_back = 1;
7025 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
7026 			if (SEQ_GEQ(start, rsm->r_start) &&
7027 			    SEQ_LT(start, rsm->r_end)) {
7028 				goto do_rest_ofb;
7029 			}
7030 		}
7031 	}
7032 start_at_beginning:
7033 	went_fwd = 1;
7034 	/*
7035 	 * Ok lets locate the block where this guy is fwd from rsm (if its
7036 	 * set)
7037 	 */
7038 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
7039 		if (SEQ_GEQ(start, rsm->r_start) &&
7040 		    SEQ_LT(start, rsm->r_end)) {
7041 			break;
7042 		}
7043 	}
7044 do_rest_ofb:
7045 	if (rsm == NULL) {
7046 		/*
7047 		 * This happens when we get duplicate sack blocks with the
7048 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7049 		 * will not change there location so we would just start at
7050 		 * the end of the first one and get lost.
7051 		 */
7052 		if (tp->t_flags & TF_SENTFIN) {
7053 			/*
7054 			 * Check to see if we have not logged the FIN that
7055 			 * went out.
7056 			 */
7057 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7058 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7059 				/*
7060 				 * Ok we did not get the FIN logged.
7061 				 */
7062 				nrsm->r_end++;
7063 				rsm = nrsm;
7064 				goto do_rest_ofb;
7065 			}
7066 		}
7067 		if (times == 1) {
7068 #ifdef BBR_INVARIANTS
7069 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7070 			    tp, bbr, sack, to, prsm);
7071 #else
7072 			goto out;
7073 #endif
7074 		}
7075 		times++;
7076 		BBR_STAT_INC(bbr_sack_proc_restart);
7077 		rsm = NULL;
7078 		goto start_at_beginning;
7079 	}
7080 	/* Ok we have an ACK for some piece of rsm */
7081 	if (rsm->r_start != start) {
7082 		/*
7083 		 * Need to split this in two pieces the before and after.
7084 		 */
7085 		if (bbr_sack_mergable(rsm, start, end))
7086 			nrsm = bbr_alloc_full_limit(bbr);
7087 		else
7088 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7089 		if (nrsm == NULL) {
7090 			/* We could not allocate ignore the sack */
7091 			struct sackblk blk;
7092 
7093 			blk.start = start;
7094 			blk.end = end;
7095 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7096 			goto out;
7097 		}
7098 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7099 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7100 		if (rsm->r_in_tmap) {
7101 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7102 			nrsm->r_in_tmap = 1;
7103 		}
7104 		rsm->r_flags &= (~BBR_HAS_FIN);
7105 		rsm = nrsm;
7106 	}
7107 	if (SEQ_GEQ(end, rsm->r_end)) {
7108 		/*
7109 		 * The end of this block is either beyond this guy or right
7110 		 * at this guy.
7111 		 */
7112 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7113 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7114 			changed += (rsm->r_end - rsm->r_start);
7115 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7116 			bbr_log_sack_passed(tp, bbr, rsm);
7117 			if (rsm->r_flags & BBR_MARKED_LOST) {
7118 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7119 			}
7120 			/* Is Reordering occuring? */
7121 			if (rsm->r_flags & BBR_SACK_PASSED) {
7122 				BBR_STAT_INC(bbr_reorder_seen);
7123 				bbr->r_ctl.rc_reorder_ts = cts;
7124 				if (rsm->r_flags & BBR_MARKED_LOST) {
7125 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7126 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7127 						/* LT sampling also needs adjustment */
7128 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7129 				}
7130 			}
7131 			rsm->r_flags |= BBR_ACKED;
7132 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7133 			if (rsm->r_in_tmap) {
7134 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7135 				rsm->r_in_tmap = 0;
7136 			}
7137 		}
7138 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7139 		if (end == rsm->r_end) {
7140 			/* This block only - done */
7141 			goto out;
7142 		}
7143 		/* There is more not coverend by this rsm move on */
7144 		start = rsm->r_end;
7145 		nrsm = TAILQ_NEXT(rsm, r_next);
7146 		rsm = nrsm;
7147 		times = 0;
7148 		goto do_rest_ofb;
7149 	}
7150 	if (rsm->r_flags & BBR_ACKED) {
7151 		/* Been here done that */
7152 		goto out;
7153 	}
7154 	/* Ok we need to split off this one at the tail */
7155 	if (bbr_sack_mergable(rsm, start, end))
7156 		nrsm = bbr_alloc_full_limit(bbr);
7157 	else
7158 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7159 	if (nrsm == NULL) {
7160 		/* failed XXXrrs what can we do but loose the sack info? */
7161 		struct sackblk blk;
7162 
7163 		blk.start = start;
7164 		blk.end = end;
7165 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7166 		goto out;
7167 	}
7168 	/* Clone it */
7169 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7170 	/* The sack block does not cover this guy fully */
7171 	rsm->r_flags &= (~BBR_HAS_FIN);
7172 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7173 	if (rsm->r_in_tmap) {
7174 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7175 		nrsm->r_in_tmap = 1;
7176 	}
7177 	nrsm->r_dupack = 0;
7178 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7179 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7180 	changed += (rsm->r_end - rsm->r_start);
7181 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7182 	bbr_log_sack_passed(tp, bbr, rsm);
7183 	/* Is Reordering occuring? */
7184 	if (rsm->r_flags & BBR_MARKED_LOST) {
7185 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7186 	}
7187 	if (rsm->r_flags & BBR_SACK_PASSED) {
7188 		BBR_STAT_INC(bbr_reorder_seen);
7189 		bbr->r_ctl.rc_reorder_ts = cts;
7190 		if (rsm->r_flags & BBR_MARKED_LOST) {
7191 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7192 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7193 				/* LT sampling also needs adjustment */
7194 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7195 		}
7196 	}
7197 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7198 	rsm->r_flags |= BBR_ACKED;
7199 	if (rsm->r_in_tmap) {
7200 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7201 		rsm->r_in_tmap = 0;
7202 	}
7203 out:
7204 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7205 		/*
7206 		 * Now can we merge this newly acked
7207 		 * block with either the previous or
7208 		 * next block?
7209 		 */
7210 		nrsm = TAILQ_NEXT(rsm, r_next);
7211 		if (nrsm &&
7212 		    (nrsm->r_flags & BBR_ACKED)) {
7213 			/* yep this and next can be merged */
7214 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7215 		}
7216 		/* Now what about the previous? */
7217 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7218 		if (nrsm &&
7219 		    (nrsm->r_flags & BBR_ACKED)) {
7220 			/* yep the previous and this can be merged */
7221 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7222 		}
7223 	}
7224 	if (used_ref == 0) {
7225 		BBR_STAT_INC(bbr_sack_proc_all);
7226 	} else {
7227 		BBR_STAT_INC(bbr_sack_proc_short);
7228 	}
7229 	if (went_fwd && went_back) {
7230 		BBR_STAT_INC(bbr_sack_search_both);
7231 	} else if (went_fwd) {
7232 		BBR_STAT_INC(bbr_sack_search_fwd);
7233 	} else if (went_back) {
7234 		BBR_STAT_INC(bbr_sack_search_back);
7235 	}
7236 	/* Save off where the next seq is */
7237 	if (rsm)
7238 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7239 	else
7240 		bbr->r_ctl.rc_sacklast = NULL;
7241 	*prsm = rsm;
7242 	return (changed);
7243 }
7244 
7245 static void inline
7246 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7247 {
7248 	struct bbr_sendmap *tmap;
7249 
7250 	BBR_STAT_INC(bbr_reneges_seen);
7251 	tmap = NULL;
7252 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7253 		/* Its no longer sacked, mark it so */
7254 		uint32_t oflags;
7255 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7256 #ifdef BBR_INVARIANTS
7257 		if (rsm->r_in_tmap) {
7258 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7259 			    bbr, rsm, rsm->r_flags);
7260 		}
7261 #endif
7262 		oflags = rsm->r_flags;
7263 		if (rsm->r_flags & BBR_MARKED_LOST) {
7264 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7265 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7266 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7267 				/* LT sampling also needs adjustment */
7268 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7269 		}
7270 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7271 		rsm->r_flags |= BBR_WAS_RENEGED;
7272 		rsm->r_flags |= BBR_RXT_CLEARED;
7273 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7274 		/* Rebuild it into our tmap */
7275 		if (tmap == NULL) {
7276 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7277 			tmap = rsm;
7278 		} else {
7279 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7280 			tmap = rsm;
7281 		}
7282 		tmap->r_in_tmap = 1;
7283 		/*
7284 		 * XXXrrs Delivered? Should we do anything here?
7285 		 *
7286 		 * Of course we don't on a rxt timeout so maybe its ok that
7287 		 * we don't?
7288 		 *
7289 		 * For now lets not.
7290 		 */
7291 		rsm = TAILQ_NEXT(rsm, r_next);
7292 	}
7293 	/*
7294 	 * Now lets possibly clear the sack filter so we start recognizing
7295 	 * sacks that cover this area.
7296 	 */
7297 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7298 }
7299 
7300 static void
7301 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7302 {
7303 	struct tcp_bbr *bbr;
7304 	struct bbr_sendmap *rsm;
7305 	uint32_t cts;
7306 
7307 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7308 	cts = bbr->r_ctl.rc_rcvtime;
7309 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7310 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7311 		if ((rsm->r_end - rsm->r_start) <= 1) {
7312 			/* Log out the SYN completely */
7313 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7314 			rsm->r_rtr_bytes = 0;
7315 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7316 			if (rsm->r_in_tmap) {
7317 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7318 				rsm->r_in_tmap = 0;
7319 			}
7320 			if (bbr->r_ctl.rc_next == rsm) {
7321 				/* scoot along the marker */
7322 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7323 			}
7324 			if (to != NULL)
7325 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7326 			bbr_free(bbr, rsm);
7327 		} else {
7328 			/* There is more (Fast open)? strip out SYN. */
7329 			rsm->r_flags &= ~BBR_HAS_SYN;
7330 			rsm->r_start++;
7331 		}
7332 	}
7333 }
7334 
7335 /*
7336  * Returns the number of bytes that were
7337  * acknowledged by SACK blocks.
7338  */
7339 
7340 static uint32_t
7341 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7342     uint32_t *prev_acked)
7343 {
7344 	uint32_t changed, last_seq, entered_recovery = 0;
7345 	struct tcp_bbr *bbr;
7346 	struct bbr_sendmap *rsm;
7347 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7348 	register uint32_t th_ack;
7349 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7350 	uint32_t cts, acked, ack_point, sack_changed = 0;
7351 	uint32_t p_maxseg, maxseg, p_acked = 0;
7352 
7353 	INP_WLOCK_ASSERT(tp->t_inpcb);
7354 	if (th->th_flags & TH_RST) {
7355 		/* We don't log resets */
7356 		return (0);
7357 	}
7358 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7359 	cts = bbr->r_ctl.rc_rcvtime;
7360 
7361 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7362 	changed = 0;
7363 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7364 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7365 	th_ack = th->th_ack;
7366 	if (SEQ_GT(th_ack, tp->snd_una)) {
7367 		acked = th_ack - tp->snd_una;
7368 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7369 		bbr->rc_tp->t_acktime = ticks;
7370 	} else
7371 		acked = 0;
7372 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7373 		/* Only sent here for sack processing */
7374 		goto proc_sack;
7375 	}
7376 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7377 		changed = th_ack - rsm->r_start;
7378 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7379 		/*
7380 		 * For the SYN incoming case we will not have called
7381 		 * tcp_output for the sending of the SYN, so there will be
7382 		 * no map. All other cases should probably be a panic.
7383 		 */
7384 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7385 			/*
7386 			 * We have a timestamp that can be used to generate
7387 			 * an initial RTT.
7388 			 */
7389 			uint32_t ts, now, rtt;
7390 
7391 			ts = bbr_ts_convert(to->to_tsecr);
7392 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7393 			rtt = now - ts;
7394 			if (rtt < 1)
7395 				rtt = 1;
7396 			bbr_log_type_bbrrttprop(bbr, rtt,
7397 						tp->iss, 0, cts,
7398 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7399 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7400 			changed = 1;
7401 			bbr->r_wanted_output = 1;
7402 			goto out;
7403 		}
7404 		goto proc_sack;
7405 	} else if (rsm == NULL) {
7406 		goto out;
7407 	}
7408 	if (changed) {
7409 		/*
7410 		 * The ACK point is advancing to th_ack, we must drop off
7411 		 * the packets in the rack log and calculate any eligble
7412 		 * RTT's.
7413 		 */
7414 		bbr->r_wanted_output = 1;
7415 more:
7416 		if (rsm == NULL) {
7417 			if (tp->t_flags & TF_SENTFIN) {
7418 				/* if we send a FIN we will not hav a map */
7419 				goto proc_sack;
7420 			}
7421 #ifdef BBR_INVARIANTS
7422 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7423 			    tp,
7424 			    th, tp->t_state, bbr,
7425 			    tp->snd_una, tp->snd_max, changed);
7426 #endif
7427 			goto proc_sack;
7428 		}
7429 	}
7430 	if (SEQ_LT(th_ack, rsm->r_start)) {
7431 		/* Huh map is missing this */
7432 #ifdef BBR_INVARIANTS
7433 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7434 		    rsm->r_start,
7435 		    th_ack, tp->t_state,
7436 		    bbr->r_state, bbr);
7437 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7438 #endif
7439 		goto proc_sack;
7440 	} else if (th_ack == rsm->r_start) {
7441 		/* None here to ack */
7442 		goto proc_sack;
7443 	}
7444 	/*
7445 	 * Clear the dup ack counter, it will
7446 	 * either be freed or if there is some
7447 	 * remaining we need to start it at zero.
7448 	 */
7449 	rsm->r_dupack = 0;
7450 	/* Now do we consume the whole thing? */
7451 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7452 		/* Its all consumed. */
7453 		uint32_t left;
7454 
7455 		if (rsm->r_flags & BBR_ACKED) {
7456 			/*
7457 			 * It was acked on the scoreboard -- remove it from
7458 			 * total
7459 			 */
7460 			p_acked += (rsm->r_end - rsm->r_start);
7461 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7462 			if (bbr->r_ctl.rc_sacked == 0)
7463 				bbr->r_ctl.rc_sacklast = NULL;
7464 		} else {
7465 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7466 			if (rsm->r_flags & BBR_MARKED_LOST) {
7467 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7468 			}
7469 			if (rsm->r_flags & BBR_SACK_PASSED) {
7470 				/*
7471 				 * There are acked segments ACKED on the
7472 				 * scoreboard further up. We are seeing
7473 				 * reordering.
7474 				 */
7475 				BBR_STAT_INC(bbr_reorder_seen);
7476 				bbr->r_ctl.rc_reorder_ts = cts;
7477 				if (rsm->r_flags & BBR_MARKED_LOST) {
7478 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7479 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7480 						/* LT sampling also needs adjustment */
7481 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7482 				}
7483 			}
7484 			rsm->r_flags &= ~BBR_MARKED_LOST;
7485 		}
7486 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7487 		rsm->r_rtr_bytes = 0;
7488 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7489 		if (rsm->r_in_tmap) {
7490 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7491 			rsm->r_in_tmap = 0;
7492 		}
7493 		if (bbr->r_ctl.rc_next == rsm) {
7494 			/* scoot along the marker */
7495 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7496 		}
7497 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7498 		/* Adjust the packet counts */
7499 		left = th_ack - rsm->r_end;
7500 		/* Free back to zone */
7501 		bbr_free(bbr, rsm);
7502 		if (left) {
7503 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7504 			goto more;
7505 		}
7506 		goto proc_sack;
7507 	}
7508 	if (rsm->r_flags & BBR_ACKED) {
7509 		/*
7510 		 * It was acked on the scoreboard -- remove it from total
7511 		 * for the part being cum-acked.
7512 		 */
7513 		p_acked += (rsm->r_end - rsm->r_start);
7514 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7515 		if (bbr->r_ctl.rc_sacked == 0)
7516 			bbr->r_ctl.rc_sacklast = NULL;
7517 	} else {
7518 		/*
7519 		 * It was acked up to th_ack point for the first time
7520 		 */
7521 		struct bbr_sendmap lrsm;
7522 
7523 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7524 		lrsm.r_end = th_ack;
7525 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7526 	}
7527 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7528 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7529 		/*
7530 		 * It was marked lost and partly ack'd now
7531 		 * for the first time. We lower the rc_lost_bytes
7532 		 * and still leave it MARKED.
7533 		 */
7534 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7535 	}
7536 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7537 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7538 	rsm->r_rtr_bytes = 0;
7539 	/* adjust packet count */
7540 	rsm->r_start = th_ack;
7541 proc_sack:
7542 	/* Check for reneging */
7543 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7544 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7545 		/*
7546 		 * The peer has moved snd_una up to the edge of this send,
7547 		 * i.e. one that it had previously acked. The only way that
7548 		 * can be true if the peer threw away data (space issues)
7549 		 * that it had previously sacked (else it would have given
7550 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7551 		 * markings here.
7552 		 *
7553 		 * Note we have to look to make sure th_ack is our
7554 		 * rsm->r_start in case we get an old ack where th_ack is
7555 		 * behind snd_una.
7556 		 */
7557 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7558 	}
7559 	if ((to->to_flags & TOF_SACK) == 0) {
7560 		/* We are done nothing left to log */
7561 		goto out;
7562 	}
7563 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7564 	if (rsm) {
7565 		last_seq = rsm->r_end;
7566 	} else {
7567 		last_seq = tp->snd_max;
7568 	}
7569 	/* Sack block processing */
7570 	if (SEQ_GT(th_ack, tp->snd_una))
7571 		ack_point = th_ack;
7572 	else
7573 		ack_point = tp->snd_una;
7574 	for (i = 0; i < to->to_nsacks; i++) {
7575 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7576 		    &sack, sizeof(sack));
7577 		sack.start = ntohl(sack.start);
7578 		sack.end = ntohl(sack.end);
7579 		if (SEQ_GT(sack.end, sack.start) &&
7580 		    SEQ_GT(sack.start, ack_point) &&
7581 		    SEQ_LT(sack.start, tp->snd_max) &&
7582 		    SEQ_GT(sack.end, ack_point) &&
7583 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7584 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7585 			    (SEQ_LT(sack.end, last_seq)) &&
7586 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7587 				/*
7588 				 * Not the last piece and its smaller than
7589 				 * 1/8th of a p_maxseg. We ignore this.
7590 				 */
7591 				BBR_STAT_INC(bbr_runt_sacks);
7592 				continue;
7593 			}
7594 			sack_blocks[num_sack_blks] = sack;
7595 			num_sack_blks++;
7596 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7597 		    SEQ_LEQ(sack.end, th_ack)) {
7598 			/*
7599 			 * Its a D-SACK block.
7600 			 */
7601 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7602 		}
7603 	}
7604 	if (num_sack_blks == 0)
7605 		goto out;
7606 	/*
7607 	 * Sort the SACK blocks so we can update the rack scoreboard with
7608 	 * just one pass.
7609 	 */
7610 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7611 				  num_sack_blks, th->th_ack);
7612 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7613 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7614 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7615 	num_sack_blks = new_sb;
7616 	if (num_sack_blks < 2) {
7617 		goto do_sack_work;
7618 	}
7619 	/* Sort the sacks */
7620 	for (i = 0; i < num_sack_blks; i++) {
7621 		for (j = i + 1; j < num_sack_blks; j++) {
7622 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7623 				sack = sack_blocks[i];
7624 				sack_blocks[i] = sack_blocks[j];
7625 				sack_blocks[j] = sack;
7626 			}
7627 		}
7628 	}
7629 	/*
7630 	 * Now are any of the sack block ends the same (yes some
7631 	 * implememtations send these)?
7632 	 */
7633 again:
7634 	if (num_sack_blks > 1) {
7635 		for (i = 0; i < num_sack_blks; i++) {
7636 			for (j = i + 1; j < num_sack_blks; j++) {
7637 				if (sack_blocks[i].end == sack_blocks[j].end) {
7638 					/*
7639 					 * Ok these two have the same end we
7640 					 * want the smallest end and then
7641 					 * throw away the larger and start
7642 					 * again.
7643 					 */
7644 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7645 						/*
7646 						 * The second block covers
7647 						 * more area use that
7648 						 */
7649 						sack_blocks[i].start = sack_blocks[j].start;
7650 					}
7651 					/*
7652 					 * Now collapse out the dup-sack and
7653 					 * lower the count
7654 					 */
7655 					for (k = (j + 1); k < num_sack_blks; k++) {
7656 						sack_blocks[j].start = sack_blocks[k].start;
7657 						sack_blocks[j].end = sack_blocks[k].end;
7658 						j++;
7659 					}
7660 					num_sack_blks--;
7661 					goto again;
7662 				}
7663 			}
7664 		}
7665 	}
7666 do_sack_work:
7667 	rsm = bbr->r_ctl.rc_sacklast;
7668 	for (i = 0; i < num_sack_blks; i++) {
7669 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7670 		if (acked) {
7671 			bbr->r_wanted_output = 1;
7672 			changed += acked;
7673 			sack_changed += acked;
7674 		}
7675 	}
7676 out:
7677 	*prev_acked = p_acked;
7678 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7679 		/*
7680 		 * Ok we have a high probability that we need to go in to
7681 		 * recovery since we have data sack'd
7682 		 */
7683 		struct bbr_sendmap *rsm;
7684 
7685 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7686 		if (rsm) {
7687 			/* Enter recovery */
7688 			entered_recovery = 1;
7689 			bbr->r_wanted_output = 1;
7690 			/*
7691 			 * When we enter recovery we need to assure we send
7692 			 * one packet.
7693 			 */
7694 			if (bbr->r_ctl.rc_resend == NULL) {
7695 				bbr->r_ctl.rc_resend = rsm;
7696 			}
7697 		}
7698 	}
7699 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7700 		/*
7701 		 * See if we need to rack-retransmit anything if so set it
7702 		 * up as the thing to resend assuming something else is not
7703 		 * already in that position.
7704 		 */
7705 		if (bbr->r_ctl.rc_resend == NULL) {
7706 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7707 		}
7708 	}
7709 	/*
7710 	 * We return the amount that changed via sack, this is used by the
7711 	 * ack-received code to augment what was changed between th_ack <->
7712 	 * snd_una.
7713 	 */
7714 	return (sack_changed);
7715 }
7716 
7717 static void
7718 bbr_strike_dupack(struct tcp_bbr *bbr)
7719 {
7720 	struct bbr_sendmap *rsm;
7721 
7722 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7723 	if (rsm && (rsm->r_dupack < 0xff)) {
7724 		rsm->r_dupack++;
7725 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7726 			bbr->r_wanted_output = 1;
7727 	}
7728 }
7729 
7730 /*
7731  * Return value of 1, we do not need to call bbr_process_data().
7732  * return value of 0, bbr_process_data can be called.
7733  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7734  * its unlocked and probably unsafe to touch the TCB.
7735  */
7736 static int
7737 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7738     struct tcpcb *tp, struct tcpopt *to,
7739     uint32_t tiwin, int32_t tlen,
7740     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7741 {
7742 	int32_t ourfinisacked = 0;
7743 	int32_t acked_amount;
7744 	uint16_t nsegs;
7745 	int32_t acked;
7746 	uint32_t lost, sack_changed = 0;
7747 	struct mbuf *mfree;
7748 	struct tcp_bbr *bbr;
7749 	uint32_t prev_acked = 0;
7750 
7751 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7752 	lost = bbr->r_ctl.rc_lost;
7753 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7754 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7755 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7756 		bbr->r_wanted_output = 1;
7757 		return (1);
7758 	}
7759 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7760 		/* Process the ack */
7761 		if (bbr->rc_in_persist)
7762 			tp->t_rxtshift = 0;
7763 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7764 		        bbr_strike_dupack(bbr);
7765 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7766 	}
7767 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7768 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7769 		/*
7770 		 * Old ack, behind the last one rcv'd or a duplicate ack
7771 		 * with SACK info.
7772 		 */
7773 		if (th->th_ack == tp->snd_una) {
7774 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7775 			if (bbr->r_state == TCPS_SYN_SENT) {
7776 				/*
7777 				 * Special case on where we sent SYN. When
7778 				 * the SYN-ACK is processed in syn_sent
7779 				 * state it bumps the snd_una. This causes
7780 				 * us to hit here even though we did ack 1
7781 				 * byte.
7782 				 *
7783 				 * Go through the nothing left case so we
7784 				 * send data.
7785 				 */
7786 				goto nothing_left;
7787 			}
7788 		}
7789 		return (0);
7790 	}
7791 	/*
7792 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7793 	 * something we sent.
7794 	 */
7795 	if (tp->t_flags & TF_NEEDSYN) {
7796 		/*
7797 		 * T/TCP: Connection was half-synchronized, and our SYN has
7798 		 * been ACK'd (so connection is now fully synchronized).  Go
7799 		 * to non-starred state, increment snd_una for ACK of SYN,
7800 		 * and check if we can do window scaling.
7801 		 */
7802 		tp->t_flags &= ~TF_NEEDSYN;
7803 		tp->snd_una++;
7804 		/* Do window scaling? */
7805 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7806 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7807 			tp->rcv_scale = tp->request_r_scale;
7808 			/* Send window already scaled. */
7809 		}
7810 	}
7811 	INP_WLOCK_ASSERT(tp->t_inpcb);
7812 
7813 	acked = BYTES_THIS_ACK(tp, th);
7814 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7815 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7816 
7817 	/*
7818 	 * If we just performed our first retransmit, and the ACK arrives
7819 	 * within our recovery window, then it was a mistake to do the
7820 	 * retransmit in the first place.  Recover our original cwnd and
7821 	 * ssthresh, and proceed to transmit where we left off.
7822 	 */
7823 	if (tp->t_flags & TF_PREVVALID) {
7824 		tp->t_flags &= ~TF_PREVVALID;
7825 		if (tp->t_rxtshift == 1 &&
7826 		    (int)(ticks - tp->t_badrxtwin) < 0)
7827 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7828 	}
7829 	SOCKBUF_LOCK(&so->so_snd);
7830 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7831 	tp->snd_wnd -= acked_amount;
7832 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7833 	/* NB: sowwakeup_locked() does an implicit unlock. */
7834 	sowwakeup_locked(so);
7835 	m_freem(mfree);
7836 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7837 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7838 	}
7839 	tp->snd_una = th->th_ack;
7840 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7841 	if (IN_RECOVERY(tp->t_flags)) {
7842 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7843 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7844 			tcp_bbr_partialack(tp);
7845 		} else {
7846 			bbr_post_recovery(tp);
7847 		}
7848 	}
7849 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7850 		tp->snd_recover = tp->snd_una;
7851 	}
7852 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7853 		tp->snd_nxt = tp->snd_max;
7854 	}
7855 	if (tp->snd_una == tp->snd_max) {
7856 		/* Nothing left outstanding */
7857 nothing_left:
7858 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7859 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
7860 			bbr->rc_tp->t_acktime = 0;
7861 		if ((sbused(&so->so_snd) == 0) &&
7862 		    (tp->t_flags & TF_SENTFIN)) {
7863 			ourfinisacked = 1;
7864 		}
7865 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7866 		if (bbr->rc_in_persist == 0) {
7867 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7868 		}
7869 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7870 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7871 		/*
7872 		 * We invalidate the last ack here since we
7873 		 * don't want to transfer forward the time
7874 		 * for our sum's calculations.
7875 		 */
7876 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7877 		    (sbavail(&so->so_snd) == 0) &&
7878 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7879 			/*
7880 			 * The socket was gone and the peer sent data, time
7881 			 * to reset him.
7882 			 */
7883 			*ret_val = 1;
7884 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7885 			/* tcp_close will kill the inp pre-log the Reset */
7886 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7887 			tp = tcp_close(tp);
7888 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7889 			BBR_STAT_INC(bbr_dropped_af_data);
7890 			return (1);
7891 		}
7892 		/* Set need output so persist might get set */
7893 		bbr->r_wanted_output = 1;
7894 	}
7895 	if (ofia)
7896 		*ofia = ourfinisacked;
7897 	return (0);
7898 }
7899 
7900 static void
7901 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7902 {
7903 	if (bbr->rc_in_persist == 0) {
7904 		bbr_timer_cancel(bbr, __LINE__, cts);
7905 		bbr->r_ctl.rc_last_delay_val = 0;
7906 		tp->t_rxtshift = 0;
7907 		bbr->rc_in_persist = 1;
7908 		bbr->r_ctl.rc_went_idle_time = cts;
7909 		/* We should be capped when rw went to 0 but just in case */
7910 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7911 		/* Time freezes for the state, so do the accounting now */
7912 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7913 			uint32_t time_in;
7914 
7915 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7916 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7917 				int32_t idx;
7918 
7919 				idx = bbr_state_val(bbr);
7920 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7921 			} else {
7922 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7923 			}
7924 		}
7925 		bbr->r_ctl.rc_bbr_state_time = cts;
7926 	}
7927 }
7928 
7929 static void
7930 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7931 {
7932 	/*
7933 	 * Note that if idle time does not exceed our
7934 	 * threshold, we do nothing continuing the state
7935 	 * transitions we were last walking through.
7936 	 */
7937 	if (idle_time >= bbr_idle_restart_threshold) {
7938 		if (bbr->rc_use_idle_restart) {
7939 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7940 			/*
7941 			 * Set our target using BBR_UNIT, so
7942 			 * we increase at a dramatic rate but
7943 			 * we stop when we get the pipe
7944 			 * full again for our current b/w estimate.
7945 			 */
7946 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7947 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7948 			bbr_set_state_target(bbr, __LINE__);
7949 			/* Now setup our gains to ramp up */
7950 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7951 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7952 			bbr_log_type_statechange(bbr, cts, __LINE__);
7953 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7954 			bbr_substate_change(bbr, cts, __LINE__, 1);
7955 		}
7956 	}
7957 }
7958 
7959 static void
7960 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7961 {
7962 	uint32_t idle_time;
7963 
7964 	if (bbr->rc_in_persist == 0)
7965 		return;
7966 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7967 	bbr->rc_in_persist = 0;
7968 	bbr->rc_hit_state_1 = 0;
7969 	bbr->r_ctl.rc_del_time = cts;
7970 	/*
7971 	 * We invalidate the last ack here since we
7972 	 * don't want to transfer forward the time
7973 	 * for our sum's calculations.
7974 	 */
7975 	if (bbr->rc_inp->inp_in_hpts) {
7976 		tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
7977 		bbr->rc_timer_first = 0;
7978 		bbr->r_ctl.rc_hpts_flags = 0;
7979 		bbr->r_ctl.rc_last_delay_val = 0;
7980 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7981 		bbr->r_agg_early_set = 0;
7982 		bbr->r_ctl.rc_agg_early = 0;
7983 	}
7984 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7985 	if (idle_time >= bbr_rtt_probe_time) {
7986 		/*
7987 		 * This qualifies as a RTT_PROBE session since we drop the
7988 		 * data outstanding to nothing and waited more than
7989 		 * bbr_rtt_probe_time.
7990 		 */
7991 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7992 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7993 	}
7994 	tp->t_rxtshift = 0;
7995 	/*
7996 	 * If in probeBW and we have persisted more than an RTT lets do
7997 	 * special handling.
7998 	 */
7999 	/* Force a time based epoch */
8000 	bbr_set_epoch(bbr, cts, __LINE__);
8001 	/*
8002 	 * Setup the lost so we don't count anything against the guy
8003 	 * we have been stuck with during persists.
8004 	 */
8005 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
8006 	/* Time un-freezes for the state */
8007 	bbr->r_ctl.rc_bbr_state_time = cts;
8008 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
8009 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
8010 		/*
8011 		 * If we are going back to probe-bw
8012 		 * or probe_rtt, we may need to possibly
8013 		 * do a fast restart.
8014 		 */
8015 		bbr_restart_after_idle(bbr, cts, idle_time);
8016 	}
8017 }
8018 
8019 static void
8020 bbr_collapsed_window(struct tcp_bbr *bbr)
8021 {
8022 	/*
8023 	 * Now we must walk the
8024 	 * send map and divide the
8025 	 * ones left stranded. These
8026 	 * guys can't cause us to abort
8027 	 * the connection and are really
8028 	 * "unsent". However if a buggy
8029 	 * client actually did keep some
8030 	 * of the data i.e. collapsed the win
8031 	 * and refused to ack and then opened
8032 	 * the win and acked that data. We would
8033 	 * get into an ack war, the simplier
8034 	 * method then of just pretending we
8035 	 * did not send those segments something
8036 	 * won't work.
8037 	 */
8038 	struct bbr_sendmap *rsm, *nrsm;
8039 	tcp_seq max_seq;
8040 	uint32_t maxseg;
8041 	int can_split = 0;
8042 	int fnd = 0;
8043 
8044 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8045 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8046 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8047 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8048 		/* Find the first seq past or at maxseq */
8049 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8050 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8051 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8052 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8053 			fnd = 1;
8054 			break;
8055 		}
8056 	}
8057 	bbr->rc_has_collapsed = 0;
8058 	if (!fnd) {
8059 		/* Nothing to do strange */
8060 		return;
8061 	}
8062 	/*
8063 	 * Now can we split?
8064 	 *
8065 	 * We don't want to split if splitting
8066 	 * would generate too many small segments
8067 	 * less we let an attacker fragment our
8068 	 * send_map and leave us out of memory.
8069 	 */
8070 	if ((max_seq != rsm->r_start) &&
8071 	    (max_seq != rsm->r_end)){
8072 		/* can we split? */
8073 		int res1, res2;
8074 
8075 		res1 = max_seq - rsm->r_start;
8076 		res2 = rsm->r_end - max_seq;
8077 		if ((res1 >= (maxseg/8)) &&
8078 		    (res2 >= (maxseg/8))) {
8079 			/* No small pieces here */
8080 			can_split = 1;
8081 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8082 			/* We are under the limit */
8083 			can_split = 1;
8084 		}
8085 	}
8086 	/* Ok do we need to split this rsm? */
8087 	if (max_seq == rsm->r_start) {
8088 		/* It's this guy no split required */
8089 		nrsm = rsm;
8090 	} else if (max_seq == rsm->r_end) {
8091 		/* It's the next one no split required. */
8092 		nrsm = TAILQ_NEXT(rsm, r_next);
8093 		if (nrsm == NULL) {
8094 			/* Huh? */
8095 			return;
8096 		}
8097 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8098 		/* yep we need to split it */
8099 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8100 		if (nrsm == NULL) {
8101 			/* failed XXXrrs what can we do mark the whole? */
8102 			nrsm = rsm;
8103 			goto no_split;
8104 		}
8105 		/* Clone it */
8106 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8107 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8108 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8109 		if (rsm->r_in_tmap) {
8110 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8111 			nrsm->r_in_tmap = 1;
8112 		}
8113 	} else {
8114 		/*
8115 		 * Split not allowed just start here just
8116 		 * use this guy.
8117 		 */
8118 		nrsm = rsm;
8119 	}
8120 no_split:
8121 	BBR_STAT_INC(bbr_collapsed_win);
8122 	/* reuse fnd as a count */
8123 	fnd = 0;
8124 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8125 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8126 		fnd++;
8127 		bbr->rc_has_collapsed = 1;
8128 	}
8129 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8130 }
8131 
8132 static void
8133 bbr_un_collapse_window(struct tcp_bbr *bbr)
8134 {
8135 	struct bbr_sendmap *rsm;
8136 	int cleared = 0;
8137 
8138 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8139 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8140 			/* Clear the flag */
8141 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8142 			cleared++;
8143 		} else
8144 			break;
8145 	}
8146 	bbr_log_type_rwnd_collapse(bbr,
8147 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8148 	bbr->rc_has_collapsed = 0;
8149 }
8150 
8151 /*
8152  * Return value of 1, the TCB is unlocked and most
8153  * likely gone, return value of 0, the TCB is still
8154  * locked.
8155  */
8156 static int
8157 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8158     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8159     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8160 {
8161 	/*
8162 	 * Update window information. Don't look at window if no ACK: TAC's
8163 	 * send garbage on first SYN.
8164 	 */
8165 	uint16_t nsegs;
8166 	int32_t tfo_syn;
8167 	struct tcp_bbr *bbr;
8168 
8169 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8170 	INP_WLOCK_ASSERT(tp->t_inpcb);
8171 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8172 	if ((thflags & TH_ACK) &&
8173 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8174 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8175 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8176 		/* keep track of pure window updates */
8177 		if (tlen == 0 &&
8178 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8179 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8180 		tp->snd_wnd = tiwin;
8181 		tp->snd_wl1 = th->th_seq;
8182 		tp->snd_wl2 = th->th_ack;
8183 		if (tp->snd_wnd > tp->max_sndwnd)
8184 			tp->max_sndwnd = tp->snd_wnd;
8185 		bbr->r_wanted_output = 1;
8186 	} else if (thflags & TH_ACK) {
8187 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8188 			tp->snd_wnd = tiwin;
8189 			tp->snd_wl1 = th->th_seq;
8190 			tp->snd_wl2 = th->th_ack;
8191 		}
8192 	}
8193 	if (tp->snd_wnd < ctf_outstanding(tp))
8194 		/* The peer collapsed its window on us */
8195 		bbr_collapsed_window(bbr);
8196  	else if (bbr->rc_has_collapsed)
8197 		bbr_un_collapse_window(bbr);
8198 	/* Was persist timer active and now we have window space? */
8199 	if ((bbr->rc_in_persist != 0) &&
8200 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8201 				bbr_minseg(bbr)))) {
8202 		/*
8203 		 * Make the rate persist at end of persist mode if idle long
8204 		 * enough
8205 		 */
8206 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8207 
8208 		/* Make sure we output to start the timer */
8209 		bbr->r_wanted_output = 1;
8210 	}
8211 	/* Do we need to enter persist? */
8212 	if ((bbr->rc_in_persist == 0) &&
8213 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8214 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8215 	    (tp->snd_max == tp->snd_una) &&
8216 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8217 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8218 		/* No send window.. we must enter persist */
8219 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8220 	}
8221 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8222 		m_freem(m);
8223 		return (0);
8224 	}
8225 	/*
8226 	 * We don't support urgent data but
8227 	 * drag along the up just to make sure
8228 	 * if there is a stack switch no one
8229 	 * is surprised.
8230 	 */
8231 	tp->rcv_up = tp->rcv_nxt;
8232 	INP_WLOCK_ASSERT(tp->t_inpcb);
8233 
8234 	/*
8235 	 * Process the segment text, merging it into the TCP sequencing
8236 	 * queue, and arranging for acknowledgment of receipt if necessary.
8237 	 * This process logically involves adjusting tp->rcv_wnd as data is
8238 	 * presented to the user (this happens in tcp_usrreq.c, case
8239 	 * PRU_RCVD).  If a FIN has already been received on this connection
8240 	 * then we just ignore the text.
8241 	 */
8242 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8243 		   IS_FASTOPEN(tp->t_flags));
8244 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8245 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8246 		tcp_seq save_start = th->th_seq;
8247 		tcp_seq save_rnxt  = tp->rcv_nxt;
8248 		int     save_tlen  = tlen;
8249 
8250 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8251 		/*
8252 		 * Insert segment which includes th into TCP reassembly
8253 		 * queue with control block tp.  Set thflags to whether
8254 		 * reassembly now includes a segment with FIN.  This handles
8255 		 * the common case inline (segment is the next to be
8256 		 * received on an established connection, and the queue is
8257 		 * empty), avoiding linkage into and removal from the queue
8258 		 * and repetition of various conversions. Set DELACK for
8259 		 * segments received in order, but ack immediately when
8260 		 * segments are out of order (so fast retransmit can work).
8261 		 */
8262 		if (th->th_seq == tp->rcv_nxt &&
8263 		    SEGQ_EMPTY(tp) &&
8264 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8265 		    tfo_syn)) {
8266 #ifdef NETFLIX_SB_LIMITS
8267 			u_int mcnt, appended;
8268 
8269 			if (so->so_rcv.sb_shlim) {
8270 				mcnt = m_memcnt(m);
8271 				appended = 0;
8272 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8273 				    CFO_NOSLEEP, NULL) == false) {
8274 					counter_u64_add(tcp_sb_shlim_fails, 1);
8275 					m_freem(m);
8276 					return (0);
8277 				}
8278 			}
8279 
8280 #endif
8281 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8282 				bbr->bbr_segs_rcvd += max(1, nsegs);
8283 				tp->t_flags |= TF_DELACK;
8284 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8285 			} else {
8286 				bbr->r_wanted_output = 1;
8287 				tp->t_flags |= TF_ACKNOW;
8288 			}
8289 			tp->rcv_nxt += tlen;
8290 			if (tlen &&
8291 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8292 			    (tp->t_fbyte_in == 0)) {
8293 				tp->t_fbyte_in = ticks;
8294 				if (tp->t_fbyte_in == 0)
8295 					tp->t_fbyte_in = 1;
8296 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8297 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8298 			}
8299 			thflags = th->th_flags & TH_FIN;
8300 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8301 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8302 			SOCKBUF_LOCK(&so->so_rcv);
8303 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8304 				m_freem(m);
8305 			else
8306 #ifdef NETFLIX_SB_LIMITS
8307 				appended =
8308 #endif
8309 					sbappendstream_locked(&so->so_rcv, m, 0);
8310 			/* NB: sorwakeup_locked() does an implicit unlock. */
8311 			sorwakeup_locked(so);
8312 #ifdef NETFLIX_SB_LIMITS
8313 			if (so->so_rcv.sb_shlim && appended != mcnt)
8314 				counter_fo_release(so->so_rcv.sb_shlim,
8315 				    mcnt - appended);
8316 #endif
8317 
8318 		} else {
8319 			/*
8320 			 * XXX: Due to the header drop above "th" is
8321 			 * theoretically invalid by now.  Fortunately
8322 			 * m_adj() doesn't actually frees any mbufs when
8323 			 * trimming from the head.
8324 			 */
8325 			tcp_seq temp = save_start;
8326 
8327 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8328 			tp->t_flags |= TF_ACKNOW;
8329 			if (tp->t_flags & TF_WAKESOR) {
8330 				tp->t_flags &= ~TF_WAKESOR;
8331 				/* NB: sorwakeup_locked() does an implicit unlock. */
8332 				sorwakeup_locked(so);
8333 			}
8334 		}
8335 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8336 		    (save_tlen > 0) &&
8337 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8338 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8339 				/*
8340 				 * DSACK actually handled in the fastpath
8341 				 * above.
8342 				 */
8343 				tcp_update_sack_list(tp, save_start,
8344 				    save_start + save_tlen);
8345 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8346 				if ((tp->rcv_numsacks >= 1) &&
8347 				    (tp->sackblks[0].end == save_start)) {
8348 					/*
8349 					 * Partial overlap, recorded at todrop
8350 					 * above.
8351 					 */
8352 					tcp_update_sack_list(tp,
8353 					    tp->sackblks[0].start,
8354 					    tp->sackblks[0].end);
8355 				} else {
8356 					tcp_update_dsack_list(tp, save_start,
8357 					    save_start + save_tlen);
8358 				}
8359 			} else if (tlen >= save_tlen) {
8360 				/* Update of sackblks. */
8361 				tcp_update_dsack_list(tp, save_start,
8362 				    save_start + save_tlen);
8363 			} else if (tlen > 0) {
8364 				tcp_update_dsack_list(tp, save_start,
8365 				    save_start + tlen);
8366 			}
8367 		}
8368 	} else {
8369 		m_freem(m);
8370 		thflags &= ~TH_FIN;
8371 	}
8372 
8373 	/*
8374 	 * If FIN is received ACK the FIN and let the user know that the
8375 	 * connection is closing.
8376 	 */
8377 	if (thflags & TH_FIN) {
8378 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8379 			/* The socket upcall is handled by socantrcvmore. */
8380 			socantrcvmore(so);
8381 			/*
8382 			 * If connection is half-synchronized (ie NEEDSYN
8383 			 * flag on) then delay ACK, so it may be piggybacked
8384 			 * when SYN is sent. Otherwise, since we received a
8385 			 * FIN then no more input can be expected, send ACK
8386 			 * now.
8387 			 */
8388 			if (tp->t_flags & TF_NEEDSYN) {
8389 				tp->t_flags |= TF_DELACK;
8390 				bbr_timer_cancel(bbr,
8391 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8392 			} else {
8393 				tp->t_flags |= TF_ACKNOW;
8394 			}
8395 			tp->rcv_nxt++;
8396 		}
8397 		switch (tp->t_state) {
8398 			/*
8399 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8400 			 * CLOSE_WAIT state.
8401 			 */
8402 		case TCPS_SYN_RECEIVED:
8403 			tp->t_starttime = ticks;
8404 			/* FALLTHROUGH */
8405 		case TCPS_ESTABLISHED:
8406 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8407 			break;
8408 
8409 			/*
8410 			 * If still in FIN_WAIT_1 STATE FIN has not been
8411 			 * acked so enter the CLOSING state.
8412 			 */
8413 		case TCPS_FIN_WAIT_1:
8414 			tcp_state_change(tp, TCPS_CLOSING);
8415 			break;
8416 
8417 			/*
8418 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8419 			 * starting the time-wait timer, turning off the
8420 			 * other standard timers.
8421 			 */
8422 		case TCPS_FIN_WAIT_2:
8423 			bbr->rc_timer_first = 1;
8424 			bbr_timer_cancel(bbr,
8425 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8426 			INP_WLOCK_ASSERT(tp->t_inpcb);
8427 			tcp_twstart(tp);
8428 			return (1);
8429 		}
8430 	}
8431 	/*
8432 	 * Return any desired output.
8433 	 */
8434 	if ((tp->t_flags & TF_ACKNOW) ||
8435 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8436 		bbr->r_wanted_output = 1;
8437 	}
8438 	INP_WLOCK_ASSERT(tp->t_inpcb);
8439 	return (0);
8440 }
8441 
8442 /*
8443  * Here nothing is really faster, its just that we
8444  * have broken out the fast-data path also just like
8445  * the fast-ack. Return 1 if we processed the packet
8446  * return 0 if you need to take the "slow-path".
8447  */
8448 static int
8449 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8450     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8451     uint32_t tiwin, int32_t nxt_pkt)
8452 {
8453 	uint16_t nsegs;
8454 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8455 	struct tcp_bbr *bbr;
8456 #ifdef NETFLIX_SB_LIMITS
8457 	u_int mcnt, appended;
8458 #endif
8459 #ifdef TCPDEBUG
8460 	/*
8461 	 * The size of tcp_saveipgen must be the size of the max ip header,
8462 	 * now IPv6.
8463 	 */
8464 	u_char tcp_saveipgen[IP6_HDR_LEN];
8465 	struct tcphdr tcp_savetcp;
8466 	short ostate = 0;
8467 
8468 #endif
8469 	/* On the hpts and we would have called output */
8470 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8471 
8472 	/*
8473 	 * If last ACK falls within this segment's sequence numbers, record
8474 	 * the timestamp. NOTE that the test is modified according to the
8475 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8476 	 */
8477 	if (bbr->r_ctl.rc_resend != NULL) {
8478 		return (0);
8479 	}
8480 	if (tiwin && tiwin != tp->snd_wnd) {
8481 		return (0);
8482 	}
8483 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8484 		return (0);
8485 	}
8486 	if (__predict_false((to->to_flags & TOF_TS) &&
8487 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8488 		return (0);
8489 	}
8490 	if (__predict_false((th->th_ack != tp->snd_una))) {
8491 		return (0);
8492 	}
8493 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8494 		return (0);
8495 	}
8496 	if ((to->to_flags & TOF_TS) != 0 &&
8497 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8498 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8499 		tp->ts_recent = to->to_tsval;
8500 	}
8501 	/*
8502 	 * This is a pure, in-sequence data packet with nothing on the
8503 	 * reassembly queue and we have enough buffer space to take it.
8504 	 */
8505 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8506 
8507 #ifdef NETFLIX_SB_LIMITS
8508 	if (so->so_rcv.sb_shlim) {
8509 		mcnt = m_memcnt(m);
8510 		appended = 0;
8511 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8512 		    CFO_NOSLEEP, NULL) == false) {
8513 			counter_u64_add(tcp_sb_shlim_fails, 1);
8514 			m_freem(m);
8515 			return (1);
8516 		}
8517 	}
8518 #endif
8519 	/* Clean receiver SACK report if present */
8520 	if (tp->rcv_numsacks)
8521 		tcp_clean_sackreport(tp);
8522 	KMOD_TCPSTAT_INC(tcps_preddat);
8523 	tp->rcv_nxt += tlen;
8524 	if (tlen &&
8525 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8526 	    (tp->t_fbyte_in == 0)) {
8527 		tp->t_fbyte_in = ticks;
8528 		if (tp->t_fbyte_in == 0)
8529 			tp->t_fbyte_in = 1;
8530 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8531 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8532 	}
8533 	/*
8534 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8535 	 */
8536 	tp->snd_wl1 = th->th_seq;
8537 	/*
8538 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8539 	 */
8540 	tp->rcv_up = tp->rcv_nxt;
8541 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8542 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8543 #ifdef TCPDEBUG
8544 	if (so->so_options & SO_DEBUG)
8545 		tcp_trace(TA_INPUT, ostate, tp,
8546 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
8547 #endif
8548 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8549 
8550 	/* Add data to socket buffer. */
8551 	SOCKBUF_LOCK(&so->so_rcv);
8552 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8553 		m_freem(m);
8554 	} else {
8555 		/*
8556 		 * Set new socket buffer size. Give up when limit is
8557 		 * reached.
8558 		 */
8559 		if (newsize)
8560 			if (!sbreserve_locked(&so->so_rcv,
8561 			    newsize, so, NULL))
8562 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8563 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8564 
8565 #ifdef NETFLIX_SB_LIMITS
8566 		appended =
8567 #endif
8568 			sbappendstream_locked(&so->so_rcv, m, 0);
8569 		ctf_calc_rwin(so, tp);
8570 	}
8571 	/* NB: sorwakeup_locked() does an implicit unlock. */
8572 	sorwakeup_locked(so);
8573 #ifdef NETFLIX_SB_LIMITS
8574 	if (so->so_rcv.sb_shlim && mcnt != appended)
8575 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8576 #endif
8577 	if (DELAY_ACK(tp, bbr, nsegs)) {
8578 		bbr->bbr_segs_rcvd += max(1, nsegs);
8579 		tp->t_flags |= TF_DELACK;
8580 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8581 	} else {
8582 		bbr->r_wanted_output = 1;
8583 		tp->t_flags |= TF_ACKNOW;
8584 	}
8585 	return (1);
8586 }
8587 
8588 /*
8589  * This subfunction is used to try to highly optimize the
8590  * fast path. We again allow window updates that are
8591  * in sequence to remain in the fast-path. We also add
8592  * in the __predict's to attempt to help the compiler.
8593  * Note that if we return a 0, then we can *not* process
8594  * it and the caller should push the packet into the
8595  * slow-path. If we return 1, then all is well and
8596  * the packet is fully processed.
8597  */
8598 static int
8599 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8600     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8601     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8602 {
8603 	int32_t acked;
8604 	uint16_t nsegs;
8605 	uint32_t sack_changed;
8606 #ifdef TCPDEBUG
8607 	/*
8608 	 * The size of tcp_saveipgen must be the size of the max ip header,
8609 	 * now IPv6.
8610 	 */
8611 	u_char tcp_saveipgen[IP6_HDR_LEN];
8612 	struct tcphdr tcp_savetcp;
8613 	short ostate = 0;
8614 
8615 #endif
8616 	uint32_t prev_acked = 0;
8617 	struct tcp_bbr *bbr;
8618 
8619 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8620 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8621 		return (0);
8622 	}
8623 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8624 		/* Above what we have sent? */
8625 		return (0);
8626 	}
8627 	if (__predict_false(tiwin == 0)) {
8628 		/* zero window */
8629 		return (0);
8630 	}
8631 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8632 		/* We need a SYN or a FIN, unlikely.. */
8633 		return (0);
8634 	}
8635 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8636 		/* Timestamp is behind .. old ack with seq wrap? */
8637 		return (0);
8638 	}
8639 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8640 		/* Still recovering */
8641 		return (0);
8642 	}
8643 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8644 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8645 		/* We are retransmitting */
8646 		return (0);
8647 	}
8648 	if (__predict_false(bbr->rc_in_persist != 0)) {
8649 		/* In persist mode */
8650 		return (0);
8651 	}
8652 	if (bbr->r_ctl.rc_sacked) {
8653 		/* We have sack holes on our scoreboard */
8654 		return (0);
8655 	}
8656 	/* Ok if we reach here, we can process a fast-ack */
8657 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8658 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8659 	/*
8660 	 * We never detect loss in fast ack [we can't
8661 	 * have a sack and can't be in recovery so
8662 	 * we always pass 0 (nothing detected)].
8663 	 */
8664 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8665 	/* Did the window get updated? */
8666 	if (tiwin != tp->snd_wnd) {
8667 		tp->snd_wnd = tiwin;
8668 		tp->snd_wl1 = th->th_seq;
8669 		if (tp->snd_wnd > tp->max_sndwnd)
8670 			tp->max_sndwnd = tp->snd_wnd;
8671 	}
8672 	/* Do we need to exit persists? */
8673 	if ((bbr->rc_in_persist != 0) &&
8674 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8675 			       bbr_minseg(bbr)))) {
8676 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8677 		bbr->r_wanted_output = 1;
8678 	}
8679 	/* Do we need to enter persists? */
8680 	if ((bbr->rc_in_persist == 0) &&
8681 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8682 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8683 	    (tp->snd_max == tp->snd_una) &&
8684 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8685 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8686 		/* No send window.. we must enter persist */
8687 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8688 	}
8689 	/*
8690 	 * If last ACK falls within this segment's sequence numbers, record
8691 	 * the timestamp. NOTE that the test is modified according to the
8692 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8693 	 */
8694 	if ((to->to_flags & TOF_TS) != 0 &&
8695 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8696 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8697 		tp->ts_recent = to->to_tsval;
8698 	}
8699 	/*
8700 	 * This is a pure ack for outstanding data.
8701 	 */
8702 	KMOD_TCPSTAT_INC(tcps_predack);
8703 
8704 	/*
8705 	 * "bad retransmit" recovery.
8706 	 */
8707 	if (tp->t_flags & TF_PREVVALID) {
8708 		tp->t_flags &= ~TF_PREVVALID;
8709 		if (tp->t_rxtshift == 1 &&
8710 		    (int)(ticks - tp->t_badrxtwin) < 0)
8711 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8712 	}
8713 	/*
8714 	 * Recalculate the transmit timer / rtt.
8715 	 *
8716 	 * Some boxes send broken timestamp replies during the SYN+ACK
8717 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8718 	 * and blow up the retransmit timer.
8719 	 */
8720 	acked = BYTES_THIS_ACK(tp, th);
8721 
8722 #ifdef TCP_HHOOK
8723 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8724 	hhook_run_tcp_est_in(tp, th, to);
8725 #endif
8726 
8727 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8728 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8729 	sbdrop(&so->so_snd, acked);
8730 
8731 	if (SEQ_GT(th->th_ack, tp->snd_una))
8732 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8733 	tp->snd_una = th->th_ack;
8734 	if (tp->snd_wnd < ctf_outstanding(tp))
8735 		/* The peer collapsed its window on us */
8736 		bbr_collapsed_window(bbr);
8737 	else if (bbr->rc_has_collapsed)
8738 		bbr_un_collapse_window(bbr);
8739 
8740 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8741 		tp->snd_recover = tp->snd_una;
8742 	}
8743 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8744 	/*
8745 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8746 	 */
8747 	tp->snd_wl2 = th->th_ack;
8748 	m_freem(m);
8749 	/*
8750 	 * If all outstanding data are acked, stop retransmit timer,
8751 	 * otherwise restart timer using current (possibly backed-off)
8752 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8753 	 * If data are ready to send, let tcp_output decide between more
8754 	 * output or persist.
8755 	 */
8756 #ifdef TCPDEBUG
8757 	if (so->so_options & SO_DEBUG)
8758 		tcp_trace(TA_INPUT, ostate, tp,
8759 		    (void *)tcp_saveipgen,
8760 		    &tcp_savetcp, 0);
8761 #endif
8762 	/* Wake up the socket if we have room to write more */
8763 	sowwakeup(so);
8764 	if (tp->snd_una == tp->snd_max) {
8765 		/* Nothing left outstanding */
8766 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8767 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8768 			bbr->rc_tp->t_acktime = 0;
8769 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8770 		if (bbr->rc_in_persist == 0) {
8771 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8772 		}
8773 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8774 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8775 		/*
8776 		 * We invalidate the last ack here since we
8777 		 * don't want to transfer forward the time
8778 		 * for our sum's calculations.
8779 		 */
8780 		bbr->r_wanted_output = 1;
8781 	}
8782 	if (sbavail(&so->so_snd)) {
8783 		bbr->r_wanted_output = 1;
8784 	}
8785 	return (1);
8786 }
8787 
8788 /*
8789  * Return value of 1, the TCB is unlocked and most
8790  * likely gone, return value of 0, the TCB is still
8791  * locked.
8792  */
8793 static int
8794 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8795     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8796     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8797 {
8798 	int32_t todrop;
8799 	int32_t ourfinisacked = 0;
8800 	struct tcp_bbr *bbr;
8801 	int32_t ret_val = 0;
8802 
8803 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8804 	ctf_calc_rwin(so, tp);
8805 	/*
8806 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8807 	 * SYN, drop the input. if seg contains a RST, then drop the
8808 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8809 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8810 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8811 	 * not support ECN so we will not say we are capable. if SYN has
8812 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8813 	 * segment to be acked (eventually) continue processing rest of
8814 	 * data/controls, beginning with URG
8815 	 */
8816 	if ((thflags & TH_ACK) &&
8817 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8818 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8819 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8820 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8821 		return (1);
8822 	}
8823 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8824 		TCP_PROBE5(connect__refused, NULL, tp,
8825 		    mtod(m, const char *), tp, th);
8826 		tp = tcp_drop(tp, ECONNREFUSED);
8827 		ctf_do_drop(m, tp);
8828 		return (1);
8829 	}
8830 	if (thflags & TH_RST) {
8831 		ctf_do_drop(m, tp);
8832 		return (1);
8833 	}
8834 	if (!(thflags & TH_SYN)) {
8835 		ctf_do_drop(m, tp);
8836 		return (1);
8837 	}
8838 	tp->irs = th->th_seq;
8839 	tcp_rcvseqinit(tp);
8840 	if (thflags & TH_ACK) {
8841 		int tfo_partial = 0;
8842 
8843 		KMOD_TCPSTAT_INC(tcps_connects);
8844 		soisconnected(so);
8845 #ifdef MAC
8846 		mac_socketpeer_set_from_mbuf(m, so);
8847 #endif
8848 		/* Do window scaling on this connection? */
8849 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8850 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8851 			tp->rcv_scale = tp->request_r_scale;
8852 		}
8853 		tp->rcv_adv += min(tp->rcv_wnd,
8854 		    TCP_MAXWIN << tp->rcv_scale);
8855 		/*
8856 		 * If not all the data that was sent in the TFO SYN
8857 		 * has been acked, resend the remainder right away.
8858 		 */
8859 		if (IS_FASTOPEN(tp->t_flags) &&
8860 		    (tp->snd_una != tp->snd_max)) {
8861 			tp->snd_nxt = th->th_ack;
8862 			tfo_partial = 1;
8863 		}
8864 		/*
8865 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8866 		 * will be turned on later.
8867 		 */
8868 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8869 			bbr->bbr_segs_rcvd += 1;
8870 			tp->t_flags |= TF_DELACK;
8871 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8872 		} else {
8873 			bbr->r_wanted_output = 1;
8874 			tp->t_flags |= TF_ACKNOW;
8875 		}
8876 		if (SEQ_GT(th->th_ack, tp->iss)) {
8877 			/*
8878 			 * The SYN is acked
8879 			 * handle it specially.
8880 			 */
8881 			bbr_log_syn(tp, to);
8882 		}
8883 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8884 			/*
8885 			 * We advance snd_una for the
8886 			 * fast open case. If th_ack is
8887 			 * acknowledging data beyond
8888 			 * snd_una we can't just call
8889 			 * ack-processing since the
8890 			 * data stream in our send-map
8891 			 * will start at snd_una + 1 (one
8892 			 * beyond the SYN). If its just
8893 			 * equal we don't need to do that
8894 			 * and there is no send_map.
8895 			 */
8896 			tp->snd_una++;
8897 		}
8898 		/*
8899 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8900 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8901 		 */
8902 		tp->t_starttime = ticks;
8903 		if (tp->t_flags & TF_NEEDFIN) {
8904 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8905 			tp->t_flags &= ~TF_NEEDFIN;
8906 			thflags &= ~TH_SYN;
8907 		} else {
8908 			tcp_state_change(tp, TCPS_ESTABLISHED);
8909 			TCP_PROBE5(connect__established, NULL, tp,
8910 			    mtod(m, const char *), tp, th);
8911 			cc_conn_init(tp);
8912 		}
8913 	} else {
8914 		/*
8915 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8916 		 * open.  If segment contains CC option and there is a
8917 		 * cached CC, apply TAO test. If it succeeds, connection is *
8918 		 * half-synchronized. Otherwise, do 3-way handshake:
8919 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8920 		 * there was no CC option, clear cached CC value.
8921 		 */
8922 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
8923 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8924 	}
8925 	INP_WLOCK_ASSERT(tp->t_inpcb);
8926 	/*
8927 	 * Advance th->th_seq to correspond to first data byte. If data,
8928 	 * trim to stay within window, dropping FIN if necessary.
8929 	 */
8930 	th->th_seq++;
8931 	if (tlen > tp->rcv_wnd) {
8932 		todrop = tlen - tp->rcv_wnd;
8933 		m_adj(m, -todrop);
8934 		tlen = tp->rcv_wnd;
8935 		thflags &= ~TH_FIN;
8936 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8937 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8938 	}
8939 	tp->snd_wl1 = th->th_seq - 1;
8940 	tp->rcv_up = th->th_seq;
8941 	/*
8942 	 * Client side of transaction: already sent SYN and data. If the
8943 	 * remote host used T/TCP to validate the SYN, our data will be
8944 	 * ACK'd; if so, enter normal data segment processing in the middle
8945 	 * of step 5, ack processing. Otherwise, goto step 6.
8946 	 */
8947 	if (thflags & TH_ACK) {
8948 		if ((to->to_flags & TOF_TS) != 0) {
8949 			uint32_t t, rtt;
8950 
8951 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8952 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8953 				rtt = t - to->to_tsecr;
8954 				if (rtt == 0) {
8955 					rtt = 1;
8956 				}
8957 				rtt *= MS_IN_USEC;
8958 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8959 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8960 						       rtt, bbr->r_ctl.rc_rcvtime);
8961 			}
8962 		}
8963 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8964 			return (ret_val);
8965 		/* We may have changed to FIN_WAIT_1 above */
8966 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8967 			/*
8968 			 * In FIN_WAIT_1 STATE in addition to the processing
8969 			 * for the ESTABLISHED state if our FIN is now
8970 			 * acknowledged then enter FIN_WAIT_2.
8971 			 */
8972 			if (ourfinisacked) {
8973 				/*
8974 				 * If we can't receive any more data, then
8975 				 * closing user can proceed. Starting the
8976 				 * timer is contrary to the specification,
8977 				 * but if we don't get a FIN we'll hang
8978 				 * forever.
8979 				 *
8980 				 * XXXjl: we should release the tp also, and
8981 				 * use a compressed state.
8982 				 */
8983 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8984 					soisdisconnected(so);
8985 					tcp_timer_activate(tp, TT_2MSL,
8986 					    (tcp_fast_finwait2_recycle ?
8987 					    tcp_finwait2_timeout :
8988 					    TP_MAXIDLE(tp)));
8989 				}
8990 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8991 			}
8992 		}
8993 	}
8994 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8995 	    tiwin, thflags, nxt_pkt));
8996 }
8997 
8998 /*
8999  * Return value of 1, the TCB is unlocked and most
9000  * likely gone, return value of 0, the TCB is still
9001  * locked.
9002  */
9003 static int
9004 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
9005 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9006 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9007 {
9008 	int32_t ourfinisacked = 0;
9009 	int32_t ret_val;
9010 	struct tcp_bbr *bbr;
9011 
9012 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9013 	ctf_calc_rwin(so, tp);
9014 	if ((thflags & TH_ACK) &&
9015 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
9016 	     SEQ_GT(th->th_ack, tp->snd_max))) {
9017 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9018 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9019 		return (1);
9020 	}
9021 	if (IS_FASTOPEN(tp->t_flags)) {
9022 		/*
9023 		 * When a TFO connection is in SYN_RECEIVED, the only valid
9024 		 * packets are the initial SYN, a retransmit/copy of the
9025 		 * initial SYN (possibly with a subset of the original
9026 		 * data), a valid ACK, a FIN, or a RST.
9027 		 */
9028 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
9029 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9030 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9031 			return (1);
9032 		} else if (thflags & TH_SYN) {
9033 			/* non-initial SYN is ignored */
9034 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
9035 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
9036 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
9037 				ctf_do_drop(m, NULL);
9038 				return (0);
9039 			}
9040 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
9041 			ctf_do_drop(m, NULL);
9042 			return (0);
9043 		}
9044 	}
9045 	if ((thflags & TH_RST) ||
9046 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9047 		return (ctf_process_rst(m, th, so, tp));
9048 	/*
9049 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9050 	 * it's less than ts_recent, drop it.
9051 	 */
9052 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9053 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9054 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9055 			return (ret_val);
9056 	}
9057 	/*
9058 	 * In the SYN-RECEIVED state, validate that the packet belongs to
9059 	 * this connection before trimming the data to fit the receive
9060 	 * window.  Check the sequence number versus IRS since we know the
9061 	 * sequence numbers haven't wrapped.  This is a partial fix for the
9062 	 * "LAND" DoS attack.
9063 	 */
9064 	if (SEQ_LT(th->th_seq, tp->irs)) {
9065 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9066 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9067 		return (1);
9068 	}
9069 	INP_WLOCK_ASSERT(tp->t_inpcb);
9070 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9071 		return (ret_val);
9072 	}
9073 	/*
9074 	 * If last ACK falls within this segment's sequence numbers, record
9075 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9076 	 * from the latest proposal of the tcplw@cray.com list (Braden
9077 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9078 	 * with our earlier PAWS tests, so this check should be solely
9079 	 * predicated on the sequence space of this segment. 3) That we
9080 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9081 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9082 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9083 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9084 	 * p.869. In such cases, we can still calculate the RTT correctly
9085 	 * when RCV.NXT == Last.ACK.Sent.
9086 	 */
9087 	if ((to->to_flags & TOF_TS) != 0 &&
9088 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9089 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9090 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9091 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9092 		tp->ts_recent = to->to_tsval;
9093 	}
9094 	tp->snd_wnd = tiwin;
9095 	/*
9096 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9097 	 * is on (half-synchronized state), then queue data for later
9098 	 * processing; else drop segment and return.
9099 	 */
9100 	if ((thflags & TH_ACK) == 0) {
9101 		if (IS_FASTOPEN(tp->t_flags)) {
9102 			cc_conn_init(tp);
9103 		}
9104 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9105 					 tiwin, thflags, nxt_pkt));
9106 	}
9107 	KMOD_TCPSTAT_INC(tcps_connects);
9108 	soisconnected(so);
9109 	/* Do window scaling? */
9110 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9111 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9112 		tp->rcv_scale = tp->request_r_scale;
9113 	}
9114 	/*
9115 	 * ok for the first time in lets see if we can use the ts to figure
9116 	 * out what the initial RTT was.
9117 	 */
9118 	if ((to->to_flags & TOF_TS) != 0) {
9119 		uint32_t t, rtt;
9120 
9121 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9122 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9123 			rtt = t - to->to_tsecr;
9124 			if (rtt == 0) {
9125 				rtt = 1;
9126 			}
9127 			rtt *= MS_IN_USEC;
9128 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9129 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9130 		}
9131 	}
9132 	/* Drop off any SYN in the send map (probably not there)  */
9133 	if (thflags & TH_ACK)
9134 		bbr_log_syn(tp, to);
9135 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9136 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9137 		tp->t_tfo_pending = NULL;
9138 	}
9139 	/*
9140 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9141 	 * FIN-WAIT-1
9142 	 */
9143 	tp->t_starttime = ticks;
9144 	if (tp->t_flags & TF_NEEDFIN) {
9145 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9146 		tp->t_flags &= ~TF_NEEDFIN;
9147 	} else {
9148 		tcp_state_change(tp, TCPS_ESTABLISHED);
9149 		TCP_PROBE5(accept__established, NULL, tp,
9150 			   mtod(m, const char *), tp, th);
9151 		/*
9152 		 * TFO connections call cc_conn_init() during SYN
9153 		 * processing.  Calling it again here for such connections
9154 		 * is not harmless as it would undo the snd_cwnd reduction
9155 		 * that occurs when a TFO SYN|ACK is retransmitted.
9156 		 */
9157 		if (!IS_FASTOPEN(tp->t_flags))
9158 			cc_conn_init(tp);
9159 	}
9160 	/*
9161 	 * Account for the ACK of our SYN prior to
9162 	 * regular ACK processing below, except for
9163 	 * simultaneous SYN, which is handled later.
9164 	 */
9165 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9166 		tp->snd_una++;
9167 	/*
9168 	 * If segment contains data or ACK, will call tcp_reass() later; if
9169 	 * not, do so now to pass queued data to user.
9170 	 */
9171 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9172 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9173 			(struct mbuf *)0);
9174 		if (tp->t_flags & TF_WAKESOR) {
9175 			tp->t_flags &= ~TF_WAKESOR;
9176 			/* NB: sorwakeup_locked() does an implicit unlock. */
9177 			sorwakeup_locked(so);
9178 		}
9179 	}
9180 	tp->snd_wl1 = th->th_seq - 1;
9181 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9182 		return (ret_val);
9183 	}
9184 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9185 		/* We could have went to FIN_WAIT_1 (or EST) above */
9186 		/*
9187 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9188 		 * ESTABLISHED state if our FIN is now acknowledged then
9189 		 * enter FIN_WAIT_2.
9190 		 */
9191 		if (ourfinisacked) {
9192 			/*
9193 			 * If we can't receive any more data, then closing
9194 			 * user can proceed. Starting the timer is contrary
9195 			 * to the specification, but if we don't get a FIN
9196 			 * we'll hang forever.
9197 			 *
9198 			 * XXXjl: we should release the tp also, and use a
9199 			 * compressed state.
9200 			 */
9201 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9202 				soisdisconnected(so);
9203 				tcp_timer_activate(tp, TT_2MSL,
9204 						   (tcp_fast_finwait2_recycle ?
9205 						    tcp_finwait2_timeout :
9206 						    TP_MAXIDLE(tp)));
9207 			}
9208 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9209 		}
9210 	}
9211 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9212 				 tiwin, thflags, nxt_pkt));
9213 }
9214 
9215 /*
9216  * Return value of 1, the TCB is unlocked and most
9217  * likely gone, return value of 0, the TCB is still
9218  * locked.
9219  */
9220 static int
9221 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9222     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9223     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9224 {
9225 	struct tcp_bbr *bbr;
9226 	int32_t ret_val;
9227 
9228 	/*
9229 	 * Header prediction: check for the two common cases of a
9230 	 * uni-directional data xfer.  If the packet has no control flags,
9231 	 * is in-sequence, the window didn't change and we're not
9232 	 * retransmitting, it's a candidate.  If the length is zero and the
9233 	 * ack moved forward, we're the sender side of the xfer.  Just free
9234 	 * the data acked & wake any higher level process that was blocked
9235 	 * waiting for space.  If the length is non-zero and the ack didn't
9236 	 * move, we're the receiver side.  If we're getting packets in-order
9237 	 * (the reassembly queue is empty), add the data toc The socket
9238 	 * buffer and note that we need a delayed ack. Make sure that the
9239 	 * hidden state-flags are also off. Since we check for
9240 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9241 	 */
9242 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9243 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9244 		/*
9245 		 * If we have delived under 4 segments increase the initial
9246 		 * window if raised by the peer. We use this to determine
9247 		 * dynamic and static rwnd's at the end of a connection.
9248 		 */
9249 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9250 	}
9251 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9252 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9253 	    __predict_true(SEGQ_EMPTY(tp)) &&
9254 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9255 		if (tlen == 0) {
9256 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9257 			    tiwin, nxt_pkt, iptos)) {
9258 				return (0);
9259 			}
9260 		} else {
9261 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9262 			    tiwin, nxt_pkt)) {
9263 				return (0);
9264 			}
9265 		}
9266 	}
9267 	ctf_calc_rwin(so, tp);
9268 
9269 	if ((thflags & TH_RST) ||
9270 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9271 		return (ctf_process_rst(m, th, so, tp));
9272 	/*
9273 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9274 	 * synchronized state.
9275 	 */
9276 	if (thflags & TH_SYN) {
9277 		ctf_challenge_ack(m, th, tp, &ret_val);
9278 		return (ret_val);
9279 	}
9280 	/*
9281 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9282 	 * it's less than ts_recent, drop it.
9283 	 */
9284 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9285 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9286 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9287 			return (ret_val);
9288 	}
9289 	INP_WLOCK_ASSERT(tp->t_inpcb);
9290 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9291 		return (ret_val);
9292 	}
9293 	/*
9294 	 * If last ACK falls within this segment's sequence numbers, record
9295 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9296 	 * from the latest proposal of the tcplw@cray.com list (Braden
9297 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9298 	 * with our earlier PAWS tests, so this check should be solely
9299 	 * predicated on the sequence space of this segment. 3) That we
9300 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9301 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9302 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9303 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9304 	 * p.869. In such cases, we can still calculate the RTT correctly
9305 	 * when RCV.NXT == Last.ACK.Sent.
9306 	 */
9307 	if ((to->to_flags & TOF_TS) != 0 &&
9308 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9309 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9310 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9311 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9312 		tp->ts_recent = to->to_tsval;
9313 	}
9314 	/*
9315 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9316 	 * is on (half-synchronized state), then queue data for later
9317 	 * processing; else drop segment and return.
9318 	 */
9319 	if ((thflags & TH_ACK) == 0) {
9320 		if (tp->t_flags & TF_NEEDSYN) {
9321 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9322 			    tiwin, thflags, nxt_pkt));
9323 		} else if (tp->t_flags & TF_ACKNOW) {
9324 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9325 			bbr->r_wanted_output = 1;
9326 			return (ret_val);
9327 		} else {
9328 			ctf_do_drop(m, NULL);
9329 			return (0);
9330 		}
9331 	}
9332 	/*
9333 	 * Ack processing.
9334 	 */
9335 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9336 		return (ret_val);
9337 	}
9338 	if (sbavail(&so->so_snd)) {
9339 		if (ctf_progress_timeout_check(tp, true)) {
9340 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9341 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9342 			return (1);
9343 		}
9344 	}
9345 	/* State changes only happen in bbr_process_data() */
9346 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9347 	    tiwin, thflags, nxt_pkt));
9348 }
9349 
9350 /*
9351  * Return value of 1, the TCB is unlocked and most
9352  * likely gone, return value of 0, the TCB is still
9353  * locked.
9354  */
9355 static int
9356 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9357     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9358     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9359 {
9360 	struct tcp_bbr *bbr;
9361 	int32_t ret_val;
9362 
9363 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9364 	ctf_calc_rwin(so, tp);
9365 	if ((thflags & TH_RST) ||
9366 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9367 		return (ctf_process_rst(m, th, so, tp));
9368 	/*
9369 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9370 	 * synchronized state.
9371 	 */
9372 	if (thflags & TH_SYN) {
9373 		ctf_challenge_ack(m, th, tp, &ret_val);
9374 		return (ret_val);
9375 	}
9376 	/*
9377 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9378 	 * it's less than ts_recent, drop it.
9379 	 */
9380 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9381 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9382 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9383 			return (ret_val);
9384 	}
9385 	INP_WLOCK_ASSERT(tp->t_inpcb);
9386 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9387 		return (ret_val);
9388 	}
9389 	/*
9390 	 * If last ACK falls within this segment's sequence numbers, record
9391 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9392 	 * from the latest proposal of the tcplw@cray.com list (Braden
9393 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9394 	 * with our earlier PAWS tests, so this check should be solely
9395 	 * predicated on the sequence space of this segment. 3) That we
9396 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9397 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9398 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9399 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9400 	 * p.869. In such cases, we can still calculate the RTT correctly
9401 	 * when RCV.NXT == Last.ACK.Sent.
9402 	 */
9403 	if ((to->to_flags & TOF_TS) != 0 &&
9404 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9405 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9406 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9407 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9408 		tp->ts_recent = to->to_tsval;
9409 	}
9410 	/*
9411 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9412 	 * is on (half-synchronized state), then queue data for later
9413 	 * processing; else drop segment and return.
9414 	 */
9415 	if ((thflags & TH_ACK) == 0) {
9416 		if (tp->t_flags & TF_NEEDSYN) {
9417 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9418 			    tiwin, thflags, nxt_pkt));
9419 		} else if (tp->t_flags & TF_ACKNOW) {
9420 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9421 			bbr->r_wanted_output = 1;
9422 			return (ret_val);
9423 		} else {
9424 			ctf_do_drop(m, NULL);
9425 			return (0);
9426 		}
9427 	}
9428 	/*
9429 	 * Ack processing.
9430 	 */
9431 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9432 		return (ret_val);
9433 	}
9434 	if (sbavail(&so->so_snd)) {
9435 		if (ctf_progress_timeout_check(tp, true)) {
9436 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9437 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9438 			return (1);
9439 		}
9440 	}
9441 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9442 	    tiwin, thflags, nxt_pkt));
9443 }
9444 
9445 static int
9446 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9447     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9448 {
9449 
9450 	if (bbr->rc_allow_data_af_clo == 0) {
9451 close_now:
9452 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9453 		/* tcp_close will kill the inp pre-log the Reset */
9454 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9455 		tp = tcp_close(tp);
9456 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9457 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9458 		return (1);
9459 	}
9460 	if (sbavail(&so->so_snd) == 0)
9461 		goto close_now;
9462 	/* Ok we allow data that is ignored and a followup reset */
9463 	tp->rcv_nxt = th->th_seq + *tlen;
9464 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9465 	bbr->r_wanted_output = 1;
9466 	*tlen = 0;
9467 	return (0);
9468 }
9469 
9470 /*
9471  * Return value of 1, the TCB is unlocked and most
9472  * likely gone, return value of 0, the TCB is still
9473  * locked.
9474  */
9475 static int
9476 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9477     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9478     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9479 {
9480 	int32_t ourfinisacked = 0;
9481 	int32_t ret_val;
9482 	struct tcp_bbr *bbr;
9483 
9484 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9485 	ctf_calc_rwin(so, tp);
9486 	if ((thflags & TH_RST) ||
9487 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9488 		return (ctf_process_rst(m, th, so, tp));
9489 	/*
9490 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9491 	 * synchronized state.
9492 	 */
9493 	if (thflags & TH_SYN) {
9494 		ctf_challenge_ack(m, th, tp, &ret_val);
9495 		return (ret_val);
9496 	}
9497 	/*
9498 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9499 	 * it's less than ts_recent, drop it.
9500 	 */
9501 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9502 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9503 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9504 			return (ret_val);
9505 	}
9506 	INP_WLOCK_ASSERT(tp->t_inpcb);
9507 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9508 		return (ret_val);
9509 	}
9510 	/*
9511 	 * If new data are received on a connection after the user processes
9512 	 * are gone, then RST the other end.
9513 	 */
9514 	if ((so->so_state & SS_NOFDREF) && tlen) {
9515 		/*
9516 		 * We call a new function now so we might continue and setup
9517 		 * to reset at all data being ack'd.
9518 		 */
9519 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9520 			return (1);
9521 	}
9522 	/*
9523 	 * If last ACK falls within this segment's sequence numbers, record
9524 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9525 	 * from the latest proposal of the tcplw@cray.com list (Braden
9526 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9527 	 * with our earlier PAWS tests, so this check should be solely
9528 	 * predicated on the sequence space of this segment. 3) That we
9529 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9530 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9531 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9532 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9533 	 * p.869. In such cases, we can still calculate the RTT correctly
9534 	 * when RCV.NXT == Last.ACK.Sent.
9535 	 */
9536 	if ((to->to_flags & TOF_TS) != 0 &&
9537 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9538 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9539 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9540 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9541 		tp->ts_recent = to->to_tsval;
9542 	}
9543 	/*
9544 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9545 	 * is on (half-synchronized state), then queue data for later
9546 	 * processing; else drop segment and return.
9547 	 */
9548 	if ((thflags & TH_ACK) == 0) {
9549 		if (tp->t_flags & TF_NEEDSYN) {
9550 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9551 			    tiwin, thflags, nxt_pkt));
9552 		} else if (tp->t_flags & TF_ACKNOW) {
9553 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9554 			bbr->r_wanted_output = 1;
9555 			return (ret_val);
9556 		} else {
9557 			ctf_do_drop(m, NULL);
9558 			return (0);
9559 		}
9560 	}
9561 	/*
9562 	 * Ack processing.
9563 	 */
9564 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9565 		return (ret_val);
9566 	}
9567 	if (ourfinisacked) {
9568 		/*
9569 		 * If we can't receive any more data, then closing user can
9570 		 * proceed. Starting the timer is contrary to the
9571 		 * specification, but if we don't get a FIN we'll hang
9572 		 * forever.
9573 		 *
9574 		 * XXXjl: we should release the tp also, and use a
9575 		 * compressed state.
9576 		 */
9577 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9578 			soisdisconnected(so);
9579 			tcp_timer_activate(tp, TT_2MSL,
9580 			    (tcp_fast_finwait2_recycle ?
9581 			    tcp_finwait2_timeout :
9582 			    TP_MAXIDLE(tp)));
9583 		}
9584 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9585 	}
9586 	if (sbavail(&so->so_snd)) {
9587 		if (ctf_progress_timeout_check(tp, true)) {
9588 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9589 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9590 			return (1);
9591 		}
9592 	}
9593 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9594 	    tiwin, thflags, nxt_pkt));
9595 }
9596 
9597 /*
9598  * Return value of 1, the TCB is unlocked and most
9599  * likely gone, return value of 0, the TCB is still
9600  * locked.
9601  */
9602 static int
9603 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9604     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9605     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9606 {
9607 	int32_t ourfinisacked = 0;
9608 	int32_t ret_val;
9609 	struct tcp_bbr *bbr;
9610 
9611 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9612 	ctf_calc_rwin(so, tp);
9613 	if ((thflags & TH_RST) ||
9614 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9615 		return (ctf_process_rst(m, th, so, tp));
9616 	/*
9617 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9618 	 * synchronized state.
9619 	 */
9620 	if (thflags & TH_SYN) {
9621 		ctf_challenge_ack(m, th, tp, &ret_val);
9622 		return (ret_val);
9623 	}
9624 	/*
9625 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9626 	 * it's less than ts_recent, drop it.
9627 	 */
9628 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9629 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9630 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9631 			return (ret_val);
9632 	}
9633 	INP_WLOCK_ASSERT(tp->t_inpcb);
9634 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9635 		return (ret_val);
9636 	}
9637 	/*
9638 	 * If new data are received on a connection after the user processes
9639 	 * are gone, then RST the other end.
9640 	 */
9641 	if ((so->so_state & SS_NOFDREF) && tlen) {
9642 		/*
9643 		 * We call a new function now so we might continue and setup
9644 		 * to reset at all data being ack'd.
9645 		 */
9646 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9647 			return (1);
9648 	}
9649 	/*
9650 	 * If last ACK falls within this segment's sequence numbers, record
9651 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9652 	 * from the latest proposal of the tcplw@cray.com list (Braden
9653 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9654 	 * with our earlier PAWS tests, so this check should be solely
9655 	 * predicated on the sequence space of this segment. 3) That we
9656 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9657 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9658 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9659 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9660 	 * p.869. In such cases, we can still calculate the RTT correctly
9661 	 * when RCV.NXT == Last.ACK.Sent.
9662 	 */
9663 	if ((to->to_flags & TOF_TS) != 0 &&
9664 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9665 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9666 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9667 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9668 		tp->ts_recent = to->to_tsval;
9669 	}
9670 	/*
9671 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9672 	 * is on (half-synchronized state), then queue data for later
9673 	 * processing; else drop segment and return.
9674 	 */
9675 	if ((thflags & TH_ACK) == 0) {
9676 		if (tp->t_flags & TF_NEEDSYN) {
9677 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9678 			    tiwin, thflags, nxt_pkt));
9679 		} else if (tp->t_flags & TF_ACKNOW) {
9680 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9681 			bbr->r_wanted_output = 1;
9682 			return (ret_val);
9683 		} else {
9684 			ctf_do_drop(m, NULL);
9685 			return (0);
9686 		}
9687 	}
9688 	/*
9689 	 * Ack processing.
9690 	 */
9691 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9692 		return (ret_val);
9693 	}
9694 	if (ourfinisacked) {
9695 		tcp_twstart(tp);
9696 		m_freem(m);
9697 		return (1);
9698 	}
9699 	if (sbavail(&so->so_snd)) {
9700 		if (ctf_progress_timeout_check(tp, true)) {
9701 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9702 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9703 			return (1);
9704 		}
9705 	}
9706 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9707 	    tiwin, thflags, nxt_pkt));
9708 }
9709 
9710 /*
9711  * Return value of 1, the TCB is unlocked and most
9712  * likely gone, return value of 0, the TCB is still
9713  * locked.
9714  */
9715 static int
9716 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9717     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9718     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9719 {
9720 	int32_t ourfinisacked = 0;
9721 	int32_t ret_val;
9722 	struct tcp_bbr *bbr;
9723 
9724 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9725 	ctf_calc_rwin(so, tp);
9726 	if ((thflags & TH_RST) ||
9727 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9728 		return (ctf_process_rst(m, th, so, tp));
9729 	/*
9730 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9731 	 * synchronized state.
9732 	 */
9733 	if (thflags & TH_SYN) {
9734 		ctf_challenge_ack(m, th, tp, &ret_val);
9735 		return (ret_val);
9736 	}
9737 	/*
9738 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9739 	 * it's less than ts_recent, drop it.
9740 	 */
9741 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9742 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9743 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9744 			return (ret_val);
9745 	}
9746 	INP_WLOCK_ASSERT(tp->t_inpcb);
9747 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9748 		return (ret_val);
9749 	}
9750 	/*
9751 	 * If new data are received on a connection after the user processes
9752 	 * are gone, then RST the other end.
9753 	 */
9754 	if ((so->so_state & SS_NOFDREF) && tlen) {
9755 		/*
9756 		 * We call a new function now so we might continue and setup
9757 		 * to reset at all data being ack'd.
9758 		 */
9759 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9760 			return (1);
9761 	}
9762 	/*
9763 	 * If last ACK falls within this segment's sequence numbers, record
9764 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9765 	 * from the latest proposal of the tcplw@cray.com list (Braden
9766 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9767 	 * with our earlier PAWS tests, so this check should be solely
9768 	 * predicated on the sequence space of this segment. 3) That we
9769 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9770 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9771 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9772 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9773 	 * p.869. In such cases, we can still calculate the RTT correctly
9774 	 * when RCV.NXT == Last.ACK.Sent.
9775 	 */
9776 	if ((to->to_flags & TOF_TS) != 0 &&
9777 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9778 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9779 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9780 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9781 		tp->ts_recent = to->to_tsval;
9782 	}
9783 	/*
9784 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9785 	 * is on (half-synchronized state), then queue data for later
9786 	 * processing; else drop segment and return.
9787 	 */
9788 	if ((thflags & TH_ACK) == 0) {
9789 		if (tp->t_flags & TF_NEEDSYN) {
9790 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9791 			    tiwin, thflags, nxt_pkt));
9792 		} else if (tp->t_flags & TF_ACKNOW) {
9793 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9794 			bbr->r_wanted_output = 1;
9795 			return (ret_val);
9796 		} else {
9797 			ctf_do_drop(m, NULL);
9798 			return (0);
9799 		}
9800 	}
9801 	/*
9802 	 * case TCPS_LAST_ACK: Ack processing.
9803 	 */
9804 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9805 		return (ret_val);
9806 	}
9807 	if (ourfinisacked) {
9808 		tp = tcp_close(tp);
9809 		ctf_do_drop(m, tp);
9810 		return (1);
9811 	}
9812 	if (sbavail(&so->so_snd)) {
9813 		if (ctf_progress_timeout_check(tp, true)) {
9814 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9815 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9816 			return (1);
9817 		}
9818 	}
9819 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9820 	    tiwin, thflags, nxt_pkt));
9821 }
9822 
9823 /*
9824  * Return value of 1, the TCB is unlocked and most
9825  * likely gone, return value of 0, the TCB is still
9826  * locked.
9827  */
9828 static int
9829 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9830     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9831     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9832 {
9833 	int32_t ourfinisacked = 0;
9834 	int32_t ret_val;
9835 	struct tcp_bbr *bbr;
9836 
9837 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9838 	ctf_calc_rwin(so, tp);
9839 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9840 	if ((thflags & TH_RST) ||
9841 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9842 		return (ctf_process_rst(m, th, so, tp));
9843 
9844 	/*
9845 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9846 	 * synchronized state.
9847 	 */
9848 	if (thflags & TH_SYN) {
9849 		ctf_challenge_ack(m, th, tp, &ret_val);
9850 		return (ret_val);
9851 	}
9852 	INP_WLOCK_ASSERT(tp->t_inpcb);
9853 	/*
9854 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9855 	 * it's less than ts_recent, drop it.
9856 	 */
9857 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9858 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9859 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9860 			return (ret_val);
9861 	}
9862 	INP_WLOCK_ASSERT(tp->t_inpcb);
9863 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9864 		return (ret_val);
9865 	}
9866 	/*
9867 	 * If new data are received on a connection after the user processes
9868 	 * are gone, then we may RST the other end depending on the outcome
9869 	 * of bbr_check_data_after_close.
9870 	 */
9871 	if ((so->so_state & SS_NOFDREF) &&
9872 	    tlen) {
9873 		/*
9874 		 * We call a new function now so we might continue and setup
9875 		 * to reset at all data being ack'd.
9876 		 */
9877 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9878 			return (1);
9879 	}
9880 	INP_WLOCK_ASSERT(tp->t_inpcb);
9881 	/*
9882 	 * If last ACK falls within this segment's sequence numbers, record
9883 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9884 	 * from the latest proposal of the tcplw@cray.com list (Braden
9885 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9886 	 * with our earlier PAWS tests, so this check should be solely
9887 	 * predicated on the sequence space of this segment. 3) That we
9888 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9889 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9890 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9891 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9892 	 * p.869. In such cases, we can still calculate the RTT correctly
9893 	 * when RCV.NXT == Last.ACK.Sent.
9894 	 */
9895 	INP_WLOCK_ASSERT(tp->t_inpcb);
9896 	if ((to->to_flags & TOF_TS) != 0 &&
9897 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9898 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9899 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9900 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9901 		tp->ts_recent = to->to_tsval;
9902 	}
9903 	/*
9904 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9905 	 * is on (half-synchronized state), then queue data for later
9906 	 * processing; else drop segment and return.
9907 	 */
9908 	if ((thflags & TH_ACK) == 0) {
9909 		if (tp->t_flags & TF_NEEDSYN) {
9910 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9911 			    tiwin, thflags, nxt_pkt));
9912 		} else if (tp->t_flags & TF_ACKNOW) {
9913 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9914 			bbr->r_wanted_output = 1;
9915 			return (ret_val);
9916 		} else {
9917 			ctf_do_drop(m, NULL);
9918 			return (0);
9919 		}
9920 	}
9921 	/*
9922 	 * Ack processing.
9923 	 */
9924 	INP_WLOCK_ASSERT(tp->t_inpcb);
9925 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9926 		return (ret_val);
9927 	}
9928 	if (sbavail(&so->so_snd)) {
9929 		if (ctf_progress_timeout_check(tp, true)) {
9930 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9931 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9932 			return (1);
9933 		}
9934 	}
9935 	INP_WLOCK_ASSERT(tp->t_inpcb);
9936 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9937 	    tiwin, thflags, nxt_pkt));
9938 }
9939 
9940 static void
9941 bbr_stop_all_timers(struct tcpcb *tp)
9942 {
9943 	struct tcp_bbr *bbr;
9944 
9945 	/*
9946 	 * Assure no timers are running.
9947 	 */
9948 	if (tcp_timer_active(tp, TT_PERSIST)) {
9949 		/* We enter in persists, set the flag appropriately */
9950 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9951 		bbr->rc_in_persist = 1;
9952 	}
9953 	tcp_timer_suspend(tp, TT_PERSIST);
9954 	tcp_timer_suspend(tp, TT_REXMT);
9955 	tcp_timer_suspend(tp, TT_KEEP);
9956 	tcp_timer_suspend(tp, TT_DELACK);
9957 }
9958 
9959 static void
9960 bbr_google_mode_on(struct tcp_bbr *bbr)
9961 {
9962 	bbr->rc_use_google = 1;
9963 	bbr->rc_no_pacing = 0;
9964 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9965 	bbr->r_use_policer = bbr_policer_detection_enabled;
9966 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9967 	bbr->bbr_use_rack_cheat = 0;
9968 	bbr->r_ctl.rc_incr_tmrs = 0;
9969 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9970 	bbr->r_ctl.rc_inc_ip_oh = 0;
9971 	bbr->r_ctl.rc_inc_enet_oh = 0;
9972 	reset_time(&bbr->r_ctl.rc_delrate,
9973 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9974 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9975 			 (11 * USECS_IN_SECOND));
9976 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9977 }
9978 
9979 static void
9980 bbr_google_mode_off(struct tcp_bbr *bbr)
9981 {
9982 	bbr->rc_use_google = 0;
9983 	bbr->r_ctl.bbr_google_discount = 0;
9984 	bbr->no_pacing_until = bbr_no_pacing_until;
9985 	bbr->r_use_policer = 0;
9986 	if (bbr->no_pacing_until)
9987 		bbr->rc_no_pacing = 1;
9988 	else
9989 		bbr->rc_no_pacing = 0;
9990 	if (bbr_use_rack_resend_cheat)
9991 		bbr->bbr_use_rack_cheat = 1;
9992 	else
9993 		bbr->bbr_use_rack_cheat = 0;
9994 	if (bbr_incr_timers)
9995 		bbr->r_ctl.rc_incr_tmrs = 1;
9996 	else
9997 		bbr->r_ctl.rc_incr_tmrs = 0;
9998 	if (bbr_include_tcp_oh)
9999 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10000 	else
10001 		bbr->r_ctl.rc_inc_tcp_oh = 0;
10002 	if (bbr_include_ip_oh)
10003 		bbr->r_ctl.rc_inc_ip_oh = 1;
10004 	else
10005 		bbr->r_ctl.rc_inc_ip_oh = 0;
10006 	if (bbr_include_enet_oh)
10007 		bbr->r_ctl.rc_inc_enet_oh = 1;
10008 	else
10009 		bbr->r_ctl.rc_inc_enet_oh = 0;
10010 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10011 	reset_time(&bbr->r_ctl.rc_delrate,
10012 		   bbr_num_pktepo_for_del_limit);
10013 	reset_time_small(&bbr->r_ctl.rc_rttprop,
10014 			 (bbr_filter_len_sec * USECS_IN_SECOND));
10015 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
10016 }
10017 /*
10018  * Return 0 on success, non-zero on failure
10019  * which indicates the error (usually no memory).
10020  */
10021 static int
10022 bbr_init(struct tcpcb *tp)
10023 {
10024 	struct tcp_bbr *bbr = NULL;
10025 	struct inpcb *inp;
10026 	uint32_t cts;
10027 
10028 	tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
10029 	if (tp->t_fb_ptr == NULL) {
10030 		/*
10031 		 * We need to allocate memory but cant. The INP and INP_INFO
10032 		 * locks and they are recusive (happens during setup. So a
10033 		 * scheme to drop the locks fails :(
10034 		 *
10035 		 */
10036 		return (ENOMEM);
10037 	}
10038 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10039 	bbr->rtt_valid = 0;
10040 	inp = tp->t_inpcb;
10041 	inp->inp_flags2 |= INP_CANNOT_DO_ECN;
10042 	inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
10043 	TAILQ_INIT(&bbr->r_ctl.rc_map);
10044 	TAILQ_INIT(&bbr->r_ctl.rc_free);
10045 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
10046 	bbr->rc_tp = tp;
10047 	if (tp->t_inpcb) {
10048 		bbr->rc_inp = tp->t_inpcb;
10049 	}
10050 	cts = tcp_get_usecs(&bbr->rc_tv);
10051 	tp->t_acktime = 0;
10052 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
10053 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
10054 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
10055 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
10056 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
10057 	bbr->r_ctl.rc_min_to = bbr_min_to;
10058 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
10059 	bbr->r_ctl.bbr_lost_at_state = 0;
10060 	bbr->r_ctl.rc_lost_at_startup = 0;
10061 	bbr->rc_all_timers_stopped = 0;
10062 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10063 	bbr->r_ctl.rc_pkt_epoch_del = 0;
10064 	bbr->r_ctl.rc_pkt_epoch = 0;
10065 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10066 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10067 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10068 	bbr->r_ctl.rc_went_idle_time = cts;
10069 	bbr->rc_pacer_started = cts;
10070 	bbr->r_ctl.rc_pkt_epoch_time = cts;
10071 	bbr->r_ctl.rc_rcvtime = cts;
10072 	bbr->r_ctl.rc_bbr_state_time = cts;
10073 	bbr->r_ctl.rc_del_time = cts;
10074 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10075 	bbr->r_ctl.last_in_probertt = cts;
10076 	bbr->skip_gain = 0;
10077 	bbr->gain_is_limited = 0;
10078 	bbr->no_pacing_until = bbr_no_pacing_until;
10079 	if (bbr->no_pacing_until)
10080 		bbr->rc_no_pacing = 1;
10081 	if (bbr_use_google_algo) {
10082 		bbr->rc_no_pacing = 0;
10083 		bbr->rc_use_google = 1;
10084 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10085 		bbr->r_use_policer = bbr_policer_detection_enabled;
10086 	} else {
10087 		bbr->rc_use_google = 0;
10088 		bbr->r_ctl.bbr_google_discount = 0;
10089 		bbr->r_use_policer = 0;
10090 	}
10091 	if (bbr_ts_limiting)
10092 		bbr->rc_use_ts_limit = 1;
10093 	else
10094 		bbr->rc_use_ts_limit = 0;
10095 	if (bbr_ts_can_raise)
10096 		bbr->ts_can_raise = 1;
10097 	else
10098 		bbr->ts_can_raise = 0;
10099 	if (V_tcp_delack_enabled == 1)
10100 		tp->t_delayed_ack = 2;
10101 	else if (V_tcp_delack_enabled == 0)
10102 		tp->t_delayed_ack = 0;
10103 	else if (V_tcp_delack_enabled < 100)
10104 		tp->t_delayed_ack = V_tcp_delack_enabled;
10105 	else
10106 		tp->t_delayed_ack = 2;
10107 	if (bbr->rc_use_google == 0)
10108 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10109 	else
10110 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10111 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10112 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10113 	bbr->rc_init_win = bbr_def_init_win;
10114 	if (tp->t_flags & TF_REQ_TSTMP)
10115 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10116 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10117 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10118 	bbr->r_init_rtt = 1;
10119 
10120 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10121 	if (bbr_allow_hdwr_pacing)
10122 		bbr->bbr_hdw_pace_ena = 1;
10123 	else
10124 		bbr->bbr_hdw_pace_ena = 0;
10125 	if (bbr_sends_full_iwnd)
10126 		bbr->bbr_init_win_cheat = 1;
10127 	else
10128 		bbr->bbr_init_win_cheat = 0;
10129 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10130 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10131 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10132 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10133 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10134 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10135 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10136 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10137 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10138 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10139 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10140 	bbr->r_ctl.rc_rtt_shrinks = cts;
10141 	if (bbr->rc_use_google) {
10142 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10143 				  FILTER_TYPE_MAX,
10144 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10145 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10146 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10147 	} else {
10148 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10149 				  FILTER_TYPE_MAX,
10150 				  bbr_num_pktepo_for_del_limit);
10151 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10152 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10153 	}
10154 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10155 	if (bbr_uses_idle_restart)
10156 		bbr->rc_use_idle_restart = 1;
10157 	else
10158 		bbr->rc_use_idle_restart = 0;
10159 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10160 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10161 	if (bbr_resends_use_tso)
10162 		bbr->rc_resends_use_tso = 1;
10163 #ifdef NETFLIX_PEAKRATE
10164 	tp->t_peakrate_thr = tp->t_maxpeakrate;
10165 #endif
10166 	if (tp->snd_una != tp->snd_max) {
10167 		/* Create a send map for the current outstanding data */
10168 		struct bbr_sendmap *rsm;
10169 
10170 		rsm = bbr_alloc(bbr);
10171 		if (rsm == NULL) {
10172 			uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10173 			tp->t_fb_ptr = NULL;
10174 			return (ENOMEM);
10175 		}
10176 		rsm->r_rtt_not_allowed = 1;
10177 		rsm->r_tim_lastsent[0] = cts;
10178 		rsm->r_rtr_cnt = 1;
10179 		rsm->r_rtr_bytes = 0;
10180 		rsm->r_start = tp->snd_una;
10181 		rsm->r_end = tp->snd_max;
10182 		rsm->r_dupack = 0;
10183 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10184 		rsm->r_ts_valid = 0;
10185 		rsm->r_del_ack_ts = tp->ts_recent;
10186 		rsm->r_del_time = cts;
10187 		if (bbr->r_ctl.r_app_limited_until)
10188 			rsm->r_app_limited = 1;
10189 		else
10190 			rsm->r_app_limited = 0;
10191 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10192 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10193 		rsm->r_in_tmap = 1;
10194 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10195 			rsm->r_bbr_state = bbr_state_val(bbr);
10196 		else
10197 			rsm->r_bbr_state = 8;
10198 	}
10199 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10200 		bbr->bbr_use_rack_cheat = 1;
10201 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10202 		bbr->r_ctl.rc_incr_tmrs = 1;
10203 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10204 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10205 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10206 		bbr->r_ctl.rc_inc_ip_oh = 1;
10207 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10208 		bbr->r_ctl.rc_inc_enet_oh = 1;
10209 
10210 	bbr_log_type_statechange(bbr, cts, __LINE__);
10211 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10212 	    (tp->t_srtt)) {
10213 		uint32_t rtt;
10214 
10215 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10216 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10217 	}
10218 	/* announce the settings and state */
10219 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10220 	tcp_bbr_tso_size_check(bbr, cts);
10221 	/*
10222 	 * Now call the generic function to start a timer. This will place
10223 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10224 	 * flags.
10225 	 */
10226 	bbr_stop_all_timers(tp);
10227 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10228 	return (0);
10229 }
10230 
10231 /*
10232  * Return 0 if we can accept the connection. Return
10233  * non-zero if we can't handle the connection. A EAGAIN
10234  * means you need to wait until the connection is up.
10235  * a EADDRNOTAVAIL means we can never handle the connection
10236  * (no SACK).
10237  */
10238 static int
10239 bbr_handoff_ok(struct tcpcb *tp)
10240 {
10241 	if ((tp->t_state == TCPS_CLOSED) ||
10242 	    (tp->t_state == TCPS_LISTEN)) {
10243 		/* Sure no problem though it may not stick */
10244 		return (0);
10245 	}
10246 	if ((tp->t_state == TCPS_SYN_SENT) ||
10247 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10248 		/*
10249 		 * We really don't know you have to get to ESTAB or beyond
10250 		 * to tell.
10251 		 */
10252 		return (EAGAIN);
10253 	}
10254 	if (tp->t_flags & TF_SENTFIN)
10255 		return (EINVAL);
10256 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10257 		return (0);
10258 	}
10259 	/*
10260 	 * If we reach here we don't do SACK on this connection so we can
10261 	 * never do rack.
10262 	 */
10263 	return (EINVAL);
10264 }
10265 
10266 static void
10267 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10268 {
10269 	if (tp->t_fb_ptr) {
10270 		uint32_t calc;
10271 		struct tcp_bbr *bbr;
10272 		struct bbr_sendmap *rsm;
10273 
10274 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10275 		if (bbr->r_ctl.crte)
10276 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10277 		bbr_log_flowend(bbr);
10278 		bbr->rc_tp = NULL;
10279 		if (tp->t_inpcb) {
10280 			/* Backout any flags2 we applied */
10281 			tp->t_inpcb->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10282 			tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10283 			tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10284 		}
10285 		if (bbr->bbr_hdrw_pacing)
10286 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10287 		else
10288 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10289 		if (bbr->r_ctl.crte != NULL) {
10290 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10291 			bbr->r_ctl.crte = NULL;
10292 		}
10293 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10294 		while (rsm) {
10295 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10296 			uma_zfree(bbr_zone, rsm);
10297 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10298 		}
10299 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10300 		while (rsm) {
10301 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10302 			uma_zfree(bbr_zone, rsm);
10303 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10304 		}
10305 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10306 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10307 			BBR_STAT_INC(bbr_dynamic_rwnd);
10308 		else
10309 			BBR_STAT_INC(bbr_static_rwnd);
10310 		bbr->r_ctl.rc_free_cnt = 0;
10311 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10312 		tp->t_fb_ptr = NULL;
10313 	}
10314 	/* Make sure snd_nxt is correctly set */
10315 	tp->snd_nxt = tp->snd_max;
10316 }
10317 
10318 static void
10319 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10320 {
10321 	switch (tp->t_state) {
10322 	case TCPS_SYN_SENT:
10323 		bbr->r_state = TCPS_SYN_SENT;
10324 		bbr->r_substate = bbr_do_syn_sent;
10325 		break;
10326 	case TCPS_SYN_RECEIVED:
10327 		bbr->r_state = TCPS_SYN_RECEIVED;
10328 		bbr->r_substate = bbr_do_syn_recv;
10329 		break;
10330 	case TCPS_ESTABLISHED:
10331 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10332 		bbr->r_state = TCPS_ESTABLISHED;
10333 		bbr->r_substate = bbr_do_established;
10334 		break;
10335 	case TCPS_CLOSE_WAIT:
10336 		bbr->r_state = TCPS_CLOSE_WAIT;
10337 		bbr->r_substate = bbr_do_close_wait;
10338 		break;
10339 	case TCPS_FIN_WAIT_1:
10340 		bbr->r_state = TCPS_FIN_WAIT_1;
10341 		bbr->r_substate = bbr_do_fin_wait_1;
10342 		break;
10343 	case TCPS_CLOSING:
10344 		bbr->r_state = TCPS_CLOSING;
10345 		bbr->r_substate = bbr_do_closing;
10346 		break;
10347 	case TCPS_LAST_ACK:
10348 		bbr->r_state = TCPS_LAST_ACK;
10349 		bbr->r_substate = bbr_do_lastack;
10350 		break;
10351 	case TCPS_FIN_WAIT_2:
10352 		bbr->r_state = TCPS_FIN_WAIT_2;
10353 		bbr->r_substate = bbr_do_fin_wait_2;
10354 		break;
10355 	case TCPS_LISTEN:
10356 	case TCPS_CLOSED:
10357 	case TCPS_TIME_WAIT:
10358 	default:
10359 		break;
10360 	};
10361 }
10362 
10363 static void
10364 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10365 {
10366 	/*
10367 	 * Now what state are we going into now? Is there adjustments
10368 	 * needed?
10369 	 */
10370 	int32_t old_state, old_gain;
10371 
10372 	old_state = bbr_state_val(bbr);
10373 	old_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
10374 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10375 		/* Save the lowest srtt we saw in our end of the sub-state */
10376 		bbr->rc_hit_state_1 = 0;
10377 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10378 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10379 	}
10380 	bbr->rc_bbr_substate++;
10381 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10382 		/* Cycle back to first state-> gain */
10383 		bbr->rc_bbr_substate = 0;
10384 	}
10385 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10386 		/*
10387 		 * We enter the gain(5/4) cycle (possibly less if
10388 		 * shallow buffer detection is enabled)
10389 		 */
10390 		if (bbr->skip_gain) {
10391 			/*
10392 			 * Hardware pacing has set our rate to
10393 			 * the max and limited our b/w just
10394 			 * do level i.e. no gain.
10395 			 */
10396 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10397 		} else if (bbr->gain_is_limited &&
10398 			   bbr->bbr_hdrw_pacing &&
10399 			   bbr->r_ctl.crte) {
10400 			/*
10401 			 * We can't gain above the hardware pacing
10402 			 * rate which is less than our rate + the gain
10403 			 * calculate the gain needed to reach the hardware
10404 			 * pacing rate..
10405 			 */
10406 			uint64_t bw, rate, gain_calc;
10407 
10408 			bw = bbr_get_bw(bbr);
10409 			rate = bbr->r_ctl.crte->rate;
10410 			if ((rate > bw) &&
10411 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10412 				gain_calc = (rate * BBR_UNIT) / bw;
10413 				if (gain_calc < BBR_UNIT)
10414 					gain_calc = BBR_UNIT;
10415 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10416 			} else {
10417 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10418 			}
10419 		} else
10420 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10421 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10422 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10423 		} else
10424 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10425 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10426 		bbr->rc_hit_state_1 = 1;
10427 		bbr->r_ctl.rc_exta_time_gd = 0;
10428 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10429 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10430 		if (bbr_state_drain_2_tar) {
10431 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10432 		} else
10433 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10434 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10435 	} else {
10436 		/* All other cycles hit here 2-7 */
10437 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10438 			if (bbr_sub_drain_slam_cwnd &&
10439 			    (bbr->rc_use_google == 0) &&
10440 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10441 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10442 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10443 			}
10444 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10445 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10446 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10447 			else
10448 				bbr->r_ctl.rc_exta_time_gd = 0;
10449 			if (bbr->r_ctl.rc_exta_time_gd) {
10450 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10451 				/* Now chop up the time for each state (div by 7) */
10452 				bbr->r_ctl.rc_level_state_extra /= 7;
10453 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10454 					/* Add a randomization */
10455 					bbr_randomize_extra_state_time(bbr);
10456 				}
10457 			}
10458 		}
10459 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10460 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10461 	}
10462 	if (bbr->rc_use_google) {
10463 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10464 	}
10465 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10466 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10467 	if (dolog)
10468 		bbr_log_type_statechange(bbr, cts, line);
10469 
10470 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10471 		uint32_t time_in;
10472 
10473 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10474 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10475 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10476 		} else {
10477 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10478 		}
10479 	}
10480 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10481 	bbr_set_state_target(bbr, __LINE__);
10482 	if (bbr_sub_drain_slam_cwnd &&
10483 	    (bbr->rc_use_google == 0) &&
10484 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10485 		/* Slam down the cwnd */
10486 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10487 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10488 		if (bbr_sub_drain_app_limit) {
10489 			/* Go app limited if we are on a long drain */
10490 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10491 							  ctf_flight_size(bbr->rc_tp,
10492 							      (bbr->r_ctl.rc_sacked +
10493 							       bbr->r_ctl.rc_lost_bytes)));
10494 		}
10495 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10496 	}
10497 	if (bbr->rc_lt_use_bw) {
10498 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10499 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10500 	}
10501 	/* Google changes TSO size every cycle */
10502 	if (bbr->rc_use_google)
10503 		tcp_bbr_tso_size_check(bbr, cts);
10504 	bbr->r_ctl.gain_epoch = cts;
10505 	bbr->r_ctl.rc_bbr_state_time = cts;
10506 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10507 }
10508 
10509 static void
10510 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10511 {
10512 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10513 	    (google_allow_early_out == 1) &&
10514 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10515 		/* We have reached out target flight size possibly early */
10516 		goto change_state;
10517 	}
10518 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10519 		return;
10520 	}
10521 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10522 		/*
10523 		 * Must be a rttProp movement forward before
10524 		 * we can change states.
10525 		 */
10526 		return;
10527 	}
10528 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10529 		/*
10530 		 * The needed time has passed but for
10531 		 * the gain cycle extra rules apply:
10532 		 * 1) If we have seen loss, we exit
10533 		 * 2) If we have not reached the target
10534 		 *    we stay in GAIN (gain-to-target).
10535 		 */
10536 		if (google_consider_lost && losses)
10537 			goto change_state;
10538 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10539 			return;
10540 		}
10541 	}
10542 change_state:
10543 	/* For gain we must reach our target, all others last 1 rttProp */
10544 	bbr_substate_change(bbr, cts, __LINE__, 1);
10545 }
10546 
10547 static void
10548 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10549 {
10550 	uint32_t flight, bbr_cur_cycle_time;
10551 
10552 	if (bbr->rc_use_google) {
10553 		bbr_set_probebw_google_gains(bbr, cts, losses);
10554 		return;
10555 	}
10556 	if (cts == 0) {
10557 		/*
10558 		 * Never alow cts to be 0 we
10559 		 * do this so we can judge if
10560 		 * we have set a timestamp.
10561 		 */
10562 		cts = 1;
10563 	}
10564 	if (bbr_state_is_pkt_epoch)
10565 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10566 	else
10567 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10568 
10569 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10570 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10571 			flight = ctf_flight_size(bbr->rc_tp,
10572 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10573 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10574 				/* Keep it slam down */
10575 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10576 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10577 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10578 				}
10579 				if (bbr_sub_drain_app_limit) {
10580 					/* Go app limited if we are on a long drain */
10581 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10582 				}
10583 			}
10584 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10585 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10586 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10587 				/*
10588 				 * Still here after the same time as
10589 				 * the gain. We need to drain harder
10590 				 * for the next srtt. Reduce by a set amount
10591 				 * the gain drop is capped at DRAIN states
10592 				 * value (88).
10593 				 */
10594 				bbr->r_ctl.flightsize_at_drain = flight;
10595 				if (bbr_drain_drop_mul &&
10596 				    bbr_drain_drop_div &&
10597 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10598 					/* Use your specific drop value (def 4/5 = 20%) */
10599 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10600 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10601 				} else {
10602 					/* You get drop of 20% */
10603 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10604 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10605 				}
10606 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10607 					/* Reduce our gain again to the bottom  */
10608 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10609 				}
10610 				bbr_log_exit_gain(bbr, cts, 4);
10611 				/*
10612 				 * Extend out so we wait another
10613 				 * epoch before dropping again.
10614 				 */
10615 				bbr->r_ctl.gain_epoch = cts;
10616 			}
10617 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10618 				if (bbr_sub_drain_slam_cwnd &&
10619 				    (bbr->rc_use_google == 0) &&
10620 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10621 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10622 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10623 				}
10624 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10625 				bbr_log_exit_gain(bbr, cts, 3);
10626 			}
10627 		} else {
10628 			/* Its a gain  */
10629 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10630 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10631 				goto change_state;
10632 			}
10633 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10634 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10635 			     bbr->rc_tp->snd_wnd)) {
10636 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10637 				bbr_log_exit_gain(bbr, cts, 2);
10638 			}
10639 		}
10640 		/**
10641 		 * We fall through and return always one of two things has
10642 		 * occurred.
10643 		 * 1) We are still not at target
10644 		 *    <or>
10645 		 * 2) We reached the target and set rc_bbr_state_atflight
10646 		 *    which means we no longer hit this block
10647 		 *    next time we are called.
10648 		 */
10649 		return;
10650 	}
10651 change_state:
10652 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10653 		return;
10654 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10655 		/* Less than a full time-period has passed */
10656 		return;
10657 	}
10658 	if (bbr->r_ctl.rc_level_state_extra &&
10659 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10660 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10661 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10662 		/* Less than a full time-period + extra has passed */
10663 		return;
10664 	}
10665 	if (bbr_gain_gets_extra_too &&
10666 	    bbr->r_ctl.rc_level_state_extra &&
10667 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10668 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10669 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10670 		/* Less than a full time-period + extra has passed */
10671 		return;
10672 	}
10673 	bbr_substate_change(bbr, cts, __LINE__, 1);
10674 }
10675 
10676 static uint32_t
10677 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10678 {
10679 	uint32_t mss, tar;
10680 
10681 	if (bbr->rc_use_google) {
10682 		/* Google just uses the cwnd target */
10683 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10684 	} else {
10685 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10686 			  bbr->r_ctl.rc_pace_max_segs);
10687 		/* Get the base cwnd with gain rounded to a mss */
10688 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10689 						      gain), mss);
10690 		/* Make sure it is within our min */
10691 		if (tar < get_min_cwnd(bbr))
10692 			return (get_min_cwnd(bbr));
10693 	}
10694 	return (tar);
10695 }
10696 
10697 static void
10698 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10699 {
10700 	uint32_t tar, meth;
10701 
10702 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10703 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10704 		/* Special case using old probe-rtt method */
10705 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10706 		meth = 1;
10707 	} else {
10708 		/* Non-probe-rtt case and reduced probe-rtt  */
10709 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10710 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10711 			/* For gain cycle we use the hptsi gain */
10712 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10713 			meth = 2;
10714 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10715 			/*
10716 			 * If configured, or for google all other states
10717 			 * get BBR_UNIT.
10718 			 */
10719 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10720 			meth = 3;
10721 		} else {
10722 			/*
10723 			 * Or we set a target based on the pacing gain
10724 			 * for non-google mode and default (non-configured).
10725 			 * Note we don't set a target goal below drain (192).
10726 			 */
10727 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10728 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10729 				meth = 4;
10730 			} else {
10731 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10732 				meth = 5;
10733 			}
10734 		}
10735 	}
10736 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10737 	bbr->r_ctl.rc_target_at_state = tar;
10738 }
10739 
10740 static void
10741 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10742 {
10743 	/* Change to probe_rtt */
10744 	uint32_t time_in;
10745 
10746 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10747 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10748 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10749 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10750 					  + bbr->r_ctl.rc_delivered);
10751 	/* Setup so we force feed the filter */
10752 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10753 		bbr->rc_prtt_set_ts = 1;
10754 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10755 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10756 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10757 	}
10758 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10759 	bbr->r_ctl.rc_rtt_shrinks = cts;
10760 	bbr->r_ctl.last_in_probertt = cts;
10761 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10762 	bbr->r_ctl.rc_bbr_state_time = cts;
10763 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10764 	/* We need to force the filter to update */
10765 
10766 	if ((bbr_sub_drain_slam_cwnd) &&
10767 	    bbr->rc_hit_state_1 &&
10768 	    (bbr->rc_use_google == 0) &&
10769 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10770 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10771 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10772 	} else
10773 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10774 	/* Update the lost */
10775 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10776 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10777 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10778 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10779 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10780 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10781 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10782 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10783 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10784 	} else {
10785 		/*
10786 		 * We bring it down slowly by using a hptsi gain that is
10787 		 * probably 75%. This will slowly float down our outstanding
10788 		 * without tampering with the cwnd.
10789 		 */
10790 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10791 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10792 		bbr_set_state_target(bbr, __LINE__);
10793 		if (bbr_prtt_slam_cwnd &&
10794 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10795 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10796 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10797 		}
10798 	}
10799 	if (ctf_flight_size(bbr->rc_tp,
10800 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10801 	    bbr->r_ctl.rc_target_at_state) {
10802 		/* We are at target */
10803 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10804 	} else {
10805 		/* We need to come down to reach target before our time begins */
10806 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10807 	}
10808 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10809 	BBR_STAT_INC(bbr_enter_probertt);
10810 	bbr_log_exit_gain(bbr, cts, 0);
10811 	bbr_log_type_statechange(bbr, cts, line);
10812 }
10813 
10814 static void
10815 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10816 {
10817 	/*
10818 	 * Sanity check on probe-rtt intervals.
10819 	 * In crazy situations where we are competing
10820 	 * against new-reno flows with huge buffers
10821 	 * our rtt-prop interval could come to dominate
10822 	 * things if we can't get through a full set
10823 	 * of cycles, we need to adjust it.
10824 	 */
10825 	if (bbr_can_adjust_probertt &&
10826 	    (bbr->rc_use_google == 0)) {
10827 		uint16_t val = 0;
10828 		uint32_t cur_rttp, fval, newval, baseval;
10829 
10830 		/* Are we to small and go into probe-rtt to often? */
10831 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10832 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10833 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10834 		if (bbr_is_ratio == 0) {
10835 			if (fval > bbr_rtt_probe_limit)
10836 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10837 			else
10838 				newval = cur_rttp;
10839 		} else {
10840 			int mul;
10841 
10842 			mul = fval / bbr_rtt_probe_limit;
10843 			newval = cur_rttp * mul;
10844 		}
10845 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10846 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10847 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10848 			val = 1;
10849 		} else {
10850 			/*
10851 			 * No adjustments were made
10852 			 * do we need to shrink it?
10853 			 */
10854 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10855 				if (cur_rttp <= bbr_rtt_probe_limit) {
10856 					/*
10857 					 * Things have calmed down lets
10858 					 * shrink all the way to default
10859 					 */
10860 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10861 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10862 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10863 					cur_rttp = bbr_rtt_probe_limit;
10864 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10865 					val = 2;
10866 				} else {
10867 					/*
10868 					 * Well does some adjustment make sense?
10869 					 */
10870 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10871 						/* We can reduce interval time some */
10872 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10873 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10874 						val = 3;
10875 					}
10876 				}
10877 			}
10878 		}
10879 		if (val)
10880 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10881 	}
10882 }
10883 
10884 static void
10885 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10886 {
10887 	/* Exit probe-rtt */
10888 
10889 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10890 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10891 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10892 	}
10893 	bbr_log_exit_gain(bbr, cts, 1);
10894 	bbr->rc_hit_state_1 = 0;
10895 	bbr->r_ctl.rc_rtt_shrinks = cts;
10896 	bbr->r_ctl.last_in_probertt = cts;
10897 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10898 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10899 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10900 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10901 					  bbr->r_ctl.rc_delivered);
10902 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10903 		uint32_t time_in;
10904 
10905 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10906 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10907 	}
10908 	if (bbr->rc_filled_pipe) {
10909 		/* Switch to probe_bw */
10910 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10911 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10912 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10913 		bbr_substate_change(bbr, cts, __LINE__, 0);
10914 		bbr_log_type_statechange(bbr, cts, __LINE__);
10915 	} else {
10916 		/* Back to startup */
10917 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10918 		bbr->r_ctl.rc_bbr_state_time = cts;
10919 		/*
10920 		 * We don't want to give a complete free 3
10921 		 * measurements until we exit, so we use
10922 		 * the number of pe's we were in probe-rtt
10923 		 * to add to the startup_epoch. That way
10924 		 * we will still retain the old state.
10925 		 */
10926 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10927 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10928 		/* Make sure to use the lower pg when shifting back in */
10929 		if (bbr->r_ctl.rc_lost &&
10930 		    bbr_use_lower_gain_in_startup &&
10931 		    (bbr->rc_use_google == 0))
10932 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10933 		else
10934 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10935 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10936 		/* Probably not needed but set it anyway */
10937 		bbr_set_state_target(bbr, __LINE__);
10938 		bbr_log_type_statechange(bbr, cts, __LINE__);
10939 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10940 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10941 	}
10942 	bbr_check_probe_rtt_limits(bbr, cts);
10943 }
10944 
10945 static int32_t inline
10946 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10947 {
10948 	if ((bbr->rc_past_init_win == 1) &&
10949 	    (bbr->rc_in_persist == 0) &&
10950 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10951 		return (1);
10952 	}
10953 	if (bbr_can_force_probertt &&
10954 	    (bbr->rc_in_persist == 0) &&
10955 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10956 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10957 		return (1);
10958 	}
10959 	return (0);
10960 }
10961 
10962 static int32_t
10963 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10964 {
10965 	uint64_t btlbw, gain;
10966 	if (pkt_epoch == 0) {
10967 		/*
10968 		 * Need to be on a pkt-epoch to continue.
10969 		 */
10970 		return (0);
10971 	}
10972 	btlbw = bbr_get_full_bw(bbr);
10973 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10974 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10975 	if (btlbw >= gain) {
10976 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10977 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10978 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10979 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10980 	}
10981 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10982 		return (1);
10983 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10984 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10985 	return(0);
10986 }
10987 
10988 static int32_t inline
10989 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10990 {
10991 	/* Have we gained 25% in the last 3 packet based epoch's? */
10992 	uint64_t btlbw, gain;
10993 	int do_exit;
10994 	int delta, rtt_gain;
10995 
10996 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10997 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10998 		/*
10999 		 * This qualifies as a RTT_PROBE session since we drop the
11000 		 * data outstanding to nothing and waited more than
11001 		 * bbr_rtt_probe_time.
11002 		 */
11003 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11004 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
11005 	}
11006 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
11007 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
11008 		return (0);
11009 	}
11010 	if (bbr->rc_use_google)
11011 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
11012 
11013 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11014 	    (bbr_use_lower_gain_in_startup)) {
11015 		/* Drop to a lower gain 1.5 x since we saw loss */
11016 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
11017 	}
11018 	if (pkt_epoch == 0) {
11019 		/*
11020 		 * Need to be on a pkt-epoch to continue.
11021 		 */
11022 		return (0);
11023 	}
11024 	if (bbr_rtt_gain_thresh) {
11025 		/*
11026 		 * Do we allow a flow to stay
11027 		 * in startup with no loss and no
11028 		 * gain in rtt over a set threshold?
11029 		 */
11030 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
11031 		    bbr->r_ctl.startup_last_srtt &&
11032 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
11033 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
11034 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
11035 		} else
11036 			rtt_gain = 0;
11037 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
11038 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
11039 			/* First time or new lower value */
11040 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
11041 
11042 		if ((bbr->r_ctl.rc_lost == 0) &&
11043 		    (rtt_gain < bbr_rtt_gain_thresh)) {
11044 			/*
11045 			 * No loss, and we are under
11046 			 * our gain threhold for
11047 			 * increasing RTT.
11048 			 */
11049 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11050 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
11051 			bbr_log_startup_event(bbr, cts, rtt_gain,
11052 					      delta, bbr->r_ctl.startup_last_srtt, 10);
11053 			return (0);
11054 		}
11055 	}
11056 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
11057 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
11058 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
11059 		/*
11060 		 * We only assess if we have a new measurment when
11061 		 * we have no loss and are not in recovery.
11062 		 * Drag up by one our last_startup epoch so we will hold
11063 		 * the number of non-gain we have already accumulated.
11064 		 */
11065 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11066 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
11067 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11068 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11069 		return (0);
11070 	}
11071 	/* Case where we reduced the lost (bad retransmit) */
11072 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11073 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11074 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11075 	btlbw = bbr_get_full_bw(bbr);
11076 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11077 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11078 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11079 	else
11080 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11081 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11082 	do_exit = 0;
11083 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11084 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11085 	if (btlbw >= gain) {
11086 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11087 		/* Update the lost so we won't exit in next set of tests */
11088 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11089 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11090 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11091 	}
11092 	if ((bbr->rc_loss_exit &&
11093 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11094 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11095 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11096 		/*
11097 		 * If we had no gain,  we had loss and that loss was above
11098 		 * our threshould, the rwnd is not constrained, and we have
11099 		 * had at least 3 packet epochs exit. Note that this is
11100 		 * switched off by sysctl. Google does not do this by the
11101 		 * way.
11102 		 */
11103 		if ((ctf_flight_size(bbr->rc_tp,
11104 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11105 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11106 			do_exit = 1;
11107 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11108 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11109 		} else {
11110 			/* Just record an updated loss value */
11111 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11112 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11113 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11114 		}
11115 	} else
11116 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11117 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11118 	    do_exit) {
11119 		/* Return 1 to exit the startup state. */
11120 		return (1);
11121 	}
11122 	/* Stay in startup */
11123 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11124 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11125 	return (0);
11126 }
11127 
11128 static void
11129 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11130 {
11131 	/*
11132 	 * A tick occurred in the rtt epoch do we need to do anything?
11133 	 */
11134 #ifdef BBR_INVARIANTS
11135 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11136 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11137 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11138 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11139 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11140 		/* Debug code? */
11141 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11142 	}
11143 #endif
11144 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11145 		/* Do we exit the startup state? */
11146 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11147 			uint32_t time_in;
11148 
11149 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11150 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11151 			bbr->rc_filled_pipe = 1;
11152 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11153 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11154 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11155 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11156 			} else
11157 				time_in = 0;
11158 			if (bbr->rc_no_pacing)
11159 				bbr->rc_no_pacing = 0;
11160 			bbr->r_ctl.rc_bbr_state_time = cts;
11161 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11162 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11163 			bbr_set_state_target(bbr, __LINE__);
11164 			if ((bbr->rc_use_google == 0) &&
11165 			    bbr_slam_cwnd_in_main_drain) {
11166 				/* Here we don't have to worry about probe-rtt */
11167 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11168 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11169 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11170 			}
11171 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11172 			bbr_log_type_statechange(bbr, cts, __LINE__);
11173 			if (ctf_flight_size(bbr->rc_tp,
11174 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11175 			    bbr->r_ctl.rc_target_at_state) {
11176 				/*
11177 				 * Switch to probe_bw if we are already
11178 				 * there
11179 				 */
11180 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11181 				bbr_substate_change(bbr, cts, __LINE__, 0);
11182 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11183 				bbr_log_type_statechange(bbr, cts, __LINE__);
11184 			}
11185 		}
11186 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11187 		uint32_t inflight;
11188 		struct tcpcb *tp;
11189 
11190 		tp = bbr->rc_tp;
11191 		inflight = ctf_flight_size(tp,
11192 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11193 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11194 			/* We have reached a flight of the cwnd target */
11195 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11196 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11197 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11198 			bbr_set_state_target(bbr, __LINE__);
11199 			/*
11200 			 * Rig it so we don't do anything crazy and
11201 			 * start fresh with a new randomization.
11202 			 */
11203 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11204 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11205 			bbr_substate_change(bbr, cts, __LINE__, 1);
11206 		}
11207 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11208 		/* Has in-flight reached the bdp (or less)? */
11209 		uint32_t inflight;
11210 		struct tcpcb *tp;
11211 
11212 		tp = bbr->rc_tp;
11213 		inflight = ctf_flight_size(tp,
11214 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11215 		if ((bbr->rc_use_google == 0) &&
11216 		    bbr_slam_cwnd_in_main_drain &&
11217 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11218 			/*
11219 			 * Here we don't have to worry about probe-rtt
11220 			 * re-slam it, but keep it slammed down.
11221 			 */
11222 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11223 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11224 		}
11225 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11226 			/* We have drained */
11227 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11228 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11229 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11230 				uint32_t time_in;
11231 
11232 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11233 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11234 			}
11235 			if ((bbr->rc_use_google == 0) &&
11236 			    bbr_slam_cwnd_in_main_drain &&
11237 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11238 				/* Restore the cwnd */
11239 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11240 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11241 			}
11242 			/* Setup probe-rtt has being done now RRS-HERE */
11243 			bbr->r_ctl.rc_rtt_shrinks = cts;
11244 			bbr->r_ctl.last_in_probertt = cts;
11245 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11246 			/* Randomly pick a sub-state */
11247 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11248 			bbr_substate_change(bbr, cts, __LINE__, 0);
11249 			bbr_log_type_statechange(bbr, cts, __LINE__);
11250 		}
11251 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11252 		uint32_t flight;
11253 
11254 		flight = ctf_flight_size(bbr->rc_tp,
11255 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11256 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11257 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11258 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11259 			/*
11260 			 * We must keep cwnd at the desired MSS.
11261 			 */
11262 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11263 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11264 		} else if ((bbr_prtt_slam_cwnd) &&
11265 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11266 			/* Re-slam it */
11267 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11268 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11269 		}
11270 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11271 			/* Has outstanding reached our target? */
11272 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11273 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11274 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11275 				/* If time is exactly 0, be 1usec off */
11276 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11277 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11278 				if (bbr->rc_use_google == 0) {
11279 					/*
11280 					 * Restore any lowering that as occurred to
11281 					 * reach here
11282 					 */
11283 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11284 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11285 					else
11286 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11287 				}
11288 			}
11289 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11290 			    (bbr->rc_use_google == 0) &&
11291 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11292 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11293 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11294 				/*
11295 				 * We have doddled with our current hptsi
11296 				 * gain an srtt and have still not made it
11297 				 * to target, or we have increased our flight.
11298 				 * Lets reduce the gain by xx%
11299 				 * flooring the reduce at DRAIN (based on
11300 				 * mul/div)
11301 				 */
11302 				int red;
11303 
11304 				bbr->r_ctl.flightsize_at_drain = flight;
11305 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11306 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11307 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11308 					/* Reduce our gain again */
11309 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11310 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11311 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11312 					/* one more chance before we give up */
11313 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11314 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11315 				} else {
11316 					/* At the very bottom */
11317 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11318 				}
11319 			}
11320 		}
11321 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11322 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11323 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11324 			/* Time to exit probe RTT normally */
11325 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11326 		}
11327 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11328 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11329 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11330 			/*
11331 			 * This qualifies as a RTT_PROBE session since we
11332 			 * drop the data outstanding to nothing and waited
11333 			 * more than bbr_rtt_probe_time.
11334 			 */
11335 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11336 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11337 		}
11338 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11339 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11340 		} else {
11341 			bbr_set_probebw_gains(bbr, cts, losses);
11342 		}
11343 	}
11344 }
11345 
11346 static void
11347 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11348 {
11349 	int32_t epoch = 0;
11350 
11351 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11352 		bbr_set_epoch(bbr, cts, line);
11353 		/* At each epoch doe lt bw sampling */
11354 		epoch = 1;
11355 	}
11356 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11357 }
11358 
11359 static int
11360 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11361     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11362     int32_t nxt_pkt, struct timeval *tv)
11363 {
11364 	int32_t thflags, retval;
11365 	uint32_t cts, lcts;
11366 	uint32_t tiwin;
11367 	struct tcpopt to;
11368 	struct tcp_bbr *bbr;
11369 	struct bbr_sendmap *rsm;
11370 	struct timeval ltv;
11371 	int32_t did_out = 0;
11372 	int32_t in_recovery;
11373 	uint16_t nsegs;
11374 	int32_t prev_state;
11375 	uint32_t lost;
11376 
11377 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11378 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11379 	/* add in our stats */
11380 	kern_prefetch(bbr, &prev_state);
11381 	prev_state = 0;
11382 	thflags = th->th_flags;
11383 	/*
11384 	 * If this is either a state-changing packet or current state isn't
11385 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11386 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11387 	 * caller may have unnecessarily acquired a write lock due to a
11388 	 * race.
11389 	 */
11390 	INP_WLOCK_ASSERT(tp->t_inpcb);
11391 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11392 	    __func__));
11393 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11394 	    __func__));
11395 
11396 	tp->t_rcvtime = ticks;
11397 	/*
11398 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11399 	 * the scale is zero.
11400 	 */
11401 	tiwin = th->th_win << tp->snd_scale;
11402 #ifdef STATS
11403 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11404 #endif
11405 
11406 	if (m->m_flags & M_TSTMP) {
11407 		/* Prefer the hardware timestamp if present */
11408 		struct timespec ts;
11409 
11410 		mbuf_tstmp2timespec(m, &ts);
11411 		bbr->rc_tv.tv_sec = ts.tv_sec;
11412 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11413 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11414 	} else if (m->m_flags & M_TSTMP_LRO) {
11415 		/* Next the arrival timestamp */
11416 		struct timespec ts;
11417 
11418 		mbuf_tstmp2timespec(m, &ts);
11419 		bbr->rc_tv.tv_sec = ts.tv_sec;
11420 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11421 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11422 	} else {
11423 		/*
11424 		 * Ok just get the current time.
11425 		 */
11426 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11427 	}
11428 	/*
11429 	 * Parse options on any incoming segment.
11430 	 */
11431 	tcp_dooptions(&to, (u_char *)(th + 1),
11432 	    (th->th_off << 2) - sizeof(struct tcphdr),
11433 	    (thflags & TH_SYN) ? TO_SYN : 0);
11434 
11435 	/*
11436 	 * If timestamps were negotiated during SYN/ACK and a
11437 	 * segment without a timestamp is received, silently drop
11438 	 * the segment, unless it is a RST segment or missing timestamps are
11439 	 * tolerated.
11440 	 * See section 3.2 of RFC 7323.
11441 	 */
11442 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11443 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11444 		retval = 0;
11445 		m_freem(m);
11446 		goto done_with_input;
11447 	}
11448 	/*
11449 	 * If echoed timestamp is later than the current time, fall back to
11450 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11451 	 * were used when this connection was established.
11452 	 */
11453 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11454 		to.to_tsecr -= tp->ts_offset;
11455 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11456 			to.to_tsecr = 0;
11457 	}
11458 	/*
11459 	 * If its the first time in we need to take care of options and
11460 	 * verify we can do SACK for rack!
11461 	 */
11462 	if (bbr->r_state == 0) {
11463 		/*
11464 		 * Process options only when we get SYN/ACK back. The SYN
11465 		 * case for incoming connections is handled in tcp_syncache.
11466 		 * According to RFC1323 the window field in a SYN (i.e., a
11467 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11468 		 * this is traditional behavior, may need to be cleaned up.
11469 		 */
11470 		if (bbr->rc_inp == NULL) {
11471 			bbr->rc_inp = tp->t_inpcb;
11472 		}
11473 		/*
11474 		 * We need to init rc_inp here since its not init'd when
11475 		 * bbr_init is called
11476 		 */
11477 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11478 			if ((to.to_flags & TOF_SCALE) &&
11479 			    (tp->t_flags & TF_REQ_SCALE)) {
11480 				tp->t_flags |= TF_RCVD_SCALE;
11481 				tp->snd_scale = to.to_wscale;
11482 			} else
11483 				tp->t_flags &= ~TF_REQ_SCALE;
11484 			/*
11485 			 * Initial send window.  It will be updated with the
11486 			 * next incoming segment to the scaled value.
11487 			 */
11488 			tp->snd_wnd = th->th_win;
11489 			if ((to.to_flags & TOF_TS) &&
11490 			    (tp->t_flags & TF_REQ_TSTMP)) {
11491 				tp->t_flags |= TF_RCVD_TSTMP;
11492 				tp->ts_recent = to.to_tsval;
11493 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11494 			} else
11495 			    tp->t_flags &= ~TF_REQ_TSTMP;
11496 			if (to.to_flags & TOF_MSS)
11497 				tcp_mss(tp, to.to_mss);
11498 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11499 			    (to.to_flags & TOF_SACKPERM) == 0)
11500 				tp->t_flags &= ~TF_SACK_PERMIT;
11501 			if (IS_FASTOPEN(tp->t_flags)) {
11502 				if (to.to_flags & TOF_FASTOPEN) {
11503 					uint16_t mss;
11504 
11505 					if (to.to_flags & TOF_MSS)
11506 						mss = to.to_mss;
11507 					else
11508 						if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
11509 							mss = TCP6_MSS;
11510 						else
11511 							mss = TCP_MSS;
11512 					tcp_fastopen_update_cache(tp, mss,
11513 					    to.to_tfo_len, to.to_tfo_cookie);
11514 				} else
11515 					tcp_fastopen_disable_path(tp);
11516 			}
11517 		}
11518 		/*
11519 		 * At this point we are at the initial call. Here we decide
11520 		 * if we are doing RACK or not. We do this by seeing if
11521 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11522 		 * we switch to the default code.
11523 		 */
11524 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11525 			/* Bail */
11526 			tcp_switch_back_to_default(tp);
11527 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11528 			    tlen, iptos);
11529 			return (1);
11530 		}
11531 		/* Set the flag */
11532 		bbr->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
11533 		tcp_set_hpts(tp->t_inpcb);
11534 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11535 	}
11536 	if (thflags & TH_ACK) {
11537 		/* Track ack types */
11538 		if (to.to_flags & TOF_SACK)
11539 			BBR_STAT_INC(bbr_acks_with_sacks);
11540 		else
11541 			BBR_STAT_INC(bbr_plain_acks);
11542 	}
11543 	/*
11544 	 * This is the one exception case where we set the rack state
11545 	 * always. All other times (timers etc) we must have a rack-state
11546 	 * set (so we assure we have done the checks above for SACK).
11547 	 */
11548 	if (thflags & TH_FIN)
11549 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11550 	if (bbr->r_state != tp->t_state)
11551 		bbr_set_state(tp, bbr, tiwin);
11552 
11553 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11554 		kern_prefetch(rsm, &prev_state);
11555 	prev_state = bbr->r_state;
11556 	bbr->rc_ack_was_delayed = 0;
11557 	lost = bbr->r_ctl.rc_lost;
11558 	bbr->rc_is_pkt_epoch_now = 0;
11559 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11560 		/* Get the real time into lcts and figure the real delay */
11561 		lcts = tcp_get_usecs(&ltv);
11562 		if (TSTMP_GT(lcts, cts)) {
11563 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11564 			bbr->rc_ack_was_delayed = 1;
11565 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11566 				     bbr->r_ctl.highest_hdwr_delay))
11567 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11568 		} else {
11569 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11570 			bbr->rc_ack_was_delayed = 0;
11571 		}
11572 	} else {
11573 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11574 		bbr->rc_ack_was_delayed = 0;
11575 	}
11576 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11577 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11578 		retval = 0;
11579 		m_freem(m);
11580 		goto done_with_input;
11581 	}
11582 	/*
11583 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11584 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11585 	 */
11586 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11587 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11588 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11589 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11590 		return (1);
11591 	}
11592 	in_recovery = IN_RECOVERY(tp->t_flags);
11593 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11594 		bbr->r_ctl.rc_high_rwnd = tiwin;
11595 #ifdef BBR_INVARIANTS
11596 	if ((tp->t_inpcb->inp_flags & INP_DROPPED) ||
11597 	    (tp->t_inpcb->inp_flags2 & INP_FREED)) {
11598 		panic("tp:%p bbr:%p given a dropped inp:%p",
11599 		    tp, bbr, tp->t_inpcb);
11600 	}
11601 #endif
11602 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11603 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11604 	bbr->rtt_valid = 0;
11605 	if (to.to_flags & TOF_TS) {
11606 		bbr->rc_ts_valid = 1;
11607 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11608 	} else {
11609 		bbr->rc_ts_valid = 0;
11610 		bbr->r_ctl.last_inbound_ts = 0;
11611 	}
11612 	retval = (*bbr->r_substate) (m, th, so,
11613 	    tp, &to, drop_hdrlen,
11614 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11615 #ifdef BBR_INVARIANTS
11616 	if ((retval == 0) &&
11617 	    (tp->t_inpcb == NULL)) {
11618 		panic("retval:%d tp:%p t_inpcb:NULL state:%d",
11619 		    retval, tp, prev_state);
11620 	}
11621 #endif
11622 	if (nxt_pkt == 0)
11623 		BBR_STAT_INC(bbr_rlock_left_ret0);
11624 	else
11625 		BBR_STAT_INC(bbr_rlock_left_ret1);
11626 	if (retval == 0) {
11627 		/*
11628 		 * If retval is 1 the tcb is unlocked and most likely the tp
11629 		 * is gone.
11630 		 */
11631 		INP_WLOCK_ASSERT(tp->t_inpcb);
11632 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11633 		if (bbr->rc_is_pkt_epoch_now)
11634 			bbr_set_pktepoch(bbr, cts, __LINE__);
11635 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11636 		if (nxt_pkt == 0) {
11637 			if (bbr->r_wanted_output != 0) {
11638 				bbr->rc_output_starts_timer = 0;
11639 				did_out = 1;
11640 				(void)tp->t_fb->tfb_tcp_output(tp);
11641 			} else
11642 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11643 		}
11644 		if ((nxt_pkt == 0) &&
11645 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11646 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11647 		     (tp->t_flags & TF_DELACK) ||
11648 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11649 		      (tp->t_state <= TCPS_CLOSING)))) {
11650 			/*
11651 			 * We could not send (probably in the hpts but
11652 			 * stopped the timer)?
11653 			 */
11654 			if ((tp->snd_max == tp->snd_una) &&
11655 			    ((tp->t_flags & TF_DELACK) == 0) &&
11656 			    (bbr->rc_inp->inp_in_hpts) &&
11657 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11658 				/*
11659 				 * keep alive not needed if we are hptsi
11660 				 * output yet
11661 				 */
11662 				;
11663 			} else {
11664 				if (bbr->rc_inp->inp_in_hpts) {
11665 					tcp_hpts_remove(bbr->rc_inp, HPTS_REMOVE_OUTPUT);
11666 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11667 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11668 						uint32_t del;
11669 
11670 						del = lcts - bbr->rc_pacer_started;
11671 						if (bbr->r_ctl.rc_last_delay_val > del) {
11672 							BBR_STAT_INC(bbr_force_timer_start);
11673 							bbr->r_ctl.rc_last_delay_val -= del;
11674 							bbr->rc_pacer_started = lcts;
11675 						} else {
11676 							/* We are late */
11677 							bbr->r_ctl.rc_last_delay_val = 0;
11678 							BBR_STAT_INC(bbr_force_output);
11679 							(void)tp->t_fb->tfb_tcp_output(tp);
11680 						}
11681 					}
11682 				}
11683 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11684 				    0);
11685 			}
11686 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11687 			/* Do we have the correct timer running? */
11688 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11689 		}
11690 		/* Do we have a new state */
11691 		if (bbr->r_state != tp->t_state)
11692 			bbr_set_state(tp, bbr, tiwin);
11693 done_with_input:
11694 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11695 		if (did_out)
11696 			bbr->r_wanted_output = 0;
11697 #ifdef BBR_INVARIANTS
11698 		if (tp->t_inpcb == NULL) {
11699 			panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
11700 			    did_out,
11701 			    retval, tp, prev_state);
11702 		}
11703 #endif
11704 	}
11705 	return (retval);
11706 }
11707 
11708 static void
11709 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11710     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11711 {
11712 	struct timeval tv;
11713 	int retval;
11714 
11715 	/* First lets see if we have old packets */
11716 	if (tp->t_in_pkt) {
11717 		if (ctf_do_queued_segments(so, tp, 1)) {
11718 			m_freem(m);
11719 			return;
11720 		}
11721 	}
11722 	if (m->m_flags & M_TSTMP_LRO) {
11723 		tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
11724 		tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
11725 	} else {
11726 		/* Should not be should we kassert instead? */
11727 		tcp_get_usecs(&tv);
11728 	}
11729 	retval = bbr_do_segment_nounlock(m, th, so, tp,
11730 					 drop_hdrlen, tlen, iptos, 0, &tv);
11731 	if (retval == 0) {
11732 		INP_WUNLOCK(tp->t_inpcb);
11733 	}
11734 }
11735 
11736 /*
11737  * Return how much data can be sent without violating the
11738  * cwnd or rwnd.
11739  */
11740 
11741 static inline uint32_t
11742 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11743     uint32_t avail, int32_t sb_offset, uint32_t cts)
11744 {
11745 	uint32_t len;
11746 
11747 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11748 		/* We never want to go over our peers rcv-window */
11749 		len = 0;
11750 	} else {
11751 		uint32_t flight;
11752 
11753 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11754 		if (flight >= sendwin) {
11755 			/*
11756 			 * We have in flight what we are allowed by cwnd (if
11757 			 * it was rwnd blocking it would have hit above out
11758 			 * >= tp->snd_wnd).
11759 			 */
11760 			return (0);
11761 		}
11762 		len = sendwin - flight;
11763 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11764 			/* We would send too much (beyond the rwnd) */
11765 			len = tp->snd_wnd - ctf_outstanding(tp);
11766 		}
11767 		if ((len + sb_offset) > avail) {
11768 			/*
11769 			 * We don't have that much in the SB, how much is
11770 			 * there?
11771 			 */
11772 			len = avail - sb_offset;
11773 		}
11774 	}
11775 	return (len);
11776 }
11777 
11778 static inline void
11779 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11780 {
11781 #ifdef NETFLIX_STATS
11782 	KMOD_TCPSTAT_INC(tcps_sndpack_error);
11783 	KMOD_TCPSTAT_ADD(tcps_sndbyte_error, len);
11784 #endif
11785 }
11786 
11787 static inline void
11788 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11789 {
11790 	if (error) {
11791 		bbr_do_error_accounting(tp, bbr, rsm, len, error);
11792 		return;
11793 	}
11794 	if (rsm) {
11795 		if (rsm->r_flags & BBR_TLP) {
11796 			/*
11797 			 * TLP should not count in retran count, but in its
11798 			 * own bin
11799 			 */
11800 #ifdef NETFLIX_STATS
11801 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11802 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11803 #endif
11804 		} else {
11805 			/* Retransmit */
11806 			tp->t_sndrexmitpack++;
11807 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11808 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11809 #ifdef STATS
11810 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11811 			    len);
11812 #endif
11813 		}
11814 		/*
11815 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11816 		 * sub-state
11817 		 */
11818 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11819 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11820 			/* Non probe_bw log in 1, 2, or 4. */
11821 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11822 		} else {
11823 			/*
11824 			 * Log our probe state 3, and log also 5-13 to show
11825 			 * us the recovery sub-state for the send. This
11826 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11827 			 */
11828 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11829 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11830 		}
11831 		/* Place in both 16's the totals of retransmitted */
11832 		counter_u64_add(bbr_state_lost[16], len);
11833 		counter_u64_add(bbr_state_resend[16], len);
11834 		/* Place in 17's the total sent */
11835 		counter_u64_add(bbr_state_resend[17], len);
11836 		counter_u64_add(bbr_state_lost[17], len);
11837 
11838 	} else {
11839 		/* New sends */
11840 		KMOD_TCPSTAT_INC(tcps_sndpack);
11841 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11842 		/* Place in 17's the total sent */
11843 		counter_u64_add(bbr_state_resend[17], len);
11844 		counter_u64_add(bbr_state_lost[17], len);
11845 #ifdef STATS
11846 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11847 		    len);
11848 #endif
11849 	}
11850 }
11851 
11852 static void
11853 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11854 {
11855 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11856 		/*
11857 		 * Limit the cwnd to not be above N x the target plus whats
11858 		 * is outstanding. The target is based on the current b/w
11859 		 * estimate.
11860 		 */
11861 		uint32_t target;
11862 
11863 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11864 		target += ctf_outstanding(tp);
11865 		target *= bbr_target_cwnd_mult_limit;
11866 		if (tp->snd_cwnd > target)
11867 			tp->snd_cwnd = target;
11868 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11869 	}
11870 }
11871 
11872 static int
11873 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11874 {
11875 	/*
11876 	 * "adv" is the amount we could increase the window, taking into
11877 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11878 	 */
11879 	int32_t adv;
11880 	int32_t oldwin;
11881 
11882 	adv = recwin;
11883 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11884 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11885 		if (adv > oldwin)
11886 			adv -= oldwin;
11887 		else {
11888 			/* We can't increase the window */
11889 			adv = 0;
11890 		}
11891 	} else
11892 		oldwin = 0;
11893 
11894 	/*
11895 	 * If the new window size ends up being the same as or less
11896 	 * than the old size when it is scaled, then don't force
11897 	 * a window update.
11898 	 */
11899 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11900 		return (0);
11901 
11902 	if (adv >= (2 * maxseg) &&
11903 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11904 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11905 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11906 		return (1);
11907 	}
11908 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11909 		return (1);
11910 	return (0);
11911 }
11912 
11913 /*
11914  * Return 0 on success and a errno on failure to send.
11915  * Note that a 0 return may not mean we sent anything
11916  * if the TCB was on the hpts. A non-zero return
11917  * does indicate the error we got from ip[6]_output.
11918  */
11919 static int
11920 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11921 {
11922 	struct socket *so;
11923 	int32_t len;
11924 	uint32_t cts;
11925 	uint32_t recwin, sendwin;
11926 	int32_t sb_offset;
11927 	int32_t flags, abandon, error = 0;
11928 	struct tcp_log_buffer *lgb = NULL;
11929 	struct mbuf *m;
11930 	struct mbuf *mb;
11931 	uint32_t if_hw_tsomaxsegcount = 0;
11932 	uint32_t if_hw_tsomaxsegsize = 0;
11933 	uint32_t if_hw_tsomax = 0;
11934 	struct ip *ip = NULL;
11935 #ifdef TCPDEBUG
11936 	struct ipovly *ipov = NULL;
11937 #endif
11938 	struct tcp_bbr *bbr;
11939 	struct tcphdr *th;
11940 	struct udphdr *udp = NULL;
11941 	u_char opt[TCP_MAXOLEN];
11942 	unsigned ipoptlen, optlen, hdrlen;
11943 	unsigned ulen;
11944 	uint32_t bbr_seq;
11945 	uint32_t delay_calc=0;
11946 	uint8_t doing_tlp = 0;
11947 	uint8_t local_options;
11948 #ifdef BBR_INVARIANTS
11949 	uint8_t doing_retran_from = 0;
11950 	uint8_t picked_up_retran = 0;
11951 #endif
11952 	uint8_t wanted_cookie = 0;
11953 	uint8_t more_to_rxt=0;
11954 	int32_t prefetch_so_done = 0;
11955 	int32_t prefetch_rsm = 0;
11956  	uint32_t what_we_can = 0;
11957 	uint32_t tot_len = 0;
11958 	uint32_t rtr_cnt = 0;
11959 	uint32_t maxseg, pace_max_segs, p_maxseg;
11960 	int32_t csum_flags = 0;
11961  	int32_t hw_tls;
11962 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11963 	unsigned ipsec_optlen = 0;
11964 
11965 #endif
11966 	volatile int32_t sack_rxmit;
11967 	struct bbr_sendmap *rsm = NULL;
11968 	int32_t tso, mtu;
11969 	struct tcpopt to;
11970 	int32_t slot = 0;
11971 	struct inpcb *inp;
11972 	struct sockbuf *sb;
11973 	uint32_t hpts_calling;
11974 #ifdef INET6
11975 	struct ip6_hdr *ip6 = NULL;
11976 	int32_t isipv6;
11977 #endif
11978 	uint8_t app_limited = BBR_JR_SENT_DATA;
11979 	uint8_t filled_all = 0;
11980 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11981 	/* We take a cache hit here */
11982 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11983 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11984 	inp = bbr->rc_inp;
11985 	so = inp->inp_socket;
11986 	sb = &so->so_snd;
11987  	if (sb->sb_flags & SB_TLS_IFNET)
11988  		hw_tls = 1;
11989  	else
11990  		hw_tls = 0;
11991 	kern_prefetch(sb, &maxseg);
11992 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11993 	if (bbr_minseg(bbr) < maxseg) {
11994 		tcp_bbr_tso_size_check(bbr, cts);
11995 	}
11996 	/* Remove any flags that indicate we are pacing on the inp  */
11997 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11998 	p_maxseg = min(maxseg, pace_max_segs);
11999 	INP_WLOCK_ASSERT(inp);
12000 #ifdef TCP_OFFLOAD
12001 	if (tp->t_flags & TF_TOE)
12002 		return (tcp_offload_output(tp));
12003 #endif
12004 
12005 #ifdef INET6
12006 	if (bbr->r_state) {
12007 		/* Use the cache line loaded if possible */
12008 		isipv6 = bbr->r_is_v6;
12009 	} else {
12010 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
12011 	}
12012 #endif
12013 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
12014 	    inp->inp_in_hpts) {
12015 		/*
12016 		 * We are on the hpts for some timer but not hptsi output.
12017 		 * Possibly remove from the hpts so we can send/recv etc.
12018 		 */
12019 		if ((tp->t_flags & TF_ACKNOW) == 0) {
12020 			/*
12021 			 * No immediate demand right now to send an ack, but
12022 			 * the user may have read, making room for new data
12023 			 * (a window update). If so we may want to cancel
12024 			 * whatever timer is running (KEEP/DEL-ACK?) and
12025 			 * continue to send out a window update. Or we may
12026 			 * have gotten more data into the socket buffer to
12027 			 * send.
12028 			 */
12029 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12030 				      (long)TCP_MAXWIN << tp->rcv_scale);
12031 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
12032 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
12033 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
12034 			    (tp->snd_max - tp->snd_una))) {
12035 				/*
12036 				 * Nothing new to send and no window update
12037 				 * is needed to send. Lets just return and
12038 				 * let the timer-run off.
12039 				 */
12040 				return (0);
12041 			}
12042 		}
12043 		tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12044 		bbr_timer_cancel(bbr, __LINE__, cts);
12045 	}
12046 	if (bbr->r_ctl.rc_last_delay_val) {
12047 		/* Calculate a rough delay for early escape to sending  */
12048 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12049 			delay_calc = cts - bbr->rc_pacer_started;
12050 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12051 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12052 		else
12053 			delay_calc = 0;
12054 	}
12055 	/* Mark that we have called bbr_output(). */
12056 	if ((bbr->r_timer_override) ||
12057 	    (tp->t_state < TCPS_ESTABLISHED)) {
12058 		/* Timeouts or early states are exempt */
12059 		if (inp->inp_in_hpts)
12060 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12061 	} else if (inp->inp_in_hpts) {
12062 		if ((bbr->r_ctl.rc_last_delay_val) &&
12063 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
12064 		    delay_calc) {
12065 			/*
12066 			 * We were being paced for output and the delay has
12067 			 * already exceeded when we were supposed to be
12068 			 * called, lets go ahead and pull out of the hpts
12069 			 * and call output.
12070 			 */
12071 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
12072 			bbr->r_ctl.rc_last_delay_val = 0;
12073 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12074 		} else if (tp->t_state == TCPS_CLOSED) {
12075 			bbr->r_ctl.rc_last_delay_val = 0;
12076 			tcp_hpts_remove(inp, HPTS_REMOVE_OUTPUT);
12077 		} else {
12078 			/*
12079 			 * On the hpts, you shall not pass! even if ACKNOW
12080 			 * is on, we will when the hpts fires, unless of
12081 			 * course we are overdue.
12082 			 */
12083 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
12084 			return (0);
12085 		}
12086 	}
12087 	bbr->rc_cwnd_limited = 0;
12088 	if (bbr->r_ctl.rc_last_delay_val) {
12089 		/* recalculate the real delay and deal with over/under  */
12090 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12091 			delay_calc = cts - bbr->rc_pacer_started;
12092 		else
12093 			delay_calc = 0;
12094 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12095 			/* Setup the delay which will be added in */
12096 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12097 		else {
12098 			/*
12099 			 * We are early setup to adjust
12100 			 * our slot time.
12101 			 */
12102 			uint64_t merged_val;
12103 
12104 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12105 			bbr->r_agg_early_set = 1;
12106 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
12107 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12108 					/* Nope our previous late cancels out the early */
12109 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12110 					bbr->r_agg_early_set = 0;
12111 					bbr->r_ctl.rc_agg_early = 0;
12112 				} else {
12113 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12114 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
12115 				}
12116 			}
12117 			merged_val = bbr->rc_pacer_started;
12118 			merged_val <<= 32;
12119 			merged_val |= bbr->r_ctl.rc_last_delay_val;
12120 			bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
12121 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12122 						 bbr->r_agg_early_set, 3);
12123 			bbr->r_ctl.rc_last_delay_val = 0;
12124 			BBR_STAT_INC(bbr_early);
12125 			delay_calc = 0;
12126 		}
12127 	} else {
12128 		/* We were not delayed due to hptsi */
12129 		if (bbr->r_agg_early_set)
12130 			bbr->r_ctl.rc_agg_early = 0;
12131 		bbr->r_agg_early_set = 0;
12132 		delay_calc = 0;
12133 	}
12134 	if (delay_calc) {
12135 		/*
12136 		 * We had a hptsi delay which means we are falling behind on
12137 		 * sending at the expected rate. Calculate an extra amount
12138 		 * of data we can send, if any, to put us back on track.
12139 		 */
12140 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12141 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12142 		else
12143 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12144 	}
12145 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12146 	if ((tp->snd_una == tp->snd_max) &&
12147 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12148 	    (sbavail(sb))) {
12149 		/*
12150 		 * Ok we have been idle with nothing outstanding
12151 		 * we possibly need to start fresh with either a new
12152 		 * suite of states or a fast-ramp up.
12153 		 */
12154 		bbr_restart_after_idle(bbr,
12155 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12156 	}
12157 	/*
12158 	 * Now was there a hptsi delay where we are behind? We only count
12159 	 * being behind if: a) We are not in recovery. b) There was a delay.
12160 	 * <and> c) We had room to send something.
12161 	 *
12162 	 */
12163 	hpts_calling = inp->inp_hpts_calls;
12164 	inp->inp_hpts_calls = 0;
12165 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12166 		if (bbr_process_timers(tp, bbr, cts, hpts_calling)) {
12167 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12168 			return (0);
12169 		}
12170 	}
12171 	bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12172 	if (hpts_calling &&
12173 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12174 		bbr->r_ctl.rc_last_delay_val = 0;
12175 	}
12176 	bbr->r_timer_override = 0;
12177 	bbr->r_wanted_output = 0;
12178 	/*
12179 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12180 	 * SYN|ACK and those sent by the retransmit timer.
12181 	 */
12182 	if (IS_FASTOPEN(tp->t_flags) &&
12183 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12184 	     (tp->t_state == TCPS_SYN_SENT)) &&
12185 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12186 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12187 		len = 0;
12188 		goto just_return_nolock;
12189 	}
12190 	/*
12191 	 * Before sending anything check for a state update. For hpts
12192 	 * calling without input this is important. If its input calling
12193 	 * then this was already done.
12194 	 */
12195 	if (bbr->rc_use_google == 0)
12196 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12197 again:
12198 	/*
12199 	 * If we've recently taken a timeout, snd_max will be greater than
12200 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12201 	 * for historic reasons the persist timer still uses it. This means
12202 	 * we have to look at it. All retransmissions that are not persits
12203 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12204 	 * end of this routine we pull snd_nxt always up to snd_max.
12205 	 */
12206 	doing_tlp = 0;
12207 #ifdef BBR_INVARIANTS
12208 	doing_retran_from = picked_up_retran = 0;
12209 #endif
12210 	error = 0;
12211 	tso = 0;
12212 	slot = 0;
12213 	mtu = 0;
12214 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12215 	sb_offset = tp->snd_max - tp->snd_una;
12216 	flags = tcp_outflags[tp->t_state];
12217 	sack_rxmit = 0;
12218 	len = 0;
12219 	rsm = NULL;
12220 	if (flags & TH_RST) {
12221 		SOCKBUF_LOCK(sb);
12222 		goto send;
12223 	}
12224 recheck_resend:
12225 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12226 		/* We need to always have one in reserve */
12227 		rsm = bbr_alloc(bbr);
12228 		if (rsm == NULL) {
12229 			error = ENOMEM;
12230 			/* Lie to get on the hpts */
12231 			tot_len = tp->t_maxseg;
12232 			if (hpts_calling)
12233 				/* Retry in a ms */
12234 				slot = 1001;
12235 			goto just_return_nolock;
12236 		}
12237 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12238 		bbr->r_ctl.rc_free_cnt++;
12239 		rsm = NULL;
12240 	}
12241 	/* What do we send, a resend? */
12242 	if (bbr->r_ctl.rc_resend == NULL) {
12243 		/* Check for rack timeout */
12244 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12245 		if (bbr->r_ctl.rc_resend) {
12246 #ifdef BBR_INVARIANTS
12247 			picked_up_retran = 1;
12248 #endif
12249 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12250 		}
12251 	}
12252 	if (bbr->r_ctl.rc_resend) {
12253 		rsm = bbr->r_ctl.rc_resend;
12254 #ifdef BBR_INVARIANTS
12255 		doing_retran_from = 1;
12256 #endif
12257 		/* Remove any TLP flags its a RACK or T-O */
12258 		rsm->r_flags &= ~BBR_TLP;
12259 		bbr->r_ctl.rc_resend = NULL;
12260 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12261 #ifdef BBR_INVARIANTS
12262 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12263 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12264 			goto recheck_resend;
12265 #else
12266 			/* TSNH */
12267 			rsm = NULL;
12268 			goto recheck_resend;
12269 #endif
12270 		}
12271 		rtr_cnt++;
12272 		if (rsm->r_flags & BBR_HAS_SYN) {
12273 			/* Only retransmit a SYN by itself */
12274 			len = 0;
12275 			if ((flags & TH_SYN) == 0) {
12276 				/* Huh something is wrong */
12277 				rsm->r_start++;
12278 				if (rsm->r_start == rsm->r_end) {
12279 					/* Clean it up, somehow we missed the ack? */
12280 					bbr_log_syn(tp, NULL);
12281 				} else {
12282 					/* TFO with data? */
12283 					rsm->r_flags &= ~BBR_HAS_SYN;
12284 					len = rsm->r_end - rsm->r_start;
12285 				}
12286 			} else {
12287 				/* Retransmitting SYN */
12288 				rsm = NULL;
12289 				SOCKBUF_LOCK(sb);
12290 				goto send;
12291 			}
12292 		} else
12293 			len = rsm->r_end - rsm->r_start;
12294 		if ((bbr->rc_resends_use_tso == 0) &&
12295 		    (len > maxseg)) {
12296 			len = maxseg;
12297 			more_to_rxt = 1;
12298 		}
12299 		sb_offset = rsm->r_start - tp->snd_una;
12300 		if (len > 0) {
12301 			sack_rxmit = 1;
12302 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12303 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12304 			    min(len, maxseg));
12305 		} else {
12306 			/* I dont think this can happen */
12307 			rsm = NULL;
12308 			goto recheck_resend;
12309 		}
12310 		BBR_STAT_INC(bbr_resends_set);
12311 	} else if (bbr->r_ctl.rc_tlp_send) {
12312 		/*
12313 		 * Tail loss probe
12314 		 */
12315 		doing_tlp = 1;
12316 		rsm = bbr->r_ctl.rc_tlp_send;
12317 		bbr->r_ctl.rc_tlp_send = NULL;
12318 		sack_rxmit = 1;
12319 		len = rsm->r_end - rsm->r_start;
12320 		rtr_cnt++;
12321 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12322 			len = maxseg;
12323 
12324 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12325 #ifdef BBR_INVARIANTS
12326 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12327 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12328 #else
12329 			/* TSNH */
12330 			rsm = NULL;
12331 			goto recheck_resend;
12332 #endif
12333 		}
12334 		sb_offset = rsm->r_start - tp->snd_una;
12335 		BBR_STAT_INC(bbr_tlp_set);
12336 	}
12337 	/*
12338 	 * Enforce a connection sendmap count limit if set
12339 	 * as long as we are not retransmiting.
12340 	 */
12341 	if ((rsm == NULL) &&
12342 	    (V_tcp_map_entries_limit > 0) &&
12343 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12344 		BBR_STAT_INC(bbr_alloc_limited);
12345 		if (!bbr->alloc_limit_reported) {
12346 			bbr->alloc_limit_reported = 1;
12347 			BBR_STAT_INC(bbr_alloc_limited_conns);
12348 		}
12349 		goto just_return_nolock;
12350 	}
12351 #ifdef BBR_INVARIANTS
12352 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12353 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12354 		    tp, bbr, rsm, sb_offset, len);
12355 	}
12356 #endif
12357 	/*
12358 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12359 	 * state flags.
12360 	 */
12361 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12362 		flags |= TH_FIN;
12363 	if (tp->t_flags & TF_NEEDSYN)
12364 		flags |= TH_SYN;
12365 
12366 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12367 		/* we are retransmitting the fin */
12368 		len--;
12369 		if (len) {
12370 			/*
12371 			 * When retransmitting data do *not* include the
12372 			 * FIN. This could happen from a TLP probe if we
12373 			 * allowed data with a FIN.
12374 			 */
12375 			flags &= ~TH_FIN;
12376 		}
12377 	} else if (rsm) {
12378 		if (flags & TH_FIN)
12379 			flags &= ~TH_FIN;
12380 	}
12381 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12382 		void *end_rsm;
12383 
12384 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12385 		if (end_rsm)
12386 			kern_prefetch(end_rsm, &prefetch_rsm);
12387 		prefetch_rsm = 1;
12388 	}
12389 	SOCKBUF_LOCK(sb);
12390 	/*
12391 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12392 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12393 	 * negative length.  This can also occur when TCP opens up its
12394 	 * congestion window while receiving additional duplicate acks after
12395 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12396 	 * the fast-retransmit.
12397 	 *
12398 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12399 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12400 	 * up 0.
12401 	 *
12402 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12403 	 * in which case len is already set.
12404 	 */
12405 	if (sack_rxmit == 0) {
12406 		uint32_t avail;
12407 
12408 		avail = sbavail(sb);
12409 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12410 			sb_offset = tp->snd_max - tp->snd_una;
12411 		else
12412 			sb_offset = 0;
12413 		if (bbr->rc_tlp_new_data) {
12414 			/* TLP is forcing out new data */
12415 			uint32_t tlplen;
12416 
12417 			doing_tlp = 1;
12418 			tlplen = maxseg;
12419 
12420 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12421 				tlplen = (uint32_t)(avail - sb_offset);
12422 			}
12423 			if (tlplen > tp->snd_wnd) {
12424 				len = tp->snd_wnd;
12425 			} else {
12426 				len = tlplen;
12427 			}
12428 			bbr->rc_tlp_new_data = 0;
12429 		} else {
12430 			what_we_can = len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12431 			if ((len < p_maxseg) &&
12432 			    (bbr->rc_in_persist == 0) &&
12433 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12434 			    ((avail - sb_offset) >= p_maxseg)) {
12435 				/*
12436 				 * We are not completing whats in the socket
12437 				 * buffer (i.e. there is at least a segment
12438 				 * waiting to send) and we have 2 or more
12439 				 * segments outstanding. There is no sense
12440 				 * of sending a little piece. Lets defer and
12441 				 * and wait until we can send a whole
12442 				 * segment.
12443 				 */
12444 				len = 0;
12445 			}
12446 			if (bbr->rc_in_persist) {
12447 				/*
12448 				 * We are in persists, figure out if
12449 				 * a retransmit is available (maybe the previous
12450 				 * persists we sent) or if we have to send new
12451 				 * data.
12452 				 */
12453 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12454 				if (rsm) {
12455 					len = rsm->r_end - rsm->r_start;
12456 					if (rsm->r_flags & BBR_HAS_FIN)
12457 						len--;
12458 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12459 						len = maxseg;
12460 					if (len > 1)
12461 						BBR_STAT_INC(bbr_persist_reneg);
12462 					/*
12463 					 * XXXrrs we could force the len to
12464 					 * 1 byte here to cause the chunk to
12465 					 * split apart.. but that would then
12466 					 * mean we always retransmit it as
12467 					 * one byte even after the window
12468 					 * opens.
12469 					 */
12470 					sack_rxmit = 1;
12471 					sb_offset = rsm->r_start - tp->snd_una;
12472 				} else {
12473 					/*
12474 					 * First time through in persists or peer
12475 					 * acked our one byte. Though we do have
12476 					 * to have something in the sb.
12477 					 */
12478 					len = 1;
12479 					sb_offset = 0;
12480 					if (avail == 0)
12481 					    len = 0;
12482 				}
12483 			}
12484 		}
12485 	}
12486 	if (prefetch_so_done == 0) {
12487 		kern_prefetch(so, &prefetch_so_done);
12488 		prefetch_so_done = 1;
12489 	}
12490 	/*
12491 	 * Lop off SYN bit if it has already been sent.  However, if this is
12492 	 * SYN-SENT state and if segment contains data and if we don't know
12493 	 * that foreign host supports TAO, suppress sending segment.
12494 	 */
12495 	if ((flags & TH_SYN) && (rsm == NULL) &&
12496 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12497 		if (tp->t_state != TCPS_SYN_RECEIVED)
12498 			flags &= ~TH_SYN;
12499 		/*
12500 		 * When sending additional segments following a TFO SYN|ACK,
12501 		 * do not include the SYN bit.
12502 		 */
12503 		if (IS_FASTOPEN(tp->t_flags) &&
12504 		    (tp->t_state == TCPS_SYN_RECEIVED))
12505 			flags &= ~TH_SYN;
12506 		sb_offset--, len++;
12507 		if (sbavail(sb) == 0)
12508 			len = 0;
12509 	} else if ((flags & TH_SYN) && rsm) {
12510 		/*
12511 		 * Subtract one from the len for the SYN being
12512 		 * retransmitted.
12513 		 */
12514 		len--;
12515 	}
12516 	/*
12517 	 * Be careful not to send data and/or FIN on SYN segments. This
12518 	 * measure is needed to prevent interoperability problems with not
12519 	 * fully conformant TCP implementations.
12520 	 */
12521 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12522 		len = 0;
12523 		flags &= ~TH_FIN;
12524 	}
12525 	/*
12526 	 * On TFO sockets, ensure no data is sent in the following cases:
12527 	 *
12528 	 *  - When retransmitting SYN|ACK on a passively-created socket
12529 	 *  - When retransmitting SYN on an actively created socket
12530 	 *  - When sending a zero-length cookie (cookie request) on an
12531 	 *    actively created socket
12532 	 *  - When the socket is in the CLOSED state (RST is being sent)
12533 	 */
12534 	if (IS_FASTOPEN(tp->t_flags) &&
12535 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12536 	     ((tp->t_state == TCPS_SYN_SENT) &&
12537 	      (tp->t_tfo_client_cookie_len == 0)) ||
12538 	     (flags & TH_RST))) {
12539 		len = 0;
12540 		sack_rxmit = 0;
12541 		rsm = NULL;
12542 	}
12543 	/* Without fast-open there should never be data sent on a SYN */
12544 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12545 		len = 0;
12546 	if (len <= 0) {
12547 		/*
12548 		 * If FIN has been sent but not acked, but we haven't been
12549 		 * called to retransmit, len will be < 0.  Otherwise, window
12550 		 * shrank after we sent into it.  If window shrank to 0,
12551 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12552 		 * window, and set the persist timer if it isn't already
12553 		 * going.  If the window didn't close completely, just wait
12554 		 * for an ACK.
12555 		 *
12556 		 * We also do a general check here to ensure that we will
12557 		 * set the persist timer when we have data to send, but a
12558 		 * 0-byte window. This makes sure the persist timer is set
12559 		 * even if the packet hits one of the "goto send" lines
12560 		 * below.
12561 		 */
12562 		len = 0;
12563 		if ((tp->snd_wnd == 0) &&
12564 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12565 		    (tp->snd_una == tp->snd_max) &&
12566 		    (sb_offset < (int)sbavail(sb))) {
12567 			/*
12568 			 * Not enough room in the rwnd to send
12569 			 * a paced segment out.
12570 			 */
12571 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12572 		}
12573 	} else if ((rsm == NULL) &&
12574 		   (doing_tlp == 0) &&
12575 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12576 		/*
12577 		 * We are not sending a full segment for
12578 		 * some reason. Should we not send anything (think
12579 		 * sws or persists)?
12580 		 */
12581 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12582 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12583 		    (len < (int)(sbavail(sb) - sb_offset))) {
12584 			/*
12585 			 * Here the rwnd is less than
12586 			 * the pacing size, this is not a retransmit,
12587 			 * we are established and
12588 			 * the send is not the last in the socket buffer
12589 			 * lets not send, and possibly enter persists.
12590 			 */
12591 			len = 0;
12592 			if (tp->snd_max == tp->snd_una)
12593 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12594 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12595 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12596 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12597 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12598 			   (len < bbr_minseg(bbr))) {
12599 			/*
12600 			 * Here we are not retransmitting, and
12601 			 * the cwnd is not so small that we could
12602 			 * not send at least a min size (rxt timer
12603 			 * not having gone off), We have 2 segments or
12604 			 * more already in flight, its not the tail end
12605 			 * of the socket buffer  and the cwnd is blocking
12606 			 * us from sending out minimum pacing segment size.
12607 			 * Lets not send anything.
12608 			 */
12609 			bbr->rc_cwnd_limited = 1;
12610 			len = 0;
12611 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12612 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12613 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12614 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12615 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12616 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12617 			/*
12618 			 * Here we have a send window but we have
12619 			 * filled it up and we can't send another pacing segment.
12620 			 * We also have in flight more than 2 segments
12621 			 * and we are not completing the sb i.e. we allow
12622 			 * the last bytes of the sb to go out even if
12623 			 * its not a full pacing segment.
12624 			 */
12625 			len = 0;
12626 		}
12627 	}
12628 	/* len will be >= 0 after this point. */
12629 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12630 	tcp_sndbuf_autoscale(tp, so, sendwin);
12631 	/*
12632 	 *
12633 	 */
12634 	if (bbr->rc_in_persist &&
12635 	    len &&
12636 	    (rsm == NULL) &&
12637 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12638 		/*
12639 		 * We are in persist, not doing a retransmit and don't have enough space
12640 		 * yet to send a full TSO. So is it at the end of the sb
12641 		 * if so we need to send else nuke to 0 and don't send.
12642 		 */
12643 		int sbleft;
12644 		if (sbavail(sb) > sb_offset)
12645 			sbleft = sbavail(sb) - sb_offset;
12646 		else
12647 			sbleft = 0;
12648 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12649 			/* not at end of sb lets not send */
12650 			len = 0;
12651 		}
12652 	}
12653 	/*
12654 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12655 	 * hardware).
12656 	 *
12657 	 * TSO may only be used if we are in a pure bulk sending state.  The
12658 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12659 	 * options prevent using TSO.  With TSO the TCP header is the same
12660 	 * (except for the sequence number) for all generated packets.  This
12661 	 * makes it impossible to transmit any options which vary per
12662 	 * generated segment or packet.
12663 	 *
12664 	 * IPv4 handling has a clear separation of ip options and ip header
12665 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12666 	 * does the right thing below to provide length of just ip options
12667 	 * and thus checking for ipoptlen is enough to decide if ip options
12668 	 * are present.
12669 	 */
12670 #ifdef INET6
12671 	if (isipv6)
12672 		ipoptlen = ip6_optlen(inp);
12673 	else
12674 #endif
12675 	if (inp->inp_options)
12676 		ipoptlen = inp->inp_options->m_len -
12677 		    offsetof(struct ipoption, ipopt_list);
12678 	else
12679 		ipoptlen = 0;
12680 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12681 	/*
12682 	 * Pre-calculate here as we save another lookup into the darknesses
12683 	 * of IPsec that way and can actually decide if TSO is ok.
12684 	 */
12685 #ifdef INET6
12686 	if (isipv6 && IPSEC_ENABLED(ipv6))
12687 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12688 #ifdef INET
12689 	else
12690 #endif
12691 #endif				/* INET6 */
12692 #ifdef INET
12693 	if (IPSEC_ENABLED(ipv4))
12694 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12695 #endif				/* INET */
12696 #endif				/* IPSEC */
12697 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12698 	ipoptlen += ipsec_optlen;
12699 #endif
12700 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12701 	    (len > maxseg) &&
12702 	    (tp->t_port == 0) &&
12703 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12704 	    tp->rcv_numsacks == 0 &&
12705 	    ipoptlen == 0)
12706 		tso = 1;
12707 
12708 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12709 	    (long)TCP_MAXWIN << tp->rcv_scale);
12710 	/*
12711 	 * Sender silly window avoidance.   We transmit under the following
12712 	 * conditions when len is non-zero:
12713 	 *
12714 	 * - We have a full segment (or more with TSO) - This is the last
12715 	 * buffer in a write()/send() and we are either idle or running
12716 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12717 	 * then 1/2 the maximum send window's worth of data (receiver may be
12718 	 * limited the window size) - we need to retransmit
12719 	 */
12720 	if (rsm)
12721 		goto send;
12722 	if (len) {
12723 		if (sack_rxmit)
12724 			goto send;
12725 		if (len >= p_maxseg)
12726 			goto send;
12727 		/*
12728 		 * NOTE! on localhost connections an 'ack' from the remote
12729 		 * end may occur synchronously with the output and cause us
12730 		 * to flush a buffer queued with moretocome.  XXX
12731 		 *
12732 		 */
12733 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12734 		    ((tp->t_flags & TF_NODELAY) ||
12735 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12736 		    (tp->t_flags & TF_NOPUSH) == 0) {
12737 			goto send;
12738 		}
12739 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12740 			goto send;
12741 		}
12742 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12743 			goto send;
12744 		}
12745 	}
12746 	/*
12747 	 * Sending of standalone window updates.
12748 	 *
12749 	 * Window updates are important when we close our window due to a
12750 	 * full socket buffer and are opening it again after the application
12751 	 * reads data from it.  Once the window has opened again and the
12752 	 * remote end starts to send again the ACK clock takes over and
12753 	 * provides the most current window information.
12754 	 *
12755 	 * We must avoid the silly window syndrome whereas every read from
12756 	 * the receive buffer, no matter how small, causes a window update
12757 	 * to be sent.  We also should avoid sending a flurry of window
12758 	 * updates when the socket buffer had queued a lot of data and the
12759 	 * application is doing small reads.
12760 	 *
12761 	 * Prevent a flurry of pointless window updates by only sending an
12762 	 * update when we can increase the advertized window by more than
12763 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12764 	 * full or is very small be more aggressive and send an update
12765 	 * whenever we can increase by two mss sized segments. In all other
12766 	 * situations the ACK's to new incoming data will carry further
12767 	 * window increases.
12768 	 *
12769 	 * Don't send an independent window update if a delayed ACK is
12770 	 * pending (it will get piggy-backed on it) or the remote side
12771 	 * already has done a half-close and won't send more data.  Skip
12772 	 * this if the connection is in T/TCP half-open state.
12773 	 */
12774 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12775 	    !(tp->t_flags & TF_DELACK) &&
12776 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12777 		/* Check to see if we should do a window update */
12778 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12779 			goto send;
12780 	}
12781 	/*
12782 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12783 	 * is also a catch-all for the retransmit timer timeout case.
12784 	 */
12785 	if (tp->t_flags & TF_ACKNOW) {
12786 		goto send;
12787 	}
12788 	if (flags & TH_RST) {
12789 		/* Always send a RST if one is due */
12790 		goto send;
12791 	}
12792 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12793 		goto send;
12794 	}
12795 	/*
12796 	 * If our state indicates that FIN should be sent and we have not
12797 	 * yet done so, then we need to send.
12798 	 */
12799 	if (flags & TH_FIN &&
12800 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12801 		goto send;
12802 	}
12803 	/*
12804 	 * No reason to send a segment, just return.
12805 	 */
12806 just_return:
12807 	SOCKBUF_UNLOCK(sb);
12808 just_return_nolock:
12809 	if (tot_len)
12810 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12811 	if (bbr->rc_no_pacing)
12812 		slot = 0;
12813 	if (tot_len == 0) {
12814 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12815 		    tp->snd_wnd) {
12816 			BBR_STAT_INC(bbr_rwnd_limited);
12817 			app_limited = BBR_JR_RWND_LIMITED;
12818 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12819 			if ((bbr->rc_in_persist == 0) &&
12820 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12821 			    (tp->snd_max == tp->snd_una) &&
12822 			    sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
12823 				/* No send window.. we must enter persist */
12824 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12825 			}
12826 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12827 			BBR_STAT_INC(bbr_app_limited);
12828 			app_limited = BBR_JR_APP_LIMITED;
12829 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12830 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12831 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12832 			BBR_STAT_INC(bbr_cwnd_limited);
12833  			app_limited = BBR_JR_CWND_LIMITED;
12834 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12835 									bbr->r_ctl.rc_lost_bytes)));
12836 			bbr->rc_cwnd_limited = 1;
12837 		} else {
12838 			BBR_STAT_INC(bbr_app_limited);
12839 			app_limited = BBR_JR_APP_LIMITED;
12840 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12841 		}
12842 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12843 		bbr->r_agg_early_set = 0;
12844 		bbr->r_ctl.rc_agg_early = 0;
12845 		bbr->r_ctl.rc_last_delay_val = 0;
12846 	} else if (bbr->rc_use_google == 0)
12847 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12848 	/* Are we app limited? */
12849 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12850 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12851 		/**
12852 		 * We are application limited.
12853 		 */
12854 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12855 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12856 	}
12857 	if (tot_len == 0)
12858 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12859 	/* Dont update the time if we did not send */
12860 	bbr->r_ctl.rc_last_delay_val = 0;
12861 	bbr->rc_output_starts_timer = 1;
12862 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12863 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12864 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12865 		/* Make sure snd_nxt is drug up */
12866 		tp->snd_nxt = tp->snd_max;
12867 	}
12868 	return (error);
12869 
12870 send:
12871 	if (doing_tlp == 0) {
12872 		/*
12873 		 * Data not a TLP, and its not the rxt firing. If it is the
12874 		 * rxt firing, we want to leave the tlp_in_progress flag on
12875 		 * so we don't send another TLP. It has to be a rack timer
12876 		 * or normal send (response to acked data) to clear the tlp
12877 		 * in progress flag.
12878 		 */
12879 		bbr->rc_tlp_in_progress = 0;
12880 		bbr->rc_tlp_rtx_out = 0;
12881 	} else {
12882 		/*
12883 		 * Its a TLP.
12884 		 */
12885 		bbr->rc_tlp_in_progress = 1;
12886 	}
12887 	bbr_timer_cancel(bbr, __LINE__, cts);
12888 	if (rsm == NULL) {
12889 		if (sbused(sb) > 0) {
12890 			/*
12891 			 * This is sub-optimal. We only send a stand alone
12892 			 * FIN on its own segment.
12893 			 */
12894 			if (flags & TH_FIN) {
12895 				flags &= ~TH_FIN;
12896 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12897 					/* Lets not send this */
12898 					slot = 0;
12899 					goto just_return;
12900 				}
12901 			}
12902 		}
12903 	} else {
12904 		/*
12905 		 * We do *not* send a FIN on a retransmit if it has data.
12906 		 * The if clause here where len > 1 should never come true.
12907 		 */
12908 		if ((len > 0) &&
12909 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12910 		    (flags & TH_FIN))) {
12911 			flags &= ~TH_FIN;
12912 			len--;
12913 		}
12914 	}
12915 	SOCKBUF_LOCK_ASSERT(sb);
12916 	if (len > 0) {
12917 		if ((tp->snd_una == tp->snd_max) &&
12918 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12919 			/*
12920 			 * This qualifies as a RTT_PROBE session since we
12921 			 * drop the data outstanding to nothing and waited
12922 			 * more than bbr_rtt_probe_time.
12923 			 */
12924 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12925 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12926 		}
12927 		if (len >= maxseg)
12928 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12929 		else
12930 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12931 	}
12932 	/*
12933 	 * Before ESTABLISHED, force sending of initial options unless TCP
12934 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12935 	 * plus TCP options always fit in a single mbuf, leaving room for a
12936 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12937 	 * + optlen <= MCLBYTES
12938 	 */
12939 	optlen = 0;
12940 #ifdef INET6
12941 	if (isipv6)
12942 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12943 	else
12944 #endif
12945 		hdrlen = sizeof(struct tcpiphdr);
12946 
12947 	/*
12948 	 * Compute options for segment. We only have to care about SYN and
12949 	 * established connection segments.  Options for SYN-ACK segments
12950 	 * are handled in TCP syncache.
12951 	 */
12952 	to.to_flags = 0;
12953 	local_options = 0;
12954 	if ((tp->t_flags & TF_NOOPT) == 0) {
12955 		/* Maximum segment size. */
12956 		if (flags & TH_SYN) {
12957 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12958 			if (tp->t_port)
12959 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12960 			to.to_flags |= TOF_MSS;
12961 			/*
12962 			 * On SYN or SYN|ACK transmits on TFO connections,
12963 			 * only include the TFO option if it is not a
12964 			 * retransmit, as the presence of the TFO option may
12965 			 * have caused the original SYN or SYN|ACK to have
12966 			 * been dropped by a middlebox.
12967 			 */
12968 			if (IS_FASTOPEN(tp->t_flags) &&
12969 			    (tp->t_rxtshift == 0)) {
12970 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12971 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12972 					to.to_tfo_cookie =
12973 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12974 					to.to_flags |= TOF_FASTOPEN;
12975 					wanted_cookie = 1;
12976 				} else if (tp->t_state == TCPS_SYN_SENT) {
12977 					to.to_tfo_len =
12978 					    tp->t_tfo_client_cookie_len;
12979 					to.to_tfo_cookie =
12980 					    tp->t_tfo_cookie.client;
12981 					to.to_flags |= TOF_FASTOPEN;
12982 					wanted_cookie = 1;
12983 				}
12984 			}
12985 		}
12986 		/* Window scaling. */
12987 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12988 			to.to_wscale = tp->request_r_scale;
12989 			to.to_flags |= TOF_SCALE;
12990 		}
12991 		/* Timestamps. */
12992 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12993 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12994 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12995 			to.to_tsecr = tp->ts_recent;
12996 			to.to_flags |= TOF_TS;
12997 			local_options += TCPOLEN_TIMESTAMP + 2;
12998 		}
12999 		/* Set receive buffer autosizing timestamp. */
13000 		if (tp->rfbuf_ts == 0 &&
13001 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
13002 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
13003 		/* Selective ACK's. */
13004 		if (flags & TH_SYN)
13005 			to.to_flags |= TOF_SACKPERM;
13006 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13007 		    tp->rcv_numsacks > 0) {
13008 			to.to_flags |= TOF_SACK;
13009 			to.to_nsacks = tp->rcv_numsacks;
13010 			to.to_sacks = (u_char *)tp->sackblks;
13011 		}
13012 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13013 		/* TCP-MD5 (RFC2385). */
13014 		if (tp->t_flags & TF_SIGNATURE)
13015 			to.to_flags |= TOF_SIGNATURE;
13016 #endif				/* TCP_SIGNATURE */
13017 
13018 		/* Processing the options. */
13019 		hdrlen += (optlen = tcp_addoptions(&to, opt));
13020 		/*
13021 		 * If we wanted a TFO option to be added, but it was unable
13022 		 * to fit, ensure no data is sent.
13023 		 */
13024 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
13025 		    !(to.to_flags & TOF_FASTOPEN))
13026 			len = 0;
13027 	}
13028 	if (tp->t_port) {
13029 		if (V_tcp_udp_tunneling_port == 0) {
13030 			/* The port was removed?? */
13031 			SOCKBUF_UNLOCK(&so->so_snd);
13032 			return (EHOSTUNREACH);
13033 		}
13034 		hdrlen += sizeof(struct udphdr);
13035 	}
13036 #ifdef INET6
13037 	if (isipv6)
13038 		ipoptlen = ip6_optlen(tp->t_inpcb);
13039 	else
13040 #endif
13041 	if (tp->t_inpcb->inp_options)
13042 		ipoptlen = tp->t_inpcb->inp_options->m_len -
13043 		    offsetof(struct ipoption, ipopt_list);
13044 	else
13045 		ipoptlen = 0;
13046 	ipoptlen = 0;
13047 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
13048 	ipoptlen += ipsec_optlen;
13049 #endif
13050 	if (bbr->rc_last_options != local_options) {
13051 		/*
13052 		 * Cache the options length this generally does not change
13053 		 * on a connection. We use this to calculate TSO.
13054 		 */
13055 		bbr->rc_last_options = local_options;
13056 	}
13057 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
13058 	p_maxseg = min(maxseg, pace_max_segs);
13059 	/*
13060 	 * Adjust data length if insertion of options will bump the packet
13061 	 * length beyond the t_maxseg length. Clear the FIN bit because we
13062 	 * cut off the tail of the segment.
13063 	 */
13064 	if (len > maxseg) {
13065 		if (len != 0 && (flags & TH_FIN)) {
13066 			flags &= ~TH_FIN;
13067 		}
13068 		if (tso) {
13069 			uint32_t moff;
13070 			int32_t max_len;
13071 
13072 			/* extract TSO information */
13073 			if_hw_tsomax = tp->t_tsomax;
13074 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
13075 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
13076 			KASSERT(ipoptlen == 0,
13077 			    ("%s: TSO can't do IP options", __func__));
13078 
13079 			/*
13080 			 * Check if we should limit by maximum payload
13081 			 * length:
13082 			 */
13083 			if (if_hw_tsomax != 0) {
13084 				/* compute maximum TSO length */
13085 				max_len = (if_hw_tsomax - hdrlen -
13086 				    max_linkhdr);
13087 				if (max_len <= 0) {
13088 					len = 0;
13089 				} else if (len > max_len) {
13090 					len = max_len;
13091 				}
13092 			}
13093 			/*
13094 			 * Prevent the last segment from being fractional
13095 			 * unless the send sockbuf can be emptied:
13096 			 */
13097 			if ((sb_offset + len) < sbavail(sb)) {
13098 				moff = len % (uint32_t)maxseg;
13099 				if (moff != 0) {
13100 					len -= moff;
13101 				}
13102 			}
13103 			/*
13104 			 * In case there are too many small fragments don't
13105 			 * use TSO:
13106 			 */
13107 			if (len <= maxseg) {
13108 				len = maxseg;
13109 				tso = 0;
13110 			}
13111 		} else {
13112 			/* Not doing TSO */
13113 			if (optlen + ipoptlen >= tp->t_maxseg) {
13114 				/*
13115 				 * Since we don't have enough space to put
13116 				 * the IP header chain and the TCP header in
13117 				 * one packet as required by RFC 7112, don't
13118 				 * send it. Also ensure that at least one
13119 				 * byte of the payload can be put into the
13120 				 * TCP segment.
13121 				 */
13122 				SOCKBUF_UNLOCK(&so->so_snd);
13123 				error = EMSGSIZE;
13124 				sack_rxmit = 0;
13125 				goto out;
13126 			}
13127 			len = maxseg;
13128 		}
13129 	} else {
13130 		/* Not doing TSO */
13131 		if_hw_tsomaxsegcount = 0;
13132 		tso = 0;
13133 	}
13134 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13135 	    ("%s: len > IP_MAXPACKET", __func__));
13136 #ifdef DIAGNOSTIC
13137 #ifdef INET6
13138 	if (max_linkhdr + hdrlen > MCLBYTES)
13139 #else
13140 	if (max_linkhdr + hdrlen > MHLEN)
13141 #endif
13142 		panic("tcphdr too big");
13143 #endif
13144 	/*
13145 	 * This KASSERT is here to catch edge cases at a well defined place.
13146 	 * Before, those had triggered (random) panic conditions further
13147 	 * down.
13148 	 */
13149 #ifdef BBR_INVARIANTS
13150 	if (sack_rxmit) {
13151 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13152 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13153 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13154 		}
13155 	}
13156 #endif
13157 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13158 	if ((len == 0) &&
13159 	    (flags & TH_FIN) &&
13160 	    (sbused(sb))) {
13161 		/*
13162 		 * We have outstanding data, don't send a fin by itself!.
13163 		 */
13164 		slot = 0;
13165 		goto just_return;
13166 	}
13167 	/*
13168 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13169 	 * and initialize the header from the template for sends on this
13170 	 * connection.
13171 	 */
13172 	if (len) {
13173 		uint32_t moff;
13174 		uint32_t orig_len;
13175 
13176 		/*
13177 		 * We place a limit on sending with hptsi.
13178 		 */
13179 		if ((rsm == NULL) && len > pace_max_segs)
13180 			len = pace_max_segs;
13181 		if (len <= maxseg)
13182 			tso = 0;
13183 #ifdef INET6
13184 		if (MHLEN < hdrlen + max_linkhdr)
13185 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13186 		else
13187 #endif
13188 			m = m_gethdr(M_NOWAIT, MT_DATA);
13189 
13190 		if (m == NULL) {
13191 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13192 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13193 			SOCKBUF_UNLOCK(sb);
13194 			error = ENOBUFS;
13195 			sack_rxmit = 0;
13196 			goto out;
13197 		}
13198 		m->m_data += max_linkhdr;
13199 		m->m_len = hdrlen;
13200 		/*
13201 		 * Start the m_copy functions from the closest mbuf to the
13202 		 * sb_offset in the socket buffer chain.
13203 		 */
13204 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13205 #ifdef BBR_INVARIANTS
13206 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13207 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13208 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13209 				    doing_retran_from,
13210 				    picked_up_retran,
13211 				    doing_tlp);
13212 
13213 #endif
13214 			/*
13215 			 * In this messed up situation we have two choices,
13216 			 * a) pretend the send worked, and just start timers
13217 			 * and what not (not good since that may lead us
13218 			 * back here a lot). <or> b) Send the lowest segment
13219 			 * in the map. <or> c) Drop the connection. Lets do
13220 			 * <b> which if it continues to happen will lead to
13221 			 * <c> via timeouts.
13222 			 */
13223 			BBR_STAT_INC(bbr_offset_recovery);
13224 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13225 			sb_offset = 0;
13226 			if (rsm == NULL) {
13227 				sack_rxmit = 0;
13228 				len = sbavail(sb);
13229 			} else {
13230 				sack_rxmit = 1;
13231 				if (rsm->r_start != tp->snd_una) {
13232 					/*
13233 					 * Things are really messed up, <c>
13234 					 * is the only thing to do.
13235 					 */
13236 					BBR_STAT_INC(bbr_offset_drop);
13237 					tcp_set_inp_to_drop(inp, EFAULT);
13238 					SOCKBUF_UNLOCK(sb);
13239 					(void)m_free(m);
13240 					return (0);
13241 				}
13242 				len = rsm->r_end - rsm->r_start;
13243 			}
13244 			if (len > sbavail(sb))
13245 				len = sbavail(sb);
13246 			if (len > maxseg)
13247 				len = maxseg;
13248 		}
13249 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13250 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13251 			m_copydata(mb, moff, (int)len,
13252 			    mtod(m, caddr_t)+hdrlen);
13253 			if (rsm == NULL)
13254 				sbsndptr_adv(sb, mb, len);
13255 			m->m_len += len;
13256 		} else {
13257 			struct sockbuf *msb;
13258 
13259 			if (rsm)
13260 				msb = NULL;
13261 			else
13262 				msb = sb;
13263 #ifdef BBR_INVARIANTS
13264 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13265 				if (rsm) {
13266 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u rsm:%p snd_una:%u rsm_start:%u flg:%x %u:%u:%u sr:%d ",
13267 					    tp, bbr, len, moff,
13268 					    sbavail(sb), rsm,
13269 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13270 					    doing_retran_from,
13271 					    picked_up_retran,
13272 					    doing_tlp, sack_rxmit);
13273 				} else {
13274 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13275 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13276 				}
13277 			}
13278 #endif
13279 			orig_len = len;
13280 			m->m_next = tcp_m_copym(
13281 				mb, moff, &len,
13282 				if_hw_tsomaxsegcount,
13283 				if_hw_tsomaxsegsize, msb,
13284 				((rsm == NULL) ? hw_tls : 0)
13285 #ifdef NETFLIX_COPY_ARGS
13286 				, &filled_all
13287 #endif
13288 				);
13289 			if (len <= maxseg) {
13290 				/*
13291 				 * Must have ran out of mbufs for the copy
13292 				 * shorten it to no longer need tso. Lets
13293 				 * not put on sendalot since we are low on
13294 				 * mbufs.
13295 				 */
13296 				tso = 0;
13297 			}
13298 			if (m->m_next == NULL) {
13299 				SOCKBUF_UNLOCK(sb);
13300 				(void)m_free(m);
13301 				error = ENOBUFS;
13302 				sack_rxmit = 0;
13303 				goto out;
13304 			}
13305 		}
13306 #ifdef BBR_INVARIANTS
13307 		if (tso && len < maxseg) {
13308 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13309 			    tp, len, maxseg);
13310 		}
13311 		if (tso && if_hw_tsomaxsegcount) {
13312 			int32_t seg_cnt = 0;
13313 			struct mbuf *foo;
13314 
13315 			foo = m;
13316 			while (foo) {
13317 				seg_cnt++;
13318 				foo = foo->m_next;
13319 			}
13320 			if (seg_cnt > if_hw_tsomaxsegcount) {
13321 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13322 			}
13323 		}
13324 #endif
13325 		/*
13326 		 * If we're sending everything we've got, set PUSH. (This
13327 		 * will keep happy those implementations which only give
13328 		 * data to the user when a buffer fills or a PUSH comes in.)
13329 		 */
13330 		if (sb_offset + len == sbused(sb) &&
13331 		    sbused(sb) &&
13332 		    !(flags & TH_SYN)) {
13333 			flags |= TH_PUSH;
13334 		}
13335 		SOCKBUF_UNLOCK(sb);
13336 	} else {
13337 		SOCKBUF_UNLOCK(sb);
13338 		if (tp->t_flags & TF_ACKNOW)
13339 			KMOD_TCPSTAT_INC(tcps_sndacks);
13340 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13341 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13342 		else
13343 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13344 
13345 		m = m_gethdr(M_NOWAIT, MT_DATA);
13346 		if (m == NULL) {
13347 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13348 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13349 			error = ENOBUFS;
13350 			/* Fudge the send time since we could not send */
13351 			sack_rxmit = 0;
13352 			goto out;
13353 		}
13354 #ifdef INET6
13355 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13356 		    MHLEN >= hdrlen) {
13357 			M_ALIGN(m, hdrlen);
13358 		} else
13359 #endif
13360 			m->m_data += max_linkhdr;
13361 		m->m_len = hdrlen;
13362 	}
13363 	SOCKBUF_UNLOCK_ASSERT(sb);
13364 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13365 #ifdef MAC
13366 	mac_inpcb_create_mbuf(inp, m);
13367 #endif
13368 #ifdef INET6
13369 	if (isipv6) {
13370 		ip6 = mtod(m, struct ip6_hdr *);
13371 		if (tp->t_port) {
13372 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13373 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13374 			udp->uh_dport = tp->t_port;
13375 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13376 			udp->uh_ulen = htons(ulen);
13377 			th = (struct tcphdr *)(udp + 1);
13378 		} else {
13379 			th = (struct tcphdr *)(ip6 + 1);
13380 		}
13381 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13382 	} else
13383 #endif				/* INET6 */
13384 	{
13385 		ip = mtod(m, struct ip *);
13386 #ifdef TCPDEBUG
13387 		ipov = (struct ipovly *)ip;
13388 #endif
13389 		if (tp->t_port) {
13390 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13391 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13392 			udp->uh_dport = tp->t_port;
13393 			ulen = hdrlen + len - sizeof(struct ip);
13394 			udp->uh_ulen = htons(ulen);
13395 			th = (struct tcphdr *)(udp + 1);
13396 		} else {
13397 			th = (struct tcphdr *)(ip + 1);
13398 		}
13399 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13400 	}
13401 	/*
13402 	 * If we are doing retransmissions, then snd_nxt will not reflect
13403 	 * the first unsent octet.  For ACK only packets, we do not want the
13404 	 * sequence number of the retransmitted packet, we want the sequence
13405 	 * number of the next unsent octet.  So, if there is no data (and no
13406 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13407 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13408 	 * one byte beyond the right edge of the window, so use snd_nxt in
13409 	 * that case, since we know we aren't doing a retransmission.
13410 	 * (retransmit and persist are mutually exclusive...)
13411 	 */
13412 	if (sack_rxmit == 0) {
13413 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13414 			/* New data (including new persists) */
13415 			th->th_seq = htonl(tp->snd_max);
13416 			bbr_seq = tp->snd_max;
13417 		} else if (flags & TH_SYN) {
13418 			/* Syn's always send from iss */
13419 			th->th_seq = htonl(tp->iss);
13420 			bbr_seq = tp->iss;
13421 		} else if (flags & TH_FIN) {
13422 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13423 				/*
13424 				 * If we sent the fin already its 1 minus
13425 				 * snd_max
13426 				 */
13427 				th->th_seq = (htonl(tp->snd_max - 1));
13428 				bbr_seq = (tp->snd_max - 1);
13429 			} else {
13430 				/* First time FIN use snd_max */
13431 				th->th_seq = htonl(tp->snd_max);
13432 				bbr_seq = tp->snd_max;
13433 			}
13434 		} else {
13435 			/*
13436 			 * len == 0 and not persist we use snd_max, sending
13437 			 * an ack unless we have sent the fin then its 1
13438 			 * minus.
13439 			 */
13440 			/*
13441 			 * XXXRRS Question if we are in persists and we have
13442 			 * nothing outstanding to send and we have not sent
13443 			 * a FIN, we will send an ACK. In such a case it
13444 			 * might be better to send (tp->snd_una - 1) which
13445 			 * would force the peer to ack.
13446 			 */
13447 			if (tp->t_flags & TF_SENTFIN) {
13448 				th->th_seq = htonl(tp->snd_max - 1);
13449 				bbr_seq = (tp->snd_max - 1);
13450 			} else {
13451 				th->th_seq = htonl(tp->snd_max);
13452 				bbr_seq = tp->snd_max;
13453 			}
13454 		}
13455 	} else {
13456 		/* All retransmits use the rsm to guide the send */
13457 		th->th_seq = htonl(rsm->r_start);
13458 		bbr_seq = rsm->r_start;
13459 	}
13460 	th->th_ack = htonl(tp->rcv_nxt);
13461 	if (optlen) {
13462 		bcopy(opt, th + 1, optlen);
13463 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13464 	}
13465 	th->th_flags = flags;
13466 	/*
13467 	 * Calculate receive window.  Don't shrink window, but avoid silly
13468 	 * window syndrome.
13469 	 */
13470 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13471 				  recwin < maxseg)))
13472 		recwin = 0;
13473 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13474 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13475 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13476 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13477 		recwin = TCP_MAXWIN << tp->rcv_scale;
13478 
13479 	/*
13480 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13481 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13482 	 * handled in syncache.
13483 	 */
13484 	if (flags & TH_SYN)
13485 		th->th_win = htons((u_short)
13486 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13487 	else {
13488 		/* Avoid shrinking window with window scaling. */
13489 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13490 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13491 	}
13492 	/*
13493 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13494 	 * window.  This may cause the remote transmitter to stall.  This
13495 	 * flag tells soreceive() to disable delayed acknowledgements when
13496 	 * draining the buffer.  This can occur if the receiver is
13497 	 * attempting to read more data than can be buffered prior to
13498 	 * transmitting on the connection.
13499 	 */
13500 	if (th->th_win == 0) {
13501 		tp->t_sndzerowin++;
13502 		tp->t_flags |= TF_RXWIN0SENT;
13503 	} else
13504 		tp->t_flags &= ~TF_RXWIN0SENT;
13505 	/*
13506 	 * We don't support urgent data, but drag along
13507 	 * the pointer in case of a stack switch.
13508 	 */
13509 	tp->snd_up = tp->snd_una;
13510 
13511 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13512 	if (to.to_flags & TOF_SIGNATURE) {
13513 		/*
13514 		 * Calculate MD5 signature and put it into the place
13515 		 * determined before. NOTE: since TCP options buffer doesn't
13516 		 * point into mbuf's data, calculate offset and use it.
13517 		 */
13518 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13519 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13520 			/*
13521 			 * Do not send segment if the calculation of MD5
13522 			 * digest has failed.
13523 			 */
13524 			goto out;
13525 		}
13526 	}
13527 #endif
13528 
13529 	/*
13530 	 * Put TCP length in extended header, and then checksum extended
13531 	 * header and data.
13532 	 */
13533 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13534 #ifdef INET6
13535 	if (isipv6) {
13536 		/*
13537 		 * ip6_plen is not need to be filled now, and will be filled
13538 		 * in ip6_output.
13539 		 */
13540 		if (tp->t_port) {
13541 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13542 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13543 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13544 			th->th_sum = htons(0);
13545 			UDPSTAT_INC(udps_opackets);
13546 		} else {
13547 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13548 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13549 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13550 			    optlen + len, IPPROTO_TCP, 0);
13551 		}
13552 	}
13553 #endif
13554 #if defined(INET6) && defined(INET)
13555 	else
13556 #endif
13557 #ifdef INET
13558 	{
13559 		if (tp->t_port) {
13560 			m->m_pkthdr.csum_flags = CSUM_UDP;
13561 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13562 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13563 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13564 			th->th_sum = htons(0);
13565 			UDPSTAT_INC(udps_opackets);
13566 		} else {
13567 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13568 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13569 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13570 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13571 			    IPPROTO_TCP + len + optlen));
13572 		}
13573 		/* IP version must be set here for ipv4/ipv6 checking later */
13574 		KASSERT(ip->ip_v == IPVERSION,
13575 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13576 	}
13577 #endif
13578 
13579 	/*
13580 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13581 	 * header checksum is always provided. XXX: Fixme: This is currently
13582 	 * not the case for IPv6.
13583 	 */
13584 	if (tso) {
13585 		KASSERT(len > maxseg,
13586 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13587 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13588 		csum_flags |= CSUM_TSO;
13589 		m->m_pkthdr.tso_segsz = maxseg;
13590 	}
13591 	KASSERT(len + hdrlen == m_length(m, NULL),
13592 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13593 	    __func__, len, hdrlen, m_length(m, NULL)));
13594 
13595 #ifdef TCP_HHOOK
13596 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13597 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13598 #endif
13599 #ifdef TCPDEBUG
13600 	/*
13601 	 * Trace.
13602 	 */
13603 	if (so->so_options & SO_DEBUG) {
13604 		u_short save = 0;
13605 
13606 #ifdef INET6
13607 		if (!isipv6)
13608 #endif
13609 		{
13610 			save = ipov->ih_len;
13611 			ipov->ih_len = htons(m->m_pkthdr.len	/* - hdrlen +
13612 			      * (th->th_off << 2) */ );
13613 		}
13614 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13615 #ifdef INET6
13616 		if (!isipv6)
13617 #endif
13618 			ipov->ih_len = save;
13619 	}
13620 #endif				/* TCPDEBUG */
13621 
13622 	/* Log to the black box */
13623 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13624 		union tcp_log_stackspecific log;
13625 
13626 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13627 		/* Record info on type of transmission */
13628 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13629 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13630 		log.u_bbr.flex3 = maxseg;
13631 		log.u_bbr.flex4 = delay_calc;
13632 		/* Encode filled_all into the upper flex5 bit */
13633 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13634 		log.u_bbr.flex5 <<= 1;
13635 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13636 		log.u_bbr.flex5 <<= 29;
13637 		if (filled_all)
13638 			log.u_bbr.flex5 |= 0x80000000;
13639 		log.u_bbr.flex5 |= tp->t_maxseg;
13640 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13641 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13642 		/* lets poke in the low and the high here for debugging */
13643 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13644 		if (rsm || sack_rxmit) {
13645 			if (doing_tlp)
13646 				log.u_bbr.flex8 = 2;
13647 			else
13648 				log.u_bbr.flex8 = 1;
13649 		} else {
13650 			log.u_bbr.flex8 = 0;
13651 		}
13652 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13653 		    len, &log, false, NULL, NULL, 0, tv);
13654 	} else {
13655 		lgb = NULL;
13656 	}
13657 	/*
13658 	 * Fill in IP length and desired time to live and send to IP level.
13659 	 * There should be a better way to handle ttl and tos; we could keep
13660 	 * them in the template, but need a way to checksum without them.
13661 	 */
13662 	/*
13663 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13664 	 * because in6_cksum() need it.
13665 	 */
13666 #ifdef INET6
13667 	if (isipv6) {
13668 		/*
13669 		 * we separately set hoplimit for every segment, since the
13670 		 * user might want to change the value via setsockopt. Also,
13671 		 * desired default hop limit might be changed via Neighbor
13672 		 * Discovery.
13673 		 */
13674 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13675 
13676 		/*
13677 		 * Set the packet size here for the benefit of DTrace
13678 		 * probes. ip6_output() will set it properly; it's supposed
13679 		 * to include the option header lengths as well.
13680 		 */
13681 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13682 
13683 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13684 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13685 		else
13686 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13687 
13688 		if (tp->t_state == TCPS_SYN_SENT)
13689 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13690 
13691 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13692 		/* TODO: IPv6 IP6TOS_ECT bit on */
13693 		error = ip6_output(m, inp->in6p_outputopts,
13694 		    &inp->inp_route6,
13695 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13696 		    NULL, NULL, inp);
13697 
13698 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13699 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13700 	}
13701 #endif				/* INET6 */
13702 #if defined(INET) && defined(INET6)
13703 	else
13704 #endif
13705 #ifdef INET
13706 	{
13707 		ip->ip_len = htons(m->m_pkthdr.len);
13708 #ifdef INET6
13709 		if (isipv6)
13710 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13711 #endif				/* INET6 */
13712 		/*
13713 		 * If we do path MTU discovery, then we set DF on every
13714 		 * packet. This might not be the best thing to do according
13715 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13716 		 * the problem so it affects only the first tcp connection
13717 		 * with a host.
13718 		 *
13719 		 * NB: Don't set DF on small MTU/MSS to have a safe
13720 		 * fallback.
13721 		 */
13722 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13723 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13724 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13725 				ip->ip_off |= htons(IP_DF);
13726 			}
13727 		} else {
13728 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13729 		}
13730 
13731 		if (tp->t_state == TCPS_SYN_SENT)
13732 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13733 
13734 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13735 
13736 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13737 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13738 		    inp);
13739 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13740 			mtu = inp->inp_route.ro_nh->nh_mtu;
13741 	}
13742 #endif				/* INET */
13743 out:
13744 
13745 	if (lgb) {
13746 		lgb->tlb_errno = error;
13747 		lgb = NULL;
13748 	}
13749 	/*
13750 	 * In transmit state, time the transmission and arrange for the
13751 	 * retransmit.  In persist state, just set snd_max.
13752 	 */
13753 	if (error == 0) {
13754 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13755 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13756 		    (tp->t_flags & TF_SACK_PERMIT) &&
13757 		    tp->rcv_numsacks > 0)
13758 			tcp_clean_dsack_blocks(tp);
13759 		/* We sent an ack clear the bbr_segs_rcvd count */
13760 		bbr->output_error_seen = 0;
13761 		bbr->oerror_cnt = 0;
13762 		bbr->bbr_segs_rcvd = 0;
13763 		if (len == 0)
13764 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13765 		/* Do accounting for new sends */
13766 		if ((len > 0) && (rsm == NULL)) {
13767 			int idx;
13768 			if (tp->snd_una == tp->snd_max) {
13769 				/*
13770 				 * Special case to match google, when
13771 				 * nothing is in flight the delivered
13772 				 * time does get updated to the current
13773 				 * time (see tcp_rate_bsd.c).
13774 				 */
13775 				bbr->r_ctl.rc_del_time = cts;
13776 			}
13777 			if (len >= maxseg) {
13778 				idx = (len / maxseg) + 3;
13779 				if (idx >= TCP_MSS_ACCT_ATIMER)
13780 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13781 				else
13782 					counter_u64_add(bbr_out_size[idx], 1);
13783 			} else {
13784 				/* smaller than a MSS */
13785 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13786 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13787 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13788 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13789 			}
13790 		}
13791 	}
13792 	abandon = 0;
13793 	/*
13794 	 * We must do the send accounting before we log the output,
13795 	 * otherwise the state of the rsm could change and we account to the
13796 	 * wrong bucket.
13797 	 */
13798 	if (len > 0) {
13799 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13800 		if (error == 0) {
13801 			if (tp->snd_una == tp->snd_max)
13802 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13803 		}
13804 	}
13805 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13806 	    cts, mb, &abandon, rsm, 0, sb);
13807 	if (abandon) {
13808 		/*
13809 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13810 		 * sent we should hit this condition.
13811 		 */
13812 		return (0);
13813 	}
13814 	if (bbr->rc_in_persist == 0) {
13815 		/*
13816 		 * Advance snd_nxt over sequence space of this segment.
13817 		 */
13818 		if (error)
13819 			/* We don't log or do anything with errors */
13820 			goto skip_upd;
13821 
13822 		if (tp->snd_una == tp->snd_max &&
13823 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13824 			/*
13825 			 * Update the time we just added data since none was
13826 			 * outstanding.
13827 			 */
13828 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13829 			bbr->rc_tp->t_acktime  = ticks;
13830 		}
13831 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13832 			if (flags & TH_SYN) {
13833 				/*
13834 				 * Smack the snd_max to iss + 1
13835 				 * if its a FO we will add len below.
13836 				 */
13837 				tp->snd_max = tp->iss + 1;
13838 			}
13839 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13840 				tp->snd_max++;
13841 				tp->t_flags |= TF_SENTFIN;
13842 			}
13843 		}
13844 		if (sack_rxmit == 0)
13845 			tp->snd_max += len;
13846 skip_upd:
13847 		if ((error == 0) && len)
13848 			tot_len += len;
13849 	} else {
13850 		/* Persists case */
13851 		int32_t xlen = len;
13852 
13853 		if (error)
13854 			goto nomore;
13855 
13856 		if (flags & TH_SYN)
13857 			++xlen;
13858 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13859 			++xlen;
13860 			tp->t_flags |= TF_SENTFIN;
13861 		}
13862 		if (xlen && (tp->snd_una == tp->snd_max)) {
13863 			/*
13864 			 * Update the time we just added data since none was
13865 			 * outstanding.
13866 			 */
13867 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13868 			bbr->rc_tp->t_acktime = ticks;
13869 		}
13870 		if (sack_rxmit == 0)
13871 			tp->snd_max += xlen;
13872 		tot_len += (len + optlen + ipoptlen);
13873 	}
13874 nomore:
13875 	if (error) {
13876 		/*
13877 		 * Failures do not advance the seq counter above. For the
13878 		 * case of ENOBUFS we will fall out and become ack-clocked.
13879 		 * capping the cwnd at the current flight.
13880 		 * Everything else will just have to retransmit with the timer
13881 		 * (no pacer).
13882 		 */
13883 		SOCKBUF_UNLOCK_ASSERT(sb);
13884 		BBR_STAT_INC(bbr_saw_oerr);
13885 		/* Clear all delay/early tracks */
13886 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13887 		bbr->r_ctl.rc_agg_early = 0;
13888 		bbr->r_agg_early_set = 0;
13889 		bbr->output_error_seen = 1;
13890 		if (bbr->oerror_cnt < 0xf)
13891 			bbr->oerror_cnt++;
13892 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13893 			/* drop the session */
13894 			tcp_set_inp_to_drop(inp, ENETDOWN);
13895 		}
13896 		switch (error) {
13897 		case ENOBUFS:
13898 			/*
13899 			 * Make this guy have to get ack's to send
13900 			 * more but lets make sure we don't
13901 			 * slam him below a T-O (1MSS).
13902 			 */
13903 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13904 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13905 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13906 				if (tp->snd_cwnd < maxseg)
13907 					tp->snd_cwnd = maxseg;
13908 			}
13909 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13910 			BBR_STAT_INC(bbr_saw_enobuf);
13911 			if (bbr->bbr_hdrw_pacing)
13912 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13913 			else
13914 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13915 			/*
13916 			 * Here even in the enobuf's case we want to do our
13917 			 * state update. The reason being we may have been
13918 			 * called by the input function. If so we have had
13919 			 * things change.
13920 			 */
13921 			error = 0;
13922 			goto enobufs;
13923 		case EMSGSIZE:
13924 			/*
13925 			 * For some reason the interface we used initially
13926 			 * to send segments changed to another or lowered
13927 			 * its MTU. If TSO was active we either got an
13928 			 * interface without TSO capabilits or TSO was
13929 			 * turned off. If we obtained mtu from ip_output()
13930 			 * then update it and try again.
13931 			 */
13932 			/* Turn on tracing (or try to) */
13933 			{
13934 				int old_maxseg;
13935 
13936 				old_maxseg = tp->t_maxseg;
13937 				BBR_STAT_INC(bbr_saw_emsgsiz);
13938 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13939 				if (mtu != 0)
13940 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13941 				if (old_maxseg <= tp->t_maxseg) {
13942 					/* Huh it did not shrink? */
13943 					tp->t_maxseg = old_maxseg - 40;
13944 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13945 				}
13946 				/*
13947 				 * Nuke all other things that can interfere
13948 				 * with slot
13949 				 */
13950 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13951 					slot = bbr_get_pacing_delay(bbr,
13952 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13953 					    (tot_len + len), cts, 0);
13954 					if (slot < bbr_error_base_paceout)
13955 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13956 				} else
13957 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13958 				bbr->rc_output_starts_timer = 1;
13959 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13960 				    tot_len);
13961 				return (error);
13962 			}
13963 		case EPERM:
13964 			tp->t_softerror = error;
13965 			/* Fall through */
13966 		case EHOSTDOWN:
13967 		case EHOSTUNREACH:
13968 		case ENETDOWN:
13969 		case ENETUNREACH:
13970 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13971 				tp->t_softerror = error;
13972 			}
13973 			/* FALLTHROUGH */
13974 		default:
13975 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13976 			bbr->rc_output_starts_timer = 1;
13977 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13978 			return (error);
13979 		}
13980 #ifdef STATS
13981 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13982 		    len &&
13983 		    (rsm == NULL) &&
13984 	    (bbr->rc_in_persist == 0)) {
13985 		tp->gput_seq = bbr_seq;
13986 		tp->gput_ack = bbr_seq +
13987 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13988 		tp->gput_ts = cts;
13989 		tp->t_flags |= TF_GPUTINPROG;
13990 #endif
13991 	}
13992 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13993 	if ((bbr->bbr_hdw_pace_ena) &&
13994 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13995 	    (bbr->rc_past_init_win) &&
13996 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13997 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13998 	    (inp->inp_route.ro_nh &&
13999 	     inp->inp_route.ro_nh->nh_ifp)) {
14000 		/*
14001 		 * We are past the initial window and
14002 		 * have at least one measurement so we
14003 		 * could use hardware pacing if its available.
14004 		 * We have an interface and we have not attempted
14005 		 * to setup hardware pacing, lets try to now.
14006 		 */
14007 		uint64_t rate_wanted;
14008 		int err = 0;
14009 
14010 		rate_wanted = bbr_get_hardware_rate(bbr);
14011 		bbr->bbr_attempt_hdwr_pace = 1;
14012 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
14013 						      inp->inp_route.ro_nh->nh_ifp,
14014 						      rate_wanted,
14015 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
14016 						      &err, NULL);
14017 		if (bbr->r_ctl.crte) {
14018 			bbr_type_log_hdwr_pacing(bbr,
14019 						 bbr->r_ctl.crte->ptbl->rs_ifp,
14020 						 rate_wanted,
14021 						 bbr->r_ctl.crte->rate,
14022 						 __LINE__, cts, err);
14023 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
14024 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
14025 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
14026 			bbr->bbr_hdrw_pacing = 1;
14027 			/* Now what is our gain status? */
14028 			if (bbr->r_ctl.crte->rate < rate_wanted) {
14029 				/* We have a problem */
14030 				bbr_setup_less_of_rate(bbr, cts,
14031 						       bbr->r_ctl.crte->rate, rate_wanted);
14032 			} else {
14033 				/* We are good */
14034 				bbr->gain_is_limited = 0;
14035 				bbr->skip_gain = 0;
14036 			}
14037 			tcp_bbr_tso_size_check(bbr, cts);
14038 		} else {
14039 			bbr_type_log_hdwr_pacing(bbr,
14040 						 inp->inp_route.ro_nh->nh_ifp,
14041 						 rate_wanted,
14042 						 0,
14043 						 __LINE__, cts, err);
14044 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
14045 		}
14046 	}
14047 	if (bbr->bbr_hdrw_pacing) {
14048 		/*
14049 		 * Worry about cases where the route
14050 		 * changes or something happened that we
14051 		 * lost our hardware pacing possibly during
14052 		 * the last ip_output call.
14053 		 */
14054 		if (inp->inp_snd_tag == NULL) {
14055 			/* A change during ip output disabled hw pacing? */
14056 			bbr->bbr_hdrw_pacing = 0;
14057 		} else if ((inp->inp_route.ro_nh == NULL) ||
14058 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
14059 			/*
14060 			 * We had an interface or route change,
14061 			 * detach from the current hdwr pacing
14062 			 * and setup to re-attempt next go
14063 			 * round.
14064 			 */
14065 			bbr->bbr_hdrw_pacing = 0;
14066 			bbr->bbr_attempt_hdwr_pace = 0;
14067 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
14068 			tcp_bbr_tso_size_check(bbr, cts);
14069 		}
14070 	}
14071 	/*
14072 	 * Data sent (as far as we can tell). If this advertises a larger
14073 	 * window than any other segment, then remember the size of the
14074 	 * advertised window. Any pending ACK has now been sent.
14075 	 */
14076 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
14077 		tp->rcv_adv = tp->rcv_nxt + recwin;
14078 
14079 	tp->last_ack_sent = tp->rcv_nxt;
14080 	if ((error == 0) &&
14081 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
14082 	    (doing_tlp == 0) &&
14083 	    (tso == 0) &&
14084 	    (len > 0) &&
14085 	    ((flags & TH_RST) == 0) &&
14086 	    ((flags & TH_SYN) == 0) &&
14087 	    (IN_RECOVERY(tp->t_flags) == 0) &&
14088 	    (bbr->rc_in_persist == 0) &&
14089 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
14090 		/*
14091 		 * For non-tso we need to goto again until we have sent out
14092 		 * enough data to match what we are hptsi out every hptsi
14093 		 * interval.
14094 		 */
14095 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14096 			/* Make sure snd_nxt is drug up */
14097 			tp->snd_nxt = tp->snd_max;
14098 		}
14099 		if (rsm != NULL) {
14100 			rsm = NULL;
14101 			goto skip_again;
14102 		}
14103 		rsm = NULL;
14104 		sack_rxmit = 0;
14105 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14106 		goto again;
14107 	}
14108 skip_again:
14109 	if ((error == 0) && (flags & TH_FIN))
14110 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
14111 	if ((error == 0) && (flags & TH_RST))
14112 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
14113 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14114 		/*
14115 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
14116 		 * what we have sent so far
14117 		 */
14118 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14119 		if (bbr->rc_no_pacing)
14120 			slot = 0;
14121 	}
14122 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14123 enobufs:
14124 	if (bbr->rc_use_google == 0)
14125 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14126 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14127 							bbr->r_ctl.rc_lost_bytes)));
14128 	bbr->rc_output_starts_timer = 1;
14129 	if (bbr->bbr_use_rack_cheat &&
14130 	    (more_to_rxt ||
14131 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14132 		/* Rack cheats and shotguns out all rxt's 1ms apart */
14133 		if (slot > 1000)
14134 			slot = 1000;
14135 	}
14136 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14137 		/*
14138 		 * We don't change the tso size until some number of sends
14139 		 * to give the hardware commands time to get down
14140 		 * to the interface.
14141 		 */
14142 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14143 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14144 			bbr->hw_pacing_set = 1;
14145 			tcp_bbr_tso_size_check(bbr, cts);
14146 		}
14147 	}
14148 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14149 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14150 		/* Make sure snd_nxt is drug up */
14151 		tp->snd_nxt = tp->snd_max;
14152 	}
14153 	return (error);
14154 
14155 }
14156 
14157 /*
14158  * See bbr_output_wtime() for return values.
14159  */
14160 static int
14161 bbr_output(struct tcpcb *tp)
14162 {
14163 	int32_t ret;
14164 	struct timeval tv;
14165 	struct tcp_bbr *bbr;
14166 
14167 	NET_EPOCH_ASSERT();
14168 
14169 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14170 	INP_WLOCK_ASSERT(tp->t_inpcb);
14171 	(void)tcp_get_usecs(&tv);
14172 	ret = bbr_output_wtime(tp, &tv);
14173 	return (ret);
14174 }
14175 
14176 static void
14177 bbr_mtu_chg(struct tcpcb *tp)
14178 {
14179 	struct tcp_bbr *bbr;
14180 	struct bbr_sendmap *rsm, *frsm = NULL;
14181 	uint32_t maxseg;
14182 
14183 	/*
14184 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14185 	 * over the current size as SACK_PASS so a retransmit will occur.
14186 	 */
14187 
14188 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14189 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14190 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14191 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14192 		/* Don't mess with ones acked (by sack?) */
14193 		if (rsm->r_flags & BBR_ACKED)
14194 			continue;
14195 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14196 			/*
14197 			 * We mark sack-passed on all the previous large
14198 			 * sends we did. This will force them to retransmit.
14199 			 */
14200 			rsm->r_flags |= BBR_SACK_PASSED;
14201 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14202 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14203 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14204 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14205 				rsm->r_flags |= BBR_MARKED_LOST;
14206 			}
14207 			if (frsm == NULL)
14208 				frsm = rsm;
14209 		}
14210 	}
14211 	if (frsm) {
14212 		bbr->r_ctl.rc_resend = frsm;
14213 	}
14214 }
14215 
14216 static int
14217 bbr_pru_options(struct tcpcb *tp, int flags)
14218 {
14219 	if (flags & PRUS_OOB)
14220 		return (EOPNOTSUPP);
14221 	return (0);
14222 }
14223 
14224 struct tcp_function_block __tcp_bbr = {
14225 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14226 	.tfb_tcp_output = bbr_output,
14227 	.tfb_do_queued_segments = ctf_do_queued_segments,
14228 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14229 	.tfb_tcp_do_segment = bbr_do_segment,
14230 	.tfb_tcp_ctloutput = bbr_ctloutput,
14231 	.tfb_tcp_fb_init = bbr_init,
14232 	.tfb_tcp_fb_fini = bbr_fini,
14233 	.tfb_tcp_timer_stop_all = bbr_stopall,
14234 	.tfb_tcp_timer_activate = bbr_timer_activate,
14235 	.tfb_tcp_timer_active = bbr_timer_active,
14236 	.tfb_tcp_timer_stop = bbr_timer_stop,
14237 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14238 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14239 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14240 	.tfb_pru_options = bbr_pru_options,
14241 };
14242 
14243 /*
14244  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14245  * socket option arguments.  When it re-acquires the lock after the copy, it
14246  * has to revalidate that the connection is still valid for the socket
14247  * option.
14248  */
14249 static int
14250 bbr_set_sockopt(struct socket *so, struct sockopt *sopt,
14251 		struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14252 {
14253 	struct epoch_tracker et;
14254 	int32_t error = 0, optval;
14255 
14256 	switch (sopt->sopt_level) {
14257 	case IPPROTO_IPV6:
14258 	case IPPROTO_IP:
14259 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14260 	}
14261 
14262 	switch (sopt->sopt_name) {
14263 	case TCP_RACK_PACE_MAX_SEG:
14264 	case TCP_RACK_MIN_TO:
14265 	case TCP_RACK_REORD_THRESH:
14266 	case TCP_RACK_REORD_FADE:
14267 	case TCP_RACK_TLP_THRESH:
14268 	case TCP_RACK_PKT_DELAY:
14269 	case TCP_BBR_ALGORITHM:
14270 	case TCP_BBR_TSLIMITS:
14271 	case TCP_BBR_IWINTSO:
14272 	case TCP_BBR_RECFORCE:
14273 	case TCP_BBR_STARTUP_PG:
14274 	case TCP_BBR_DRAIN_PG:
14275 	case TCP_BBR_RWND_IS_APP:
14276 	case TCP_BBR_PROBE_RTT_INT:
14277 	case TCP_BBR_PROBE_RTT_GAIN:
14278 	case TCP_BBR_PROBE_RTT_LEN:
14279 	case TCP_BBR_STARTUP_LOSS_EXIT:
14280 	case TCP_BBR_USEDEL_RATE:
14281 	case TCP_BBR_MIN_RTO:
14282 	case TCP_BBR_MAX_RTO:
14283 	case TCP_BBR_PACE_PER_SEC:
14284 	case TCP_DELACK:
14285 	case TCP_BBR_PACE_DEL_TAR:
14286 	case TCP_BBR_SEND_IWND_IN_TSO:
14287 	case TCP_BBR_EXTRA_STATE:
14288 	case TCP_BBR_UTTER_MAX_TSO:
14289 	case TCP_BBR_MIN_TOPACEOUT:
14290 	case TCP_BBR_FLOOR_MIN_TSO:
14291 	case TCP_BBR_TSTMP_RAISES:
14292 	case TCP_BBR_POLICER_DETECT:
14293 	case TCP_BBR_USE_RACK_CHEAT:
14294 	case TCP_DATA_AFTER_CLOSE:
14295 	case TCP_BBR_HDWR_PACE:
14296 	case TCP_BBR_PACE_SEG_MAX:
14297 	case TCP_BBR_PACE_SEG_MIN:
14298 	case TCP_BBR_PACE_CROSS:
14299 	case TCP_BBR_PACE_OH:
14300 #ifdef NETFLIX_PEAKRATE
14301 	case TCP_MAXPEAKRATE:
14302 #endif
14303 	case TCP_BBR_TMR_PACE_OH:
14304 	case TCP_BBR_RACK_RTT_USE:
14305 	case TCP_BBR_RETRAN_WTSO:
14306 		break;
14307 	default:
14308 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14309 		break;
14310 	}
14311 	INP_WUNLOCK(inp);
14312 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14313 	if (error)
14314 		return (error);
14315 	INP_WLOCK(inp);
14316 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
14317 		INP_WUNLOCK(inp);
14318 		return (ECONNRESET);
14319 	}
14320 	tp = intotcpcb(inp);
14321 	if (tp->t_fb != &__tcp_bbr) {
14322 		INP_WUNLOCK(inp);
14323 		return (ENOPROTOOPT);
14324 	}
14325 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14326 	switch (sopt->sopt_name) {
14327 	case TCP_BBR_PACE_PER_SEC:
14328 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14329 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14330 		break;
14331 	case TCP_BBR_PACE_DEL_TAR:
14332 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14333 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14334 		break;
14335 	case TCP_BBR_PACE_SEG_MAX:
14336 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14337 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14338 		break;
14339 	case TCP_BBR_PACE_SEG_MIN:
14340 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14341 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14342 		break;
14343 	case TCP_BBR_PACE_CROSS:
14344 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14345 		bbr->r_ctl.bbr_cross_over = optval;
14346 		break;
14347 	case TCP_BBR_ALGORITHM:
14348 		BBR_OPTS_INC(tcp_bbr_algorithm);
14349 		if (optval && (bbr->rc_use_google == 0)) {
14350 			/* Turn on the google mode */
14351 			bbr_google_mode_on(bbr);
14352 			if ((optval > 3) && (optval < 500)) {
14353 				/*
14354 				 * Must be at least greater than .3%
14355 				 * and must be less than 50.0%.
14356 				 */
14357 				bbr->r_ctl.bbr_google_discount = optval;
14358 			}
14359 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14360 			/* Turn off the google mode */
14361 			bbr_google_mode_off(bbr);
14362 		}
14363 		break;
14364 	case TCP_BBR_TSLIMITS:
14365 		BBR_OPTS_INC(tcp_bbr_tslimits);
14366 		if (optval == 1)
14367 			bbr->rc_use_ts_limit = 1;
14368 		else if (optval == 0)
14369 			bbr->rc_use_ts_limit = 0;
14370 		else
14371 			error = EINVAL;
14372 		break;
14373 
14374 	case TCP_BBR_IWINTSO:
14375 		BBR_OPTS_INC(tcp_bbr_iwintso);
14376 		if ((optval >= 0) && (optval < 128)) {
14377 			uint32_t twin;
14378 
14379 			bbr->rc_init_win = optval;
14380 			twin = bbr_initial_cwnd(bbr, tp);
14381 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14382 				tp->snd_cwnd = twin;
14383 			else
14384 				error = EBUSY;
14385 		} else
14386 			error = EINVAL;
14387 		break;
14388 	case TCP_BBR_STARTUP_PG:
14389 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14390 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14391 			bbr->r_ctl.rc_startup_pg = optval;
14392 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14393 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14394 			}
14395 		} else
14396 			error = EINVAL;
14397 		break;
14398 	case TCP_BBR_DRAIN_PG:
14399 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14400 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14401 			bbr->r_ctl.rc_drain_pg = optval;
14402 		else
14403 			error = EINVAL;
14404 		break;
14405 	case TCP_BBR_PROBE_RTT_LEN:
14406 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14407 		if (optval <= 1)
14408 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14409 		else
14410 			error = EINVAL;
14411 		break;
14412 	case TCP_BBR_PROBE_RTT_GAIN:
14413 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14414 		if (optval <= BBR_UNIT)
14415 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14416 		else
14417 			error = EINVAL;
14418 		break;
14419 	case TCP_BBR_PROBE_RTT_INT:
14420 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14421 		if (optval > 1000)
14422 			bbr->r_ctl.rc_probertt_int = optval;
14423 		else
14424 			error = EINVAL;
14425 		break;
14426 	case TCP_BBR_MIN_TOPACEOUT:
14427 		BBR_OPTS_INC(tcp_bbr_topaceout);
14428 		if (optval == 0) {
14429 			bbr->no_pacing_until = 0;
14430 			bbr->rc_no_pacing = 0;
14431 		} else if (optval <= 0x00ff) {
14432 			bbr->no_pacing_until = optval;
14433 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14434 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14435 				/* Turn on no pacing */
14436 				bbr->rc_no_pacing = 1;
14437 			}
14438 		} else
14439 			error = EINVAL;
14440 		break;
14441 	case TCP_BBR_STARTUP_LOSS_EXIT:
14442 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14443 		bbr->rc_loss_exit = optval;
14444 		break;
14445 	case TCP_BBR_USEDEL_RATE:
14446 		error = EINVAL;
14447 		break;
14448 	case TCP_BBR_MIN_RTO:
14449 		BBR_OPTS_INC(tcp_bbr_min_rto);
14450 		bbr->r_ctl.rc_min_rto_ms = optval;
14451 		break;
14452 	case TCP_BBR_MAX_RTO:
14453 		BBR_OPTS_INC(tcp_bbr_max_rto);
14454 		bbr->rc_max_rto_sec = optval;
14455 		break;
14456 	case TCP_RACK_MIN_TO:
14457 		/* Minimum time between rack t-o's in ms */
14458 		BBR_OPTS_INC(tcp_rack_min_to);
14459 		bbr->r_ctl.rc_min_to = optval;
14460 		break;
14461 	case TCP_RACK_REORD_THRESH:
14462 		/* RACK reorder threshold (shift amount) */
14463 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14464 		if ((optval > 0) && (optval < 31))
14465 			bbr->r_ctl.rc_reorder_shift = optval;
14466 		else
14467 			error = EINVAL;
14468 		break;
14469 	case TCP_RACK_REORD_FADE:
14470 		/* Does reordering fade after ms time */
14471 		BBR_OPTS_INC(tcp_rack_reord_fade);
14472 		bbr->r_ctl.rc_reorder_fade = optval;
14473 		break;
14474 	case TCP_RACK_TLP_THRESH:
14475 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14476 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14477 		if (optval)
14478 			bbr->rc_tlp_threshold = optval;
14479 		else
14480 			error = EINVAL;
14481 		break;
14482 	case TCP_BBR_USE_RACK_CHEAT:
14483 		BBR_OPTS_INC(tcp_use_rackcheat);
14484 		if (bbr->rc_use_google) {
14485 			error = EINVAL;
14486 			break;
14487 		}
14488 		BBR_OPTS_INC(tcp_rack_cheat);
14489 		if (optval)
14490 			bbr->bbr_use_rack_cheat = 1;
14491 		else
14492 			bbr->bbr_use_rack_cheat = 0;
14493 		break;
14494 	case TCP_BBR_FLOOR_MIN_TSO:
14495 		BBR_OPTS_INC(tcp_utter_max_tso);
14496 		if ((optval >= 0) && (optval < 40))
14497 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14498 		else
14499 			error = EINVAL;
14500 		break;
14501 	case TCP_BBR_UTTER_MAX_TSO:
14502 		BBR_OPTS_INC(tcp_utter_max_tso);
14503 		if ((optval >= 0) && (optval < 0xffff))
14504 			bbr->r_ctl.bbr_utter_max = optval;
14505 		else
14506 			error = EINVAL;
14507 		break;
14508 
14509 	case TCP_BBR_EXTRA_STATE:
14510 		BBR_OPTS_INC(tcp_extra_state);
14511 		if (optval)
14512 			bbr->rc_use_idle_restart = 1;
14513 		else
14514 			bbr->rc_use_idle_restart = 0;
14515 		break;
14516 	case TCP_BBR_SEND_IWND_IN_TSO:
14517 		BBR_OPTS_INC(tcp_iwnd_tso);
14518 		if (optval) {
14519 			bbr->bbr_init_win_cheat = 1;
14520 			if (bbr->rc_past_init_win == 0) {
14521 				uint32_t cts;
14522 				cts = tcp_get_usecs(&bbr->rc_tv);
14523 				tcp_bbr_tso_size_check(bbr, cts);
14524 			}
14525 		} else
14526 			bbr->bbr_init_win_cheat = 0;
14527 		break;
14528 	case TCP_BBR_HDWR_PACE:
14529 		BBR_OPTS_INC(tcp_hdwr_pacing);
14530 		if (optval){
14531 			bbr->bbr_hdw_pace_ena = 1;
14532 			bbr->bbr_attempt_hdwr_pace = 0;
14533 		} else {
14534 			bbr->bbr_hdw_pace_ena = 0;
14535 #ifdef RATELIMIT
14536 			if (bbr->r_ctl.crte != NULL) {
14537 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14538 				bbr->r_ctl.crte = NULL;
14539 			}
14540 #endif
14541 		}
14542 		break;
14543 
14544 	case TCP_DELACK:
14545 		BBR_OPTS_INC(tcp_delack);
14546 		if (optval < 100) {
14547 			if (optval == 0) /* off */
14548 				tp->t_delayed_ack = 0;
14549 			else if (optval == 1) /* on which is 2 */
14550 				tp->t_delayed_ack = 2;
14551 			else /* higher than 2 and less than 100 */
14552 				tp->t_delayed_ack = optval;
14553 			if (tp->t_flags & TF_DELACK) {
14554 				tp->t_flags &= ~TF_DELACK;
14555 				tp->t_flags |= TF_ACKNOW;
14556 				NET_EPOCH_ENTER(et);
14557 				bbr_output(tp);
14558 				NET_EPOCH_EXIT(et);
14559 			}
14560 		} else
14561 			error = EINVAL;
14562 		break;
14563 	case TCP_RACK_PKT_DELAY:
14564 		/* RACK added ms i.e. rack-rtt + reord + N */
14565 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14566 		bbr->r_ctl.rc_pkt_delay = optval;
14567 		break;
14568 #ifdef NETFLIX_PEAKRATE
14569 	case TCP_MAXPEAKRATE:
14570 		BBR_OPTS_INC(tcp_maxpeak);
14571 		error = tcp_set_maxpeakrate(tp, optval);
14572 		if (!error)
14573 			tp->t_peakrate_thr = tp->t_maxpeakrate;
14574 		break;
14575 #endif
14576 	case TCP_BBR_RETRAN_WTSO:
14577 		BBR_OPTS_INC(tcp_retran_wtso);
14578 		if (optval)
14579 			bbr->rc_resends_use_tso = 1;
14580 		else
14581 			bbr->rc_resends_use_tso = 0;
14582 		break;
14583 	case TCP_DATA_AFTER_CLOSE:
14584 		BBR_OPTS_INC(tcp_data_ac);
14585 		if (optval)
14586 			bbr->rc_allow_data_af_clo = 1;
14587 		else
14588 			bbr->rc_allow_data_af_clo = 0;
14589 		break;
14590 	case TCP_BBR_POLICER_DETECT:
14591 		BBR_OPTS_INC(tcp_policer_det);
14592 		if (bbr->rc_use_google == 0)
14593 			error = EINVAL;
14594 		else if (optval)
14595 			bbr->r_use_policer = 1;
14596 		else
14597 			bbr->r_use_policer = 0;
14598 		break;
14599 
14600 	case TCP_BBR_TSTMP_RAISES:
14601 		BBR_OPTS_INC(tcp_ts_raises);
14602 		if (optval)
14603 			bbr->ts_can_raise = 1;
14604 		else
14605 			bbr->ts_can_raise = 0;
14606 		break;
14607 	case TCP_BBR_TMR_PACE_OH:
14608 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14609 		if (bbr->rc_use_google) {
14610 			error = EINVAL;
14611 		} else {
14612 			if (optval)
14613 				bbr->r_ctl.rc_incr_tmrs = 1;
14614 			else
14615 				bbr->r_ctl.rc_incr_tmrs = 0;
14616 		}
14617 		break;
14618 	case TCP_BBR_PACE_OH:
14619 		BBR_OPTS_INC(tcp_pacing_oh);
14620 		if (bbr->rc_use_google) {
14621 			error = EINVAL;
14622 		} else {
14623 			if (optval > (BBR_INCL_TCP_OH|
14624 				      BBR_INCL_IP_OH|
14625 				      BBR_INCL_ENET_OH)) {
14626 				error = EINVAL;
14627 				break;
14628 			}
14629 			if (optval & BBR_INCL_TCP_OH)
14630 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14631 			else
14632 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14633 			if (optval & BBR_INCL_IP_OH)
14634 				bbr->r_ctl.rc_inc_ip_oh = 1;
14635 			else
14636 				bbr->r_ctl.rc_inc_ip_oh = 0;
14637 			if (optval & BBR_INCL_ENET_OH)
14638 				bbr->r_ctl.rc_inc_enet_oh = 1;
14639 			else
14640 				bbr->r_ctl.rc_inc_enet_oh = 0;
14641 		}
14642 		break;
14643 	default:
14644 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14645 		break;
14646 	}
14647 #ifdef NETFLIX_STATS
14648 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14649 #endif
14650 	INP_WUNLOCK(inp);
14651 	return (error);
14652 }
14653 
14654 /*
14655  * return 0 on success, error-num on failure
14656  */
14657 static int
14658 bbr_get_sockopt(struct socket *so, struct sockopt *sopt,
14659     struct inpcb *inp, struct tcpcb *tp, struct tcp_bbr *bbr)
14660 {
14661 	int32_t error, optval;
14662 
14663 	/*
14664 	 * Because all our options are either boolean or an int, we can just
14665 	 * pull everything into optval and then unlock and copy. If we ever
14666 	 * add a option that is not a int, then this will have quite an
14667 	 * impact to this routine.
14668 	 */
14669 	switch (sopt->sopt_name) {
14670 	case TCP_BBR_PACE_PER_SEC:
14671 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14672 		break;
14673 	case TCP_BBR_PACE_DEL_TAR:
14674 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14675 		break;
14676 	case TCP_BBR_PACE_SEG_MAX:
14677 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14678 		break;
14679 	case TCP_BBR_MIN_TOPACEOUT:
14680 		optval = bbr->no_pacing_until;
14681 		break;
14682 	case TCP_BBR_PACE_SEG_MIN:
14683 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14684 		break;
14685 	case TCP_BBR_PACE_CROSS:
14686 		optval = bbr->r_ctl.bbr_cross_over;
14687 		break;
14688 	case TCP_BBR_ALGORITHM:
14689 		optval = bbr->rc_use_google;
14690 		break;
14691 	case TCP_BBR_TSLIMITS:
14692 		optval = bbr->rc_use_ts_limit;
14693 		break;
14694 	case TCP_BBR_IWINTSO:
14695 		optval = bbr->rc_init_win;
14696 		break;
14697 	case TCP_BBR_STARTUP_PG:
14698 		optval = bbr->r_ctl.rc_startup_pg;
14699 		break;
14700 	case TCP_BBR_DRAIN_PG:
14701 		optval = bbr->r_ctl.rc_drain_pg;
14702 		break;
14703 	case TCP_BBR_PROBE_RTT_INT:
14704 		optval = bbr->r_ctl.rc_probertt_int;
14705 		break;
14706 	case TCP_BBR_PROBE_RTT_LEN:
14707 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14708 		break;
14709 	case TCP_BBR_PROBE_RTT_GAIN:
14710 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14711 		break;
14712 	case TCP_BBR_STARTUP_LOSS_EXIT:
14713 		optval = bbr->rc_loss_exit;
14714 		break;
14715 	case TCP_BBR_USEDEL_RATE:
14716 		error = EINVAL;
14717 		break;
14718 	case TCP_BBR_MIN_RTO:
14719 		optval = bbr->r_ctl.rc_min_rto_ms;
14720 		break;
14721 	case TCP_BBR_MAX_RTO:
14722 		optval = bbr->rc_max_rto_sec;
14723 		break;
14724 	case TCP_RACK_PACE_MAX_SEG:
14725 		/* Max segments in a pace */
14726 		optval = bbr->r_ctl.rc_pace_max_segs;
14727 		break;
14728 	case TCP_RACK_MIN_TO:
14729 		/* Minimum time between rack t-o's in ms */
14730 		optval = bbr->r_ctl.rc_min_to;
14731 		break;
14732 	case TCP_RACK_REORD_THRESH:
14733 		/* RACK reorder threshold (shift amount) */
14734 		optval = bbr->r_ctl.rc_reorder_shift;
14735 		break;
14736 	case TCP_RACK_REORD_FADE:
14737 		/* Does reordering fade after ms time */
14738 		optval = bbr->r_ctl.rc_reorder_fade;
14739 		break;
14740 	case TCP_BBR_USE_RACK_CHEAT:
14741 		/* Do we use the rack cheat for rxt */
14742 		optval = bbr->bbr_use_rack_cheat;
14743 		break;
14744 	case TCP_BBR_FLOOR_MIN_TSO:
14745 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14746 		break;
14747 	case TCP_BBR_UTTER_MAX_TSO:
14748 		optval = bbr->r_ctl.bbr_utter_max;
14749 		break;
14750 	case TCP_BBR_SEND_IWND_IN_TSO:
14751 		/* Do we send TSO size segments initially */
14752 		optval = bbr->bbr_init_win_cheat;
14753 		break;
14754 	case TCP_BBR_EXTRA_STATE:
14755 		optval = bbr->rc_use_idle_restart;
14756 		break;
14757 	case TCP_RACK_TLP_THRESH:
14758 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14759 		optval = bbr->rc_tlp_threshold;
14760 		break;
14761 	case TCP_RACK_PKT_DELAY:
14762 		/* RACK added ms i.e. rack-rtt + reord + N */
14763 		optval = bbr->r_ctl.rc_pkt_delay;
14764 		break;
14765 	case TCP_BBR_RETRAN_WTSO:
14766 		optval = bbr->rc_resends_use_tso;
14767 		break;
14768 	case TCP_DATA_AFTER_CLOSE:
14769 		optval = bbr->rc_allow_data_af_clo;
14770 		break;
14771 	case TCP_DELACK:
14772 		optval = tp->t_delayed_ack;
14773 		break;
14774 	case TCP_BBR_HDWR_PACE:
14775 		optval = bbr->bbr_hdw_pace_ena;
14776 		break;
14777 	case TCP_BBR_POLICER_DETECT:
14778 		optval = bbr->r_use_policer;
14779 		break;
14780 	case TCP_BBR_TSTMP_RAISES:
14781 		optval = bbr->ts_can_raise;
14782 		break;
14783 	case TCP_BBR_TMR_PACE_OH:
14784 		optval = bbr->r_ctl.rc_incr_tmrs;
14785 		break;
14786 	case TCP_BBR_PACE_OH:
14787 		optval = 0;
14788 		if (bbr->r_ctl.rc_inc_tcp_oh)
14789 			optval |= BBR_INCL_TCP_OH;
14790 		if (bbr->r_ctl.rc_inc_ip_oh)
14791 			optval |= BBR_INCL_IP_OH;
14792 		if (bbr->r_ctl.rc_inc_enet_oh)
14793 			optval |= BBR_INCL_ENET_OH;
14794 		break;
14795 	default:
14796 		return (tcp_default_ctloutput(so, sopt, inp, tp));
14797 		break;
14798 	}
14799 	INP_WUNLOCK(inp);
14800 	error = sooptcopyout(sopt, &optval, sizeof optval);
14801 	return (error);
14802 }
14803 
14804 /*
14805  * return 0 on success, error-num on failure
14806  */
14807 static int
14808 bbr_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
14809 {
14810 	int32_t error = EINVAL;
14811 	struct tcp_bbr *bbr;
14812 
14813 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14814 	if (bbr == NULL) {
14815 		/* Huh? */
14816 		goto out;
14817 	}
14818 	if (sopt->sopt_dir == SOPT_SET) {
14819 		return (bbr_set_sockopt(so, sopt, inp, tp, bbr));
14820 	} else if (sopt->sopt_dir == SOPT_GET) {
14821 		return (bbr_get_sockopt(so, sopt, inp, tp, bbr));
14822 	}
14823 out:
14824 	INP_WUNLOCK(inp);
14825 	return (error);
14826 }
14827 
14828 static const char *bbr_stack_names[] = {
14829 	__XSTRING(STACKNAME),
14830 #ifdef STACKALIAS
14831 	__XSTRING(STACKALIAS),
14832 #endif
14833 };
14834 
14835 static bool bbr_mod_inited = false;
14836 
14837 static int
14838 tcp_addbbr(module_t mod, int32_t type, void *data)
14839 {
14840 	int32_t err = 0;
14841 	int num_stacks;
14842 
14843 	switch (type) {
14844 	case MOD_LOAD:
14845 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14846 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14847 		    sizeof(struct bbr_sendmap),
14848 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14849 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14850 		    sizeof(struct tcp_bbr),
14851 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14852 		sysctl_ctx_init(&bbr_sysctl_ctx);
14853 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14854 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14855 		    OID_AUTO,
14856 #ifdef STACKALIAS
14857 		    __XSTRING(STACKALIAS),
14858 #else
14859 		    __XSTRING(STACKNAME),
14860 #endif
14861 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14862 		    "");
14863 		if (bbr_sysctl_root == NULL) {
14864 			printf("Failed to add sysctl node\n");
14865 			err = EFAULT;
14866 			goto free_uma;
14867 		}
14868 		bbr_init_sysctls();
14869 		num_stacks = nitems(bbr_stack_names);
14870 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14871 		    bbr_stack_names, &num_stacks);
14872 		if (err) {
14873 			printf("Failed to register %s stack name for "
14874 			    "%s module\n", bbr_stack_names[num_stacks],
14875 			    __XSTRING(MODNAME));
14876 			sysctl_ctx_free(&bbr_sysctl_ctx);
14877 	free_uma:
14878 			uma_zdestroy(bbr_zone);
14879 			uma_zdestroy(bbr_pcb_zone);
14880 			bbr_counter_destroy();
14881 			printf("Failed to register " __XSTRING(MODNAME)
14882 			    " module err:%d\n", err);
14883 			return (err);
14884 		}
14885 		tcp_lro_reg_mbufq();
14886 		bbr_mod_inited = true;
14887 		printf(__XSTRING(MODNAME) " is now available\n");
14888 		break;
14889 	case MOD_QUIESCE:
14890 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14891 		break;
14892 	case MOD_UNLOAD:
14893 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14894 		if (err == EBUSY)
14895 			break;
14896 		if (bbr_mod_inited) {
14897 			uma_zdestroy(bbr_zone);
14898 			uma_zdestroy(bbr_pcb_zone);
14899 			sysctl_ctx_free(&bbr_sysctl_ctx);
14900 			bbr_counter_destroy();
14901 			printf(__XSTRING(MODNAME)
14902 			    " is now no longer available\n");
14903 			bbr_mod_inited = false;
14904 		}
14905 		tcp_lro_dereg_mbufq();
14906 		err = 0;
14907 		break;
14908 	default:
14909 		return (EOPNOTSUPP);
14910 	}
14911 	return (err);
14912 }
14913 
14914 static moduledata_t tcp_bbr = {
14915 	.name = __XSTRING(MODNAME),
14916 	    .evhand = tcp_addbbr,
14917 	    .priv = 0
14918 };
14919 
14920 MODULE_VERSION(MODNAME, 1);
14921 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14922 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14923