xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision 4c9a0adad18263ec8725d9bfc5f560c6ad1da8bd)
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 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_ratelimit.h"
38 #include <sys/param.h>
39 #include <sys/arb.h>
40 #include <sys/module.h>
41 #include <sys/kernel.h>
42 #include <sys/libkern.h>
43 #ifdef TCP_HHOOK
44 #include <sys/hhook.h>
45 #endif
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/proc.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #ifdef STATS
54 #include <sys/qmath.h>
55 #include <sys/tree.h>
56 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
57 #endif
58 #include <sys/refcount.h>
59 #include <sys/queue.h>
60 #include <sys/eventhandler.h>
61 #include <sys/smp.h>
62 #include <sys/kthread.h>
63 #include <sys/lock.h>
64 #include <sys/mutex.h>
65 #include <sys/tim_filter.h>
66 #include <sys/time.h>
67 #include <sys/protosw.h>
68 #include <vm/uma.h>
69 #include <sys/kern_prefetch.h>
70 
71 #include <net/route.h>
72 #include <net/route/nhop.h>
73 #include <net/vnet.h>
74 
75 #define TCPSTATES		/* for logging */
76 
77 #include <netinet/in.h>
78 #include <netinet/in_kdtrace.h>
79 #include <netinet/in_pcb.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
82 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
83 #include <netinet/ip_var.h>
84 #include <netinet/ip6.h>
85 #include <netinet6/in6_pcb.h>
86 #include <netinet6/ip6_var.h>
87 #define	TCPOUTFLAGS
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/tcpip.h>
94 #include <netinet/tcp_hpts.h>
95 #include <netinet/cc/cc.h>
96 #include <netinet/tcp_log_buf.h>
97 #include <netinet/tcp_ratelimit.h>
98 #include <netinet/tcp_lro.h>
99 #ifdef TCP_OFFLOAD
100 #include <netinet/tcp_offload.h>
101 #endif
102 #ifdef INET6
103 #include <netinet6/tcp6_var.h>
104 #endif
105 #include <netinet/tcp_fastopen.h>
106 
107 #include <netipsec/ipsec_support.h>
108 #include <net/if.h>
109 #include <net/if_var.h>
110 #include <net/ethernet.h>
111 
112 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
113 #include <netipsec/ipsec.h>
114 #include <netipsec/ipsec6.h>
115 #endif				/* IPSEC */
116 
117 #include <netinet/udp.h>
118 #include <netinet/udp_var.h>
119 #include <machine/in_cksum.h>
120 
121 #ifdef MAC
122 #include <security/mac/mac_framework.h>
123 #endif
124 
125 #include "sack_filter.h"
126 #include "tcp_bbr.h"
127 #include "rack_bbr_common.h"
128 uma_zone_t bbr_zone;
129 uma_zone_t bbr_pcb_zone;
130 
131 struct sysctl_ctx_list bbr_sysctl_ctx;
132 struct sysctl_oid *bbr_sysctl_root;
133 
134 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
135 	(tv) = (value); \
136 	if ((u_long)(tv) < (u_long)(tvmin)) \
137 		(tv) = (tvmin); \
138 	if ((u_long)(tv) > (u_long)(tvmax)) \
139 		(tv) = (tvmax); \
140 } while(0)
141 
142 /*#define BBR_INVARIANT 1*/
143 
144 /*
145  * initial window
146  */
147 static uint32_t bbr_def_init_win = 10;
148 static int32_t bbr_persist_min = 250000;	/* 250ms */
149 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
150 static int32_t bbr_cwnd_may_shrink = 0;
151 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
152 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
153 static int32_t bbr_hardware_pacing_limit = 8000;
154 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
155 static int32_t bbr_no_retran = 0;
156 
157 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
158 static int32_t bbr_max_net_error_cnt = 10;
159 /* Should the following be dynamic too -- loss wise */
160 static int32_t bbr_rtt_gain_thresh = 0;
161 /* Measurement controls */
162 static int32_t bbr_use_google_algo = 1;
163 static int32_t bbr_ts_limiting = 1;
164 static int32_t bbr_ts_can_raise = 0;
165 static int32_t bbr_do_red = 600;
166 static int32_t bbr_red_scale = 20000;
167 static int32_t bbr_red_mul = 1;
168 static int32_t bbr_red_div = 2;
169 static int32_t bbr_red_growth_restrict = 1;
170 static int32_t  bbr_target_is_bbunit = 0;
171 static int32_t bbr_drop_limit = 0;
172 /*
173  * How much gain do we need to see to
174  * stay in startup?
175  */
176 static int32_t bbr_marks_rxt_sack_passed = 0;
177 static int32_t bbr_start_exit = 25;
178 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
179 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
180 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
181 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
182 					 * if we go back ever to where the pacer
183 					 * has priority over timers.
184 					 */
185 static int32_t bbr_policer_call_from_rack_to = 0;
186 static int32_t bbr_policer_detection_enabled = 1;
187 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
188 						 * measurements before we are
189 						 * "good" note that 2 == 1.
190 						 * This is because we use a >
191 						 * comparison. This means if
192 						 * min_measure was 0, it takes
193 						 * num-measures > min(0) and
194 						 * you get 1 measurement and
195 						 * you are good. Set to 1, you
196 						 * have to have two
197 						 * measurements (this is done
198 						 * to prevent it from being ok
199 						 * to have no measurements). */
200 static int32_t bbr_no_pacing_until = 4;
201 
202 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
203 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
204 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
205 
206 static int32_t bbr_target_cwnd_mult_limit = 8;
207 /*
208  * bbr_cwnd_min_val is the number of
209  * segments we hold to in the RTT probe
210  * state typically 4.
211  */
212 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
213 
214 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
215 
216 static int32_t bbr_gain_to_target = 1;
217 static int32_t bbr_gain_gets_extra_too = 1;
218 /*
219  * bbr_high_gain is the 2/ln(2) value we need
220  * to double the sending rate in startup. This
221  * is used for both cwnd and hptsi gain's.
222  */
223 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
224 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
225 static int32_t bbr_use_lower_gain_in_startup = 1;
226 
227 /* thresholds for reduction on drain in sub-states/drain */
228 static int32_t bbr_drain_rtt = BBR_SRTT;
229 static int32_t bbr_drain_floor = 88;
230 static int32_t google_allow_early_out = 1;
231 static int32_t google_consider_lost = 1;
232 static int32_t bbr_drain_drop_mul = 4;
233 static int32_t bbr_drain_drop_div = 5;
234 static int32_t bbr_rand_ot = 50;
235 static int32_t bbr_can_force_probertt = 0;
236 static int32_t bbr_can_adjust_probertt = 1;
237 static int32_t bbr_probertt_sets_rtt = 0;
238 static int32_t bbr_can_use_ts_for_rtt = 1;
239 static int32_t bbr_is_ratio = 0;
240 static int32_t bbr_sub_drain_app_limit = 1;
241 static int32_t bbr_prtt_slam_cwnd = 1;
242 static int32_t bbr_sub_drain_slam_cwnd = 1;
243 static int32_t bbr_slam_cwnd_in_main_drain = 1;
244 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
245 					 * hold */
246 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
247 /*
248  * bbr_drain_gain is the reverse of the high_gain
249  * designed to drain back out the standing queue
250  * that is formed in startup by causing a larger
251  * hptsi gain and thus drainging the packets
252  * in flight.
253  */
254 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
255 static int32_t bbr_rttprobe_gain = 192;
256 
257 /*
258  * The cwnd_gain is the default cwnd gain applied when
259  * calculating a target cwnd. Note that the cwnd is
260  * a secondary factor in the way BBR works (see the
261  * paper and think about it, it will take some time).
262  * Basically the hptsi_gain spreads the packets out
263  * so you never get more than BDP to the peer even
264  * if the cwnd is high. In our implemenation that
265  * means in non-recovery/retransmission scenarios
266  * cwnd will never be reached by the flight-size.
267  */
268 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
269 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
270 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
271 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
272 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
273 static int32_t bbr_ignore_data_after_close = 1;
274 static int16_t bbr_hptsi_gain[] = {
275 	(BBR_UNIT *5 / 4),
276 	(BBR_UNIT * 3 / 4),
277 	BBR_UNIT,
278 	BBR_UNIT,
279 	BBR_UNIT,
280 	BBR_UNIT,
281 	BBR_UNIT,
282 	BBR_UNIT
283 };
284 int32_t bbr_use_rack_resend_cheat = 1;
285 int32_t bbr_sends_full_iwnd = 1;
286 
287 #define BBR_HPTSI_GAIN_MAX 8
288 /*
289  * The BBR module incorporates a number of
290  * TCP ideas that have been put out into the IETF
291  * over the last few years:
292  * - Yuchung Cheng's RACK TCP (for which its named) that
293  *    will stop us using the number of dup acks and instead
294  *    use time as the gage of when we retransmit.
295  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
296  *    of Dukkipati et.al.
297  * - Van Jacobson's et.al BBR.
298  *
299  * RACK depends on SACK, so if an endpoint arrives that
300  * cannot do SACK the state machine below will shuttle the
301  * connection back to using the "default" TCP stack that is
302  * in FreeBSD.
303  *
304  * To implement BBR and RACK the original TCP stack was first decomposed
305  * into a functional state machine with individual states
306  * for each of the possible TCP connection states. The do_segment
307  * functions role in life is to mandate the connection supports SACK
308  * initially and then assure that the RACK state matches the conenction
309  * state before calling the states do_segment function. Data processing
310  * of inbound segments also now happens in the hpts_do_segment in general
311  * with only one exception. This is so we can keep the connection on
312  * a single CPU.
313  *
314  * Each state is simplified due to the fact that the original do_segment
315  * has been decomposed and we *know* what state we are in (no
316  * switches on the state) and all tests for SACK are gone. This
317  * greatly simplifies what each state does.
318  *
319  * TCP output is also over-written with a new version since it
320  * must maintain the new rack scoreboard and has had hptsi
321  * integrated as a requirment. Still todo is to eliminate the
322  * use of the callout_() system and use the hpts for all
323  * timers as well.
324  */
325 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
326 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
327 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
328 						 * free list */
329 static int32_t bbr_tlp_thresh = 1;
330 static int32_t bbr_reorder_thresh = 2;
331 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
332 						 * 60,000,000 - 60 seconds */
333 static int32_t bbr_pkt_delay = 1000;
334 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
335 static int32_t bbr_incr_timers = 1;
336 
337 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
338 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
339 static int32_t bbr_exit_startup_at_loss = 1;
340 
341 /*
342  * bbr_lt_bw_ratio is 1/8th
343  * bbr_lt_bw_diff is  < 4 Kbit/sec
344  */
345 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
346 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
347 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
348 						 * the lt_bw for */
349 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
350 						 * lt_bw */
351 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
352 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
353 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
354 
355 static int32_t bbr_verbose_logging = 0;
356 /*
357  * Currently regular tcp has a rto_min of 30ms
358  * the backoff goes 12 times so that ends up
359  * being a total of 122.850 seconds before a
360  * connection is killed.
361  */
362 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
363 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
364 
365 /****************************************************/
366 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
367 /****************************************************/
368 /* What amount is our formula using to get TSO size */
369 static int32_t bbr_hptsi_per_second = 1000;
370 
371 /*
372  * For hptsi under bbr_cross_over connections what is delay
373  * target 7ms (in usec) combined with a seg_max of 2
374  * gets us close to identical google behavior in
375  * TSO size selection (possibly more 1MSS sends).
376  */
377 static int32_t bbr_hptsi_segments_delay_tar = 7000;
378 
379 /* Does pacing delay include overhead's in its time calculations? */
380 static int32_t bbr_include_enet_oh = 0;
381 static int32_t bbr_include_ip_oh = 1;
382 static int32_t bbr_include_tcp_oh = 1;
383 static int32_t bbr_google_discount = 10;
384 
385 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
386 static int32_t bbr_state_is_pkt_epoch = 0;
387 static int32_t bbr_state_drain_2_tar = 1;
388 /* What is the max the 0 - bbr_cross_over MBPS TSO target
389  * can reach using our delay target. Note that this
390  * value becomes the floor for the cross over
391  * algorithm.
392  */
393 static int32_t bbr_hptsi_segments_max = 2;
394 static int32_t bbr_hptsi_segments_floor = 1;
395 static int32_t bbr_hptsi_utter_max = 0;
396 
397 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
398 static int32_t bbr_hptsi_bytes_min = 1460;
399 static int32_t bbr_all_get_min = 0;
400 
401 /* Cross over point from algo-a to algo-b */
402 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
403 
404 /* Do we deal with our restart state? */
405 static int32_t bbr_uses_idle_restart = 0;
406 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
407 
408 /* Do we allow hardware pacing? */
409 static int32_t bbr_allow_hdwr_pacing = 0;
410 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
411 static int32_t bbr_hdwr_pace_floor = 1;
412 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
413 
414 /****************************************************/
415 static int32_t bbr_resends_use_tso = 0;
416 static int32_t bbr_tlp_max_resend = 2;
417 static int32_t bbr_sack_block_limit = 128;
418 
419 #define  BBR_MAX_STAT 19
420 counter_u64_t bbr_state_time[BBR_MAX_STAT];
421 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
422 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
423 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
424 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
425 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
426 counter_u64_t bbr_flows_whdwr_pacing;
427 counter_u64_t bbr_flows_nohdwr_pacing;
428 
429 counter_u64_t bbr_nohdwr_pacing_enobuf;
430 counter_u64_t bbr_hdwr_pacing_enobuf;
431 
432 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
433 
434 /*
435  * Static defintions we need for forward declarations.
436  */
437 static uint32_t
438 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
439 		      uint32_t useconds_time, uint64_t bw);
440 static uint32_t
441 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
442 static void
443 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
444 static void
445 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
446 static void
447 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
448 		    int dolog);
449 static uint32_t
450 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
451 static void
452 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
453 		 int32_t pkt_epoch, uint32_t losses);
454 static uint32_t
455 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts,
456 		     struct bbr_sendmap *rsm);
457 static uint32_t
458 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
459 static uint32_t
460 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
461 		    struct bbr_sendmap *rsm, uint32_t srtt, uint32_t cts);
462 static void
463 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
464 		 int32_t line);
465 static void
466 bbr_set_state_target(struct tcp_bbr *bbr, int line);
467 static void
468 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
469 static void
470 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick,
471 		       int event, int line);
472 static void
473 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
474 static void
475 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
476 static void
477 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
478 		    uint32_t rtt, uint32_t line, uint8_t is_start,
479 		    uint16_t set);
480 static struct bbr_sendmap *
481 bbr_find_lowest_rsm(struct tcp_bbr *bbr);
482 static __inline uint32_t
483 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
484 static void
485 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot,
486 		 uint8_t which);
487 static void
488 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts,
489 		  uint32_t time_since_sent, uint32_t srtt,
490 		  uint32_t thresh, uint32_t to);
491 static void
492 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
493 static void
494 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
495 		    uint32_t del_by, uint32_t cts, uint32_t sloton,
496 		    uint32_t prev_delay);
497 static void
498 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
499 		  int32_t line);
500 static void
501 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr);
502 static void
503 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
504 static void
505 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
506 static void
507 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
508 static void
509 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
510 			  uint32_t cts, uint32_t usecs, uint64_t bw,
511 			  uint32_t override, int mod);
512 static int bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt);
513 
514 static inline uint8_t
515 bbr_state_val(struct tcp_bbr *bbr)
516 {
517 	return(bbr->rc_bbr_substate);
518 }
519 
520 static inline uint32_t
521 get_min_cwnd(struct tcp_bbr *bbr)
522 {
523 	int mss;
524 
525 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
526 		  bbr->r_ctl.rc_pace_max_segs);
527 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
528 		return (bbr_cwnd_min_val_hs * mss);
529 	else
530 		return (bbr_cwnd_min_val * mss);
531 }
532 
533 static uint32_t
534 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
535 {
536 	uint64_t srtt, var;
537 	uint64_t ret_val;
538 
539 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
540 	if (tp->t_srtt == 0) {
541 		srtt = (uint64_t)BBR_INITIAL_RTO;
542 		var = 0;
543 	} else {
544 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
545 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
546 	}
547 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
548 	    bbr_persist_min, bbr_persist_max);
549 	return ((uint32_t)ret_val);
550 }
551 
552 static uint32_t
553 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
554 {
555 	/*
556 	 * Start the FR timer, we do this based on getting the first one in
557 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
558 	 * events we need to stop the running timer (if its running) before
559 	 * starting the new one.
560 	 */
561 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
562 	int32_t idx;
563 	int32_t is_tlp_timer = 0;
564 	struct bbr_sendmap *rsm;
565 
566 	if (bbr->rc_all_timers_stopped) {
567 		/* All timers have been stopped none are to run */
568 		return (0);
569 	}
570 	if (bbr->rc_in_persist) {
571 		/* We can't start any timer in persists */
572 		return (bbr_get_persists_timer_val(tp, bbr));
573 	}
574 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
575 	if ((rsm == NULL) ||
576 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
577 	    (tp->t_state < TCPS_ESTABLISHED)) {
578 		/* Nothing on the send map */
579 activate_rxt:
580 		if (SEQ_LT(tp->snd_una, tp->snd_max) ||
581 		    sbavail(&tptosocket(tp)->so_snd)) {
582 			uint64_t tov;
583 
584 			time_since_sent = 0;
585 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
586 			if (rsm) {
587 				idx = rsm->r_rtr_cnt - 1;
588 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
589 					tstmp_touse = rsm->r_tim_lastsent[idx];
590 				else
591 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
592 				if (TSTMP_GT(tstmp_touse, cts))
593 				    time_since_sent = cts - tstmp_touse;
594 			}
595 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
596 			if (tp->t_srtt == 0)
597 				tov = BBR_INITIAL_RTO;
598 			else
599 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
600 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
601 			if (tp->t_rxtshift)
602 				tov *= tcp_backoff[tp->t_rxtshift];
603 			if (tov > time_since_sent)
604 				tov -= time_since_sent;
605 			else
606 				tov = bbr->r_ctl.rc_min_to;
607 			TCPT_RANGESET_NOSLOP(to, tov,
608 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
609 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
610 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
611 			return (to);
612 		}
613 		return (0);
614 	}
615 	if (rsm->r_flags & BBR_ACKED) {
616 		rsm = bbr_find_lowest_rsm(bbr);
617 		if (rsm == NULL) {
618 			/* No lowest? */
619 			goto activate_rxt;
620 		}
621 	}
622 	/* Convert from ms to usecs */
623 	if (rsm->r_flags & BBR_SACK_PASSED) {
624 		if ((tp->t_flags & TF_SENTFIN) &&
625 		    ((tp->snd_max - tp->snd_una) == 1) &&
626 		    (rsm->r_flags & BBR_HAS_FIN)) {
627 			/*
628 			 * We don't start a bbr rack timer if all we have is
629 			 * a FIN outstanding.
630 			 */
631 			goto activate_rxt;
632 		}
633 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
634 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
635 		idx = rsm->r_rtr_cnt - 1;
636 		exp = rsm->r_tim_lastsent[idx] + thresh;
637 		if (SEQ_GEQ(exp, cts)) {
638 			to = exp - cts;
639 			if (to < bbr->r_ctl.rc_min_to) {
640 				to = bbr->r_ctl.rc_min_to;
641 			}
642 		} else {
643 			to = bbr->r_ctl.rc_min_to;
644 		}
645 	} else {
646 		/* Ok we need to do a TLP not RACK */
647 		if (bbr->rc_tlp_in_progress != 0) {
648 			/*
649 			 * The previous send was a TLP.
650 			 */
651 			goto activate_rxt;
652 		}
653 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
654 		if (rsm == NULL) {
655 			/* We found no rsm to TLP with. */
656 			goto activate_rxt;
657 		}
658 		if (rsm->r_flags & BBR_HAS_FIN) {
659 			/* If its a FIN we don't do TLP */
660 			rsm = NULL;
661 			goto activate_rxt;
662 		}
663 		time_since_sent = 0;
664 		idx = rsm->r_rtr_cnt - 1;
665 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
666 			tstmp_touse = rsm->r_tim_lastsent[idx];
667 		else
668 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
669 		if (TSTMP_GT(tstmp_touse, cts))
670 		    time_since_sent = cts - tstmp_touse;
671 		is_tlp_timer = 1;
672 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
673 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
674 		if (thresh > time_since_sent)
675 			to = thresh - time_since_sent;
676 		else
677 			to = bbr->r_ctl.rc_min_to;
678 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
679 			/*
680 			 * If the TLP time works out to larger than the max
681 			 * RTO lets not do TLP.. just RTO.
682 			 */
683 			goto activate_rxt;
684 		}
685 		if ((bbr->rc_tlp_rtx_out == 1) &&
686 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
687 			/*
688 			 * Second retransmit of the same TLP
689 			 * lets not.
690 			 */
691 			bbr->rc_tlp_rtx_out = 0;
692 			goto activate_rxt;
693 		}
694 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
695 			/*
696 			 * The tail is no longer the last one I did a probe
697 			 * on
698 			 */
699 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
700 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
701 		}
702 	}
703 	if (is_tlp_timer == 0) {
704 		BBR_STAT_INC(bbr_to_arm_rack);
705 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
706 	} else {
707 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
708 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
709 			/*
710 			 * We have exceeded how many times we can retran the
711 			 * current TLP timer, switch to the RTO timer.
712 			 */
713 			goto activate_rxt;
714 		} else {
715 			BBR_STAT_INC(bbr_to_arm_tlp);
716 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
717 		}
718 	}
719 	return (to);
720 }
721 
722 static inline int32_t
723 bbr_minseg(struct tcp_bbr *bbr)
724 {
725 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
726 }
727 
728 static void
729 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
730 {
731 	struct inpcb *inp = tptoinpcb(tp);
732 	struct hpts_diag diag;
733 	uint32_t delayed_ack = 0;
734 	uint32_t left = 0;
735 	uint32_t hpts_timeout;
736 	uint8_t stopped;
737 	int32_t delay_calc = 0;
738 	uint32_t prev_delay = 0;
739 
740 	if (tcp_in_hpts(tp)) {
741 		/* A previous call is already set up */
742 		return;
743 	}
744 	if ((tp->t_state == TCPS_CLOSED) ||
745 	    (tp->t_state == TCPS_LISTEN)) {
746 		return;
747 	}
748 	stopped = bbr->rc_tmr_stopped;
749 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
750 		left = bbr->r_ctl.rc_timer_exp - cts;
751 	}
752 	bbr->r_ctl.rc_hpts_flags = 0;
753 	bbr->r_ctl.rc_timer_exp = 0;
754 	prev_delay = bbr->r_ctl.rc_last_delay_val;
755 	if (bbr->r_ctl.rc_last_delay_val &&
756 	    (slot == 0)) {
757 		/*
758 		 * If a previous pacer delay was in place we
759 		 * are not coming from the output side (where
760 		 * we calculate a delay, more likely a timer).
761 		 */
762 		slot = bbr->r_ctl.rc_last_delay_val;
763 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
764 			/* Compensate for time passed  */
765 			delay_calc = cts - bbr->rc_pacer_started;
766 			if (delay_calc <= slot)
767 				slot -= delay_calc;
768 		}
769 	}
770 	/* Do we have early to make up for by pushing out the pacing time? */
771 	if (bbr->r_agg_early_set) {
772 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
773 		slot += bbr->r_ctl.rc_agg_early;
774 		bbr->r_ctl.rc_agg_early = 0;
775 		bbr->r_agg_early_set = 0;
776 	}
777 	/* Are we running a total debt that needs to be compensated for? */
778 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
779 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
780 			/* We nuke the delay */
781 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
782 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
783 		} else {
784 			/* We nuke some of the delay, put in a minimal 100usecs  */
785 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
786 			bbr->r_ctl.rc_last_delay_val = slot = 100;
787 		}
788 	}
789 	bbr->r_ctl.rc_last_delay_val = slot;
790 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
791 	if (tp->t_flags & TF_DELACK) {
792 		if (bbr->rc_in_persist == 0) {
793 			delayed_ack = bbr_delack_time;
794 		} else {
795 			/*
796 			 * We are in persists and have
797 			 * gotten a new data element.
798 			 */
799 			if (hpts_timeout > bbr_delack_time) {
800 				/*
801 				 * Lets make the persists timer (which acks)
802 				 * be the smaller of hpts_timeout and bbr_delack_time.
803 				 */
804 				hpts_timeout = bbr_delack_time;
805 			}
806 		}
807 	}
808 	if (delayed_ack &&
809 	    ((hpts_timeout == 0) ||
810 	     (delayed_ack < hpts_timeout))) {
811 		/* We need a Delayed ack timer */
812 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
813 		hpts_timeout = delayed_ack;
814 	}
815 	if (slot) {
816 		/* Mark that we have a pacing timer up */
817 		BBR_STAT_INC(bbr_paced_segments);
818 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
819 	}
820 	/*
821 	 * If no timers are going to run and we will fall off thfe hptsi
822 	 * wheel, we resort to a keep-alive timer if its configured.
823 	 */
824 	if ((hpts_timeout == 0) &&
825 	    (slot == 0)) {
826 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
827 		    (tp->t_state <= TCPS_CLOSING)) {
828 			/*
829 			 * Ok we have no timer (persists, rack, tlp, rxt  or
830 			 * del-ack), we don't have segments being paced. So
831 			 * all that is left is the keepalive timer.
832 			 */
833 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
834 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
835 			} else {
836 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
837 			}
838 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
839 		}
840 	}
841 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
842 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
843 		/*
844 		 * RACK, TLP, persists and RXT timers all are restartable
845 		 * based on actions input .. i.e we received a packet (ack
846 		 * or sack) and that changes things (rw, or snd_una etc).
847 		 * Thus we can restart them with a new value. For
848 		 * keep-alive, delayed_ack we keep track of what was left
849 		 * and restart the timer with a smaller value.
850 		 */
851 		if (left < hpts_timeout)
852 			hpts_timeout = left;
853 	}
854 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
855 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
856 		/*
857 		 * If configured to do so, and the timer is either
858 		 * the TLP or RXT timer, we need to increase the timeout
859 		 * by the pacing time. Consider the bottleneck at my
860 		 * machine as an example, we are sending something
861 		 * to start a TLP on. The last packet won't be emitted
862 		 * fully until the pacing time (the bottleneck will hold
863 		 * the data in place). Once the packet is emitted that
864 		 * is when we want to start waiting for the TLP. This
865 		 * is most evident with hardware pacing (where the nic
866 		 * is holding the packet(s) before emitting). But it
867 		 * can also show up in the network so we do it for all
868 		 * cases. Technically we would take off one packet from
869 		 * this extra delay but this is easier and being more
870 		 * conservative is probably better.
871 		 */
872 		hpts_timeout += slot;
873 	}
874 	if (hpts_timeout) {
875 		/*
876 		 * Hack alert for now we can't time-out over 2147 seconds (a
877 		 * bit more than 35min)
878 		 */
879 		if (hpts_timeout > 0x7ffffffe)
880 			hpts_timeout = 0x7ffffffe;
881 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
882 	} else
883 		bbr->r_ctl.rc_timer_exp = 0;
884 	if ((slot) &&
885 	    (bbr->rc_use_google ||
886 	     bbr->output_error_seen ||
887 	     (slot <= hpts_timeout))  ) {
888 		/*
889 		 * Tell LRO that it can queue packets while
890 		 * we pace.
891 		 */
892 		bbr->rc_tp->t_flags2 |= TF2_MBUF_QUEUE_READY;
893 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
894 		    (bbr->rc_cwnd_limited == 0)) {
895 			/*
896 			 * If we are not cwnd limited and we
897 			 * are running a rack timer we put on
898 			 * the do not disturbe even for sack.
899 			 */
900 			tp->t_flags2 |= TF2_DONT_SACK_QUEUE;
901 		} else
902 			tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
903 		bbr->rc_pacer_started = cts;
904 
905 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(slot),
906 					   __LINE__, &diag);
907 		bbr->rc_timer_first = 0;
908 		bbr->bbr_timer_src = frm;
909 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
910 		bbr_log_hpts_diag(bbr, cts, &diag);
911 	} else if (hpts_timeout) {
912 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(hpts_timeout),
913 					   __LINE__, &diag);
914 		/*
915 		 * We add the flag here as well if the slot is set,
916 		 * since hpts will call in to clear the queue first before
917 		 * calling the output routine (which does our timers).
918 		 * We don't want to set the flag if its just a timer
919 		 * else the arrival of data might (that causes us
920 		 * to send more) might get delayed. Imagine being
921 		 * on a keep-alive timer and a request comes in for
922 		 * more data.
923 		 */
924 		if (slot)
925 			bbr->rc_pacer_started = cts;
926 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
927 		    (bbr->rc_cwnd_limited == 0)) {
928 			/*
929 			 * For a rack timer, don't wake us even
930 			 * if a sack arrives as long as we are
931 			 * not cwnd limited.
932 			 */
933 			tp->t_flags2 |= (TF2_MBUF_QUEUE_READY |
934 			    TF2_DONT_SACK_QUEUE);
935 		} else {
936 			/* All other timers wake us up */
937 			tp->t_flags2 &= ~(TF2_MBUF_QUEUE_READY |
938 			    TF2_DONT_SACK_QUEUE);
939 		}
940 		bbr->bbr_timer_src = frm;
941 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
942 		bbr_log_hpts_diag(bbr, cts, &diag);
943 		bbr->rc_timer_first = 1;
944 	}
945 	bbr->rc_tmr_stopped = 0;
946 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
947 }
948 
949 static void
950 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
951 {
952 	/*
953 	 * We received an ack, and then did not call send or were bounced
954 	 * out due to the hpts was running. Now a timer is up as well, is it
955 	 * the right timer?
956 	 */
957 	struct inpcb *inp;
958 	struct bbr_sendmap *rsm;
959 	uint32_t hpts_timeout;
960 	int tmr_up;
961 
962 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
963 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
964 		return;
965 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
966 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
967 	    (tmr_up == PACE_TMR_RXT)) {
968 		/* Should be an RXT */
969 		return;
970 	}
971 	inp = bbr->rc_inp;
972 	if (rsm == NULL) {
973 		/* Nothing outstanding? */
974 		if (tp->t_flags & TF_DELACK) {
975 			if (tmr_up == PACE_TMR_DELACK)
976 				/*
977 				 * We are supposed to have delayed ack up
978 				 * and we do
979 				 */
980 				return;
981 		} else if (sbavail(&inp->inp_socket->so_snd) &&
982 		    (tmr_up == PACE_TMR_RXT)) {
983 			/*
984 			 * if we hit enobufs then we would expect the
985 			 * possibility of nothing outstanding and the RXT up
986 			 * (and the hptsi timer).
987 			 */
988 			return;
989 		} else if (((V_tcp_always_keepalive ||
990 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
991 			    (tp->t_state <= TCPS_CLOSING)) &&
992 			    (tmr_up == PACE_TMR_KEEP) &&
993 		    (tp->snd_max == tp->snd_una)) {
994 			/* We should have keep alive up and we do */
995 			return;
996 		}
997 	}
998 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
999 		if ((tp->t_flags & TF_SENTFIN) &&
1000 		    ((tp->snd_max - tp->snd_una) == 1) &&
1001 		    (rsm->r_flags & BBR_HAS_FIN)) {
1002 			/* needs to be a RXT */
1003 			if (tmr_up == PACE_TMR_RXT)
1004 				return;
1005 			else
1006 				goto wrong_timer;
1007 		} else if (tmr_up == PACE_TMR_RACK)
1008 			return;
1009 		else
1010 			goto wrong_timer;
1011 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1012 		/* Rack timer has priority if we have data out */
1013 		return;
1014 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1015 		    ((tmr_up == PACE_TMR_TLP) ||
1016 	    (tmr_up == PACE_TMR_RXT))) {
1017 		/*
1018 		 * Either a TLP or RXT is fine if no sack-passed is in place
1019 		 * and data is outstanding.
1020 		 */
1021 		return;
1022 	} else if (tmr_up == PACE_TMR_DELACK) {
1023 		/*
1024 		 * If the delayed ack was going to go off before the
1025 		 * rtx/tlp/rack timer were going to expire, then that would
1026 		 * be the timer in control. Note we don't check the time
1027 		 * here trusting the code is correct.
1028 		 */
1029 		return;
1030 	}
1031 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1032 	    ((tmr_up == PACE_TMR_RXT) ||
1033 	     (tmr_up == PACE_TMR_TLP) ||
1034 	     (tmr_up == PACE_TMR_RACK))) {
1035 		/*
1036 		 * We have outstanding data and
1037 		 * we *do* have a RACK, TLP or RXT
1038 		 * timer running. We won't restart
1039 		 * anything here since thats probably ok we
1040 		 * will get called with some timer here shortly.
1041 		 */
1042 		return;
1043 	}
1044 	/*
1045 	 * Ok the timer originally started is not what we want now. We will
1046 	 * force the hpts to be stopped if any, and restart with the slot
1047 	 * set to what was in the saved slot.
1048 	 */
1049 wrong_timer:
1050 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1051 		if (tcp_in_hpts(tp))
1052 			tcp_hpts_remove(tp);
1053 		bbr_timer_cancel(bbr, __LINE__, cts);
1054 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1055 		    0);
1056 	} else {
1057 		/*
1058 		 * Output is hptsi so we just need to switch the type of
1059 		 * timer. We don't bother with keep-alive, since when we
1060 		 * jump through the output, it will start the keep-alive if
1061 		 * nothing is sent.
1062 		 *
1063 		 * We only need a delayed-ack added and or the hpts_timeout.
1064 		 */
1065 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1066 		if (tp->t_flags & TF_DELACK) {
1067 			if (hpts_timeout == 0) {
1068 				hpts_timeout = bbr_delack_time;
1069 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1070 			}
1071 			else if (hpts_timeout > bbr_delack_time) {
1072 				hpts_timeout = bbr_delack_time;
1073 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1074 			}
1075 		}
1076 		if (hpts_timeout) {
1077 			if (hpts_timeout > 0x7ffffffe)
1078 				hpts_timeout = 0x7ffffffe;
1079 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1080 		}
1081 	}
1082 }
1083 
1084 int32_t bbr_clear_lost = 0;
1085 
1086 /*
1087  * Considers the two time values now (cts) and earlier.
1088  * If cts is smaller than earlier, we could have
1089  * had a sequence wrap (our counter wraps every
1090  * 70 min or so) or it could be just clock skew
1091  * getting us two different time values. Clock skew
1092  * will show up within 10ms or so. So in such
1093  * a case (where cts is behind earlier time by
1094  * less than 10ms) we return 0. Otherwise we
1095  * return the true difference between them.
1096  */
1097 static inline uint32_t
1098 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1099 	/*
1100 	 * Given two timestamps, the current time stamp cts, and some other
1101 	 * time-stamp taken in theory earlier return the difference. The
1102 	 * trick is here sometimes locking will get the other timestamp
1103 	 * after the cts. If this occurs we need to return 0.
1104 	 */
1105 	if (TSTMP_GEQ(cts, earlier_time))
1106 		return (cts - earlier_time);
1107 	/*
1108 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1109 	 * If its more than 10ms difference then we had a time wrap. Else
1110 	 * its just the normal locking foo. I wonder if we should not go to
1111 	 * 64bit TS and get rid of this issue.
1112 	 */
1113 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1114 		return (0);
1115 	/*
1116 	 * Ok the time must have wrapped. So we need to answer a large
1117 	 * amount of time, which the normal subtraction should do.
1118 	 */
1119 	return (cts - earlier_time);
1120 }
1121 
1122 static int
1123 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1124 {
1125 	uint32_t stat;
1126 	int32_t error;
1127 
1128 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1129 	if (error || req->newptr == NULL)
1130 		return error;
1131 
1132 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1133 	if (error)
1134 		return (error);
1135 	if (stat == 1) {
1136 #ifdef BBR_INVARIANTS
1137 		printf("Clearing BBR lost counters\n");
1138 #endif
1139 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1140 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1141 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1142 	} else if (stat == 2) {
1143 #ifdef BBR_INVARIANTS
1144 		printf("Clearing BBR option counters\n");
1145 #endif
1146 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1147 	} else if (stat == 3) {
1148 #ifdef BBR_INVARIANTS
1149 		printf("Clearing BBR stats counters\n");
1150 #endif
1151 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1152 	} else if (stat == 4) {
1153 #ifdef BBR_INVARIANTS
1154 		printf("Clearing BBR out-size counters\n");
1155 #endif
1156 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1157 	}
1158 	bbr_clear_lost = 0;
1159 	return (0);
1160 }
1161 
1162 static void
1163 bbr_init_sysctls(void)
1164 {
1165 	struct sysctl_oid *bbr_probertt;
1166 	struct sysctl_oid *bbr_hptsi;
1167 	struct sysctl_oid *bbr_measure;
1168 	struct sysctl_oid *bbr_cwnd;
1169 	struct sysctl_oid *bbr_timeout;
1170 	struct sysctl_oid *bbr_states;
1171 	struct sysctl_oid *bbr_startup;
1172 	struct sysctl_oid *bbr_policer;
1173 
1174 	/* Probe rtt controls */
1175 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1176 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1177 	    OID_AUTO,
1178 	    "probertt",
1179 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1180 	    "");
1181 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1182 	    SYSCTL_CHILDREN(bbr_probertt),
1183 	    OID_AUTO, "gain", CTLFLAG_RW,
1184 	    &bbr_rttprobe_gain, 192,
1185 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1186 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1187 	    SYSCTL_CHILDREN(bbr_probertt),
1188 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1189 	    &bbr_rtt_probe_cwndtarg, 4,
1190 	    "How many mss's are outstanding during probe-rtt");
1191 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1192 	    SYSCTL_CHILDREN(bbr_probertt),
1193 	    OID_AUTO, "int", CTLFLAG_RW,
1194 	    &bbr_rtt_probe_limit, 4000000,
1195 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1196 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1197 	    SYSCTL_CHILDREN(bbr_probertt),
1198 	    OID_AUTO, "mintime", CTLFLAG_RW,
1199 	    &bbr_rtt_probe_time, 200000,
1200 	    "How many microseconds in probe-rtt");
1201 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1202 	    SYSCTL_CHILDREN(bbr_probertt),
1203 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1204 	    &bbr_filter_len_sec, 6,
1205 	    "How long in seconds does the rttProp filter run?");
1206 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1207 	    SYSCTL_CHILDREN(bbr_probertt),
1208 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1209 	    &bbr_drain_rtt, BBR_SRTT,
1210 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1211 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1212 	    SYSCTL_CHILDREN(bbr_probertt),
1213 	    OID_AUTO, "can_force", CTLFLAG_RW,
1214 	    &bbr_can_force_probertt, 0,
1215 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1216 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1217 	    SYSCTL_CHILDREN(bbr_probertt),
1218 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1219 	    &bbr_probertt_sets_rtt, 0,
1220 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1221 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1222 	    SYSCTL_CHILDREN(bbr_probertt),
1223 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1224 	    &bbr_can_adjust_probertt, 1,
1225 	    "Can we dynamically adjust the probe-rtt limits and times?");
1226 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1227 	    SYSCTL_CHILDREN(bbr_probertt),
1228 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1229 	    &bbr_is_ratio, 0,
1230 	    "is the limit to filter a ratio?");
1231 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1232 	    SYSCTL_CHILDREN(bbr_probertt),
1233 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1234 	    &bbr_prtt_slam_cwnd, 0,
1235 	    "Should we set/recover cwnd?");
1236 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1237 	    SYSCTL_CHILDREN(bbr_probertt),
1238 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1239 	    &bbr_can_use_ts_for_rtt, 1,
1240 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1241 
1242 	/* Pacing controls */
1243 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1244 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1245 	    OID_AUTO,
1246 	    "pacing",
1247 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1248 	    "");
1249 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1250 	    SYSCTL_CHILDREN(bbr_hptsi),
1251 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1252 	    &bbr_allow_hdwr_pacing, 1,
1253 	    "Do we allow hardware pacing?");
1254 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1255 	    SYSCTL_CHILDREN(bbr_hptsi),
1256 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1257 	    &bbr_hardware_pacing_limit, 4000,
1258 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1259 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1260 	    SYSCTL_CHILDREN(bbr_hptsi),
1261 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1262 	    &bbr_hdwr_pace_adjust, 2,
1263 	    "Multiplier to calculated tso size?");
1264 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1265 	    SYSCTL_CHILDREN(bbr_hptsi),
1266 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1267 	    &bbr_hdwr_pace_floor, 1,
1268 	    "Do we invoke the hardware pacing floor?");
1269 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1270 	    SYSCTL_CHILDREN(bbr_hptsi),
1271 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1272 	    &bbr_hdwr_pacing_delay_cnt, 10,
1273 	    "How many packets must be sent after hdwr pacing is enabled");
1274 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1275 	    SYSCTL_CHILDREN(bbr_hptsi),
1276 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1277 	    &bbr_cross_over, 3000000,
1278 	    "What is the point where we cross over to linux like TSO size set");
1279 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1280 	    SYSCTL_CHILDREN(bbr_hptsi),
1281 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1282 	    &bbr_hptsi_segments_delay_tar, 7000,
1283 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1284 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1285 	    SYSCTL_CHILDREN(bbr_hptsi),
1286 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1287 	    &bbr_include_enet_oh, 0,
1288 	    "Do we include the ethernet overhead in calculating pacing delay?");
1289 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1290 	    SYSCTL_CHILDREN(bbr_hptsi),
1291 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1292 	    &bbr_include_ip_oh, 1,
1293 	    "Do we include the IP overhead in calculating pacing delay?");
1294 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1295 	    SYSCTL_CHILDREN(bbr_hptsi),
1296 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1297 	    &bbr_include_tcp_oh, 0,
1298 	    "Do we include the TCP overhead in calculating pacing delay?");
1299 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1300 	    SYSCTL_CHILDREN(bbr_hptsi),
1301 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1302 	    &bbr_google_discount, 10,
1303 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1304 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1305 	    SYSCTL_CHILDREN(bbr_hptsi),
1306 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1307 	    &bbr_all_get_min, 0,
1308 	    "If you are less than a MSS do you just get the min?");
1309 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1310 	    SYSCTL_CHILDREN(bbr_hptsi),
1311 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1312 	    &bbr_hptsi_bytes_min, 1460,
1313 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1314 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1315 	    SYSCTL_CHILDREN(bbr_hptsi),
1316 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1317 	    &bbr_hptsi_segments_max, 6,
1318 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1319 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1320 	    SYSCTL_CHILDREN(bbr_hptsi),
1321 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1322 	    &bbr_hptsi_segments_floor, 1,
1323 	    "Minimum TSO size we will fall too in segments");
1324 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1325 	    SYSCTL_CHILDREN(bbr_hptsi),
1326 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1327 	    &bbr_hptsi_utter_max, 0,
1328 	    "The absolute maximum that any pacing (outside of hardware) can be");
1329 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1330 	    SYSCTL_CHILDREN(bbr_hptsi),
1331 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1332 	    &bbr_hptsi_per_second, 100,
1333 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1334 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1335 	    SYSCTL_CHILDREN(bbr_hptsi),
1336 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1337 	    &bbr_hptsi_max_mul, 1,
1338 	    "The multiplier for pace len max");
1339 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1340 	    SYSCTL_CHILDREN(bbr_hptsi),
1341 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1342 	    &bbr_hptsi_max_div, 2,
1343 	    "The divisor for pace len max");
1344 	/* Measurement controls */
1345 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1346 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1347 	    OID_AUTO,
1348 	    "measure",
1349 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1350 	    "Measurement controls");
1351 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1352 	    SYSCTL_CHILDREN(bbr_measure),
1353 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1354 	    &bbr_initial_bw_bps, 62500,
1355 	    "Minimum initial b/w in bytes per second");
1356 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1357 	    SYSCTL_CHILDREN(bbr_measure),
1358 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1359 	    &bbr_sack_not_required, 0,
1360 	    "Do we allow bbr to run on connections not supporting SACK?");
1361 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1362 	    SYSCTL_CHILDREN(bbr_measure),
1363 	    OID_AUTO, "use_google", CTLFLAG_RW,
1364 	    &bbr_use_google_algo, 0,
1365 	    "Use has close to google V1.0 has possible?");
1366 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1367 	    SYSCTL_CHILDREN(bbr_measure),
1368 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1369 	    &bbr_ts_limiting, 1,
1370 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1371 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1372 	    SYSCTL_CHILDREN(bbr_measure),
1373 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1374 	    &bbr_ts_can_raise, 0,
1375 	    "Can we raise the b/w via timestamp b/w calculation?");
1376 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1377 	    SYSCTL_CHILDREN(bbr_measure),
1378 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1379 	    &bbr_min_usec_delta, 20000,
1380 	    "How long in usec between ts of our sends in ts validation code?");
1381 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1382 	    SYSCTL_CHILDREN(bbr_measure),
1383 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1384 	    &bbr_min_peer_delta, 20,
1385 	    "What min numerical value should be between the peer deltas?");
1386 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1387 	    SYSCTL_CHILDREN(bbr_measure),
1388 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1389 	    &bbr_delta_percent, 150,
1390 	    "What percentage (150 = 15.0) do we allow variance for?");
1391 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1392 	    SYSCTL_CHILDREN(bbr_measure),
1393 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1394 	    &bbr_min_measurements_req, 1,
1395 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1396 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1397 	    SYSCTL_CHILDREN(bbr_measure),
1398 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1399 	    &bbr_no_pacing_until, 4,
1400 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1401 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1402 	    SYSCTL_CHILDREN(bbr_measure),
1403 	    OID_AUTO, "quanta", CTLFLAG_RW,
1404 	    &bbr_quanta, 2,
1405 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1406 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1407 	    SYSCTL_CHILDREN(bbr_measure),
1408 	    OID_AUTO, "noretran", CTLFLAG_RW,
1409 	    &bbr_no_retran, 0,
1410 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1411 	/* State controls */
1412 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1413 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1414 	    OID_AUTO,
1415 	    "states",
1416 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1417 	    "State controls");
1418 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1419 	    SYSCTL_CHILDREN(bbr_states),
1420 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1421 	    &bbr_uses_idle_restart, 0,
1422 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1423 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1424 	    SYSCTL_CHILDREN(bbr_states),
1425 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1426 	    &bbr_idle_restart_threshold, 100000,
1427 	    "How long must we be idle before we restart??");
1428 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1429 	    SYSCTL_CHILDREN(bbr_states),
1430 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1431 	    &bbr_state_is_pkt_epoch, 0,
1432 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1433 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1434 	    SYSCTL_CHILDREN(bbr_states),
1435 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1436 	    &bbr_rtt_gain_thresh, 0,
1437 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1438 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1439 	    SYSCTL_CHILDREN(bbr_states),
1440 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1441 	    &bbr_drain_floor, 88,
1442 	    "What is the lowest we can drain (pg) too?");
1443 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1444 	    SYSCTL_CHILDREN(bbr_states),
1445 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1446 	    &bbr_state_drain_2_tar, 1,
1447 	    "Do we drain to target in drain substate?");
1448 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1449 	    SYSCTL_CHILDREN(bbr_states),
1450 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1451 	    &bbr_gain_to_target, 1,
1452 	    "Does probe bw gain to target??");
1453 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1454 	    SYSCTL_CHILDREN(bbr_states),
1455 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1456 	    &bbr_gain_gets_extra_too, 1,
1457 	    "Does probe bw gain get the extra time too?");
1458 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1459 	    SYSCTL_CHILDREN(bbr_states),
1460 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1461 	    &bbr_drain_drop_div, 5,
1462 	    "Long drain drop divider?");
1463 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1464 	    SYSCTL_CHILDREN(bbr_states),
1465 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1466 	    &bbr_drain_drop_mul, 4,
1467 	    "Long drain drop multiplier?");
1468 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1469 	    SYSCTL_CHILDREN(bbr_states),
1470 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1471 	    &bbr_rand_ot, 50,
1472 	    "Random discount of the ot?");
1473 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1474 	    SYSCTL_CHILDREN(bbr_states),
1475 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1476 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1477 	    "How many packet-epochs does the b/w delivery rate last?");
1478 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1479 	    SYSCTL_CHILDREN(bbr_states),
1480 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1481 	    &bbr_sub_drain_app_limit, 0,
1482 	    "Does our sub-state drain invoke app limited if its long?");
1483 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1484 	    SYSCTL_CHILDREN(bbr_states),
1485 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1486 	    &bbr_sub_drain_slam_cwnd, 0,
1487 	    "Should we set/recover cwnd for sub-state drain?");
1488 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1489 	    SYSCTL_CHILDREN(bbr_states),
1490 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1491 	    &bbr_slam_cwnd_in_main_drain, 0,
1492 	    "Should we set/recover cwnd for main-state drain?");
1493 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1494 	    SYSCTL_CHILDREN(bbr_states),
1495 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1496 	    &google_allow_early_out, 1,
1497 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1498 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1499 	    SYSCTL_CHILDREN(bbr_states),
1500 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1501 	    &google_consider_lost, 1,
1502 	    "Should we have losses exit gain of probebw in google mode??");
1503 	/* Startup controls */
1504 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1505 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1506 	    OID_AUTO,
1507 	    "startup",
1508 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1509 	    "Startup controls");
1510 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1511 	    SYSCTL_CHILDREN(bbr_startup),
1512 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1513 	    &bbr_sends_full_iwnd, 1,
1514 	    "Do we not pace but burst out initial windows has our TSO size?");
1515 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1516 	    SYSCTL_CHILDREN(bbr_startup),
1517 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1518 	    &bbr_startup_loss_thresh, 2000,
1519 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1520 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1521 	    SYSCTL_CHILDREN(bbr_startup),
1522 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1523 	    &bbr_use_lower_gain_in_startup, 1,
1524 	    "Should we use a lower hptsi gain if we see loss in startup?");
1525 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1526 	    SYSCTL_CHILDREN(bbr_startup),
1527 	    OID_AUTO, "gain", CTLFLAG_RW,
1528 	    &bbr_start_exit, 25,
1529 	    "What gain percent do we need to see to stay in startup??");
1530 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1531 	    SYSCTL_CHILDREN(bbr_startup),
1532 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1533 	    &bbr_low_start_exit, 15,
1534 	    "What gain percent do we need to see to stay in the lower gain startup??");
1535 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1536 	    SYSCTL_CHILDREN(bbr_startup),
1537 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1538 	    &bbr_exit_startup_at_loss, 1,
1539 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1540 	/* CWND controls */
1541 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1542 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1543 	    OID_AUTO,
1544 	    "cwnd",
1545 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1546 	    "Cwnd controls");
1547 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1548 	    SYSCTL_CHILDREN(bbr_cwnd),
1549 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1550 	    &bbr_cwndtarget_rtt_touse, 0,
1551 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1552 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1553 	    SYSCTL_CHILDREN(bbr_cwnd),
1554 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1555 	    &bbr_cwnd_may_shrink, 0,
1556 	    "Can the cwnd shrink if it would grow to more than the target?");
1557 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1558 	    SYSCTL_CHILDREN(bbr_cwnd),
1559 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1560 	    &bbr_target_cwnd_mult_limit, 8,
1561 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1562 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1563 	    SYSCTL_CHILDREN(bbr_cwnd),
1564 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1565 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1566 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1567 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1568 	    SYSCTL_CHILDREN(bbr_cwnd),
1569 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1570 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1571 	    "What is the min cwnd (rttProp > 1ms)");
1572 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1573 	    SYSCTL_CHILDREN(bbr_cwnd),
1574 	    OID_AUTO, "initwin", CTLFLAG_RW,
1575 	    &bbr_def_init_win, 10,
1576 	    "What is the BBR initial window, if 0 use tcp version");
1577 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1578 	    SYSCTL_CHILDREN(bbr_cwnd),
1579 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1580 	    &bbr_do_red, 600,
1581 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1582 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1583 	    SYSCTL_CHILDREN(bbr_cwnd),
1584 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1585 	    &bbr_red_scale, 20000,
1586 	    "What RTT do we scale with?");
1587 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1588 	    SYSCTL_CHILDREN(bbr_cwnd),
1589 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1590 	    &bbr_red_growth_restrict, 1,
1591 	    "Do we restrict cwnd growth for whats in flight?");
1592 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1593 	    SYSCTL_CHILDREN(bbr_cwnd),
1594 	    OID_AUTO, "red_div", CTLFLAG_RW,
1595 	    &bbr_red_div, 2,
1596 	    "If we reduce whats the divisor?");
1597 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1598 	    SYSCTL_CHILDREN(bbr_cwnd),
1599 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1600 	    &bbr_red_mul, 1,
1601 	    "If we reduce whats the mulitiplier?");
1602 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1603 	    SYSCTL_CHILDREN(bbr_cwnd),
1604 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1605 	    &bbr_target_is_bbunit, 0,
1606 	    "Is the state target the pacing_gain or BBR_UNIT?");
1607 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1608 	    SYSCTL_CHILDREN(bbr_cwnd),
1609 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1610 	    &bbr_drop_limit, 0,
1611 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1612 
1613 	/* Timeout controls */
1614 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1615 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1616 	    OID_AUTO,
1617 	    "timeout",
1618 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1619 	    "Time out controls");
1620 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1621 	    SYSCTL_CHILDREN(bbr_timeout),
1622 	    OID_AUTO, "delack", CTLFLAG_RW,
1623 	    &bbr_delack_time, 100000,
1624 	    "BBR's delayed ack time");
1625 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1626 	    SYSCTL_CHILDREN(bbr_timeout),
1627 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1628 	    &bbr_tlp_type_to_use, 3,
1629 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1630 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1631 	    SYSCTL_CHILDREN(bbr_timeout),
1632 	    OID_AUTO, "persmin", CTLFLAG_RW,
1633 	    &bbr_persist_min, 250000,
1634 	    "What is the minimum time in microseconds between persists");
1635 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1636 	    SYSCTL_CHILDREN(bbr_timeout),
1637 	    OID_AUTO, "persmax", CTLFLAG_RW,
1638 	    &bbr_persist_max, 1000000,
1639 	    "What is the largest delay in microseconds between persists");
1640 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1641 	    SYSCTL_CHILDREN(bbr_timeout),
1642 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1643 	    &bbr_tlp_min, 10000,
1644 	    "TLP Min timeout in usecs");
1645 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1646 	    SYSCTL_CHILDREN(bbr_timeout),
1647 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1648 	    &bbr_delayed_ack_time, 200000,
1649 	    "TLP delayed ack compensation value");
1650 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1651 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1652 	    OID_AUTO, "minrto", CTLFLAG_RW,
1653 	    &bbr_rto_min_ms, 30,
1654 	    "Minimum RTO in ms");
1655 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1656 	    SYSCTL_CHILDREN(bbr_timeout),
1657 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1658 	    &bbr_rto_max_sec, 4,
1659 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1660 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1661 	    SYSCTL_CHILDREN(bbr_timeout),
1662 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1663 	    &bbr_tlp_max_resend, 2,
1664 	    "How many times does TLP retry a single segment or multiple with no ACK");
1665 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1666 	    SYSCTL_CHILDREN(bbr_timeout),
1667 	    OID_AUTO, "minto", CTLFLAG_RW,
1668 	    &bbr_min_to, 1000,
1669 	    "Minimum rack timeout in useconds");
1670 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1671 	    SYSCTL_CHILDREN(bbr_timeout),
1672 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1673 	    &bbr_pkt_delay, 1000,
1674 	    "Extra RACK time (in useconds) besides reordering thresh");
1675 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1676 	    SYSCTL_CHILDREN(bbr_timeout),
1677 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1678 	    &bbr_incr_timers, 1,
1679 	    "Increase the RXT/TLP timer by the pacing time used?");
1680 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1681 	    SYSCTL_CHILDREN(bbr_timeout),
1682 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1683 	    &bbr_marks_rxt_sack_passed, 0,
1684 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1685 	/* Policer controls */
1686 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1687 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1688 	    OID_AUTO,
1689 	    "policer",
1690 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1691 	    "Policer controls");
1692 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1693 	    SYSCTL_CHILDREN(bbr_policer),
1694 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1695 	    &bbr_policer_detection_enabled, 1,
1696 	    "Is policer detection enabled??");
1697 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1698 	    SYSCTL_CHILDREN(bbr_policer),
1699 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1700 	    &bbr_lt_intvl_min_rtts, 4,
1701 	    "Minimum number of PE's?");
1702 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1703 	    SYSCTL_CHILDREN(bbr_policer),
1704 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1705 	    &bbr_lt_bw_diff, (4000/8),
1706 	    "Minimal bw diff?");
1707 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1708 	    SYSCTL_CHILDREN(bbr_policer),
1709 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1710 	    &bbr_lt_bw_ratio, 8,
1711 	    "Minimal bw diff?");
1712 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1713 	    SYSCTL_CHILDREN(bbr_policer),
1714 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1715 	    &bbr_policer_call_from_rack_to, 0,
1716 	    "Do we call the policer detection code from a rack-timeout?");
1717 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1718 	    SYSCTL_CHILDREN(bbr_policer),
1719 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1720 	    &bbr_lt_intvl_fp, 0,
1721 	    "What packet epoch do we do false-positive detection at (0=no)?");
1722 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1723 	    SYSCTL_CHILDREN(bbr_policer),
1724 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1725 	    &bbr_lt_loss_thresh, 196,
1726 	    "Loss threshold 196 = 19.6%?");
1727 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1728 	    SYSCTL_CHILDREN(bbr_policer),
1729 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1730 	    &bbr_lt_fd_thresh, 100,
1731 	    "What percentage is the false detection threshold (150=15.0)?");
1732 	/* All the rest */
1733 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1734 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1735 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1736 	    &bbr_use_rack_resend_cheat, 0,
1737 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1738 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1739 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1740 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1741 	    &bbr_error_base_paceout, 10000,
1742 	    "When we hit an error what is the min to pace out in usec's?");
1743 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1744 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1745 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1746 	    &bbr_max_net_error_cnt, 10,
1747 	    "When we hit this many errors in a row, kill the session?");
1748 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1749 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1750 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1751 	    &bbr_ignore_data_after_close, 1,
1752 	    "Do we hold off sending a RST until all pending data is ack'd");
1753 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1754 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1755 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1756 	    &bbr_resends_use_tso, 0,
1757 	    "Can resends use TSO?");
1758 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1759 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1760 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1761 	    &bbr_sack_block_limit, 128,
1762 	    "When do we start ignoring small sack blocks");
1763 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1764 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1765 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1766 	    &bbr_verbose_logging, 0,
1767 	    "Should BBR black box logging be verbose");
1768 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1769 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1770 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1771 	    &bbr_reorder_thresh, 2,
1772 	    "What factor for rack will be added when seeing reordering (shift right)");
1773 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1774 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1775 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1776 	    &bbr_reorder_fade, 0,
1777 	    "Does reorder detection fade, if so how many ms (0 means never)");
1778 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1779 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1780 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1781 	    &bbr_tlp_thresh, 1,
1782 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1783 	/* Stats and counters */
1784 	/* The pacing counters for hdwr/software can't be in the array */
1785 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1786 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1787 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1788 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1789 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1790 	    &bbr_hdwr_pacing_enobuf,
1791 	    "Total number of enobufs for hardware paced flows");
1792 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1793 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1794 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1795 	    &bbr_nohdwr_pacing_enobuf,
1796 	    "Total number of enobufs for non-hardware paced flows");
1797 
1798 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1799 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1800 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1801 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1802 	    &bbr_flows_whdwr_pacing,
1803 	    "Total number of hardware paced flows");
1804 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1805 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1806 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1807 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1808 	    &bbr_flows_nohdwr_pacing,
1809 	    "Total number of software paced flows");
1810 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1811 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1812 	    OID_AUTO, "stats", CTLFLAG_RD,
1813 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1814 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1815 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1816 	    OID_AUTO, "opts", CTLFLAG_RD,
1817 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1818 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1819 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1820 	    OID_AUTO, "lost", CTLFLAG_RD,
1821 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1822 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1823 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1824 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1825 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1826 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1827 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1828 	    OID_AUTO, "statetime", CTLFLAG_RD,
1829 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1830 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1831 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1832 	    OID_AUTO, "outsize", CTLFLAG_RD,
1833 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1834 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1835 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1836 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1837 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1838 }
1839 
1840 static void
1841 bbr_counter_destroy(void)
1842 {
1843 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1844 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1845 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1846 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1847 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1848 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1849 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1850 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1851 	counter_u64_free(bbr_flows_whdwr_pacing);
1852 	counter_u64_free(bbr_flows_nohdwr_pacing);
1853 
1854 }
1855 
1856 static __inline void
1857 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1858 {
1859 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1860 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1861 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1862 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1863 	l->bw_inuse = bbr_get_bw(bbr);
1864 	l->inflight = ctf_flight_size(bbr->rc_tp,
1865 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1866 	l->applimited = bbr->r_ctl.r_app_limited_until;
1867 	l->delivered = bbr->r_ctl.rc_delivered;
1868 	l->timeStamp = cts;
1869 	l->lost = bbr->r_ctl.rc_lost;
1870 	l->bbr_state = bbr->rc_bbr_state;
1871 	l->bbr_substate = bbr_state_val(bbr);
1872 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1873 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1874 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1875 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1876 	l->inhpts = tcp_in_hpts(bbr->rc_tp);
1877 	l->use_lt_bw = bbr->rc_lt_use_bw;
1878 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1879 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1880 }
1881 
1882 static void
1883 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1884 {
1885 	if (tcp_bblogging_on(bbr->rc_tp)) {
1886 		union tcp_log_stackspecific log;
1887 
1888 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1889 		log.u_bbr.flex1 = 0;
1890 		log.u_bbr.flex2 = 0;
1891 		log.u_bbr.flex5 = 0;
1892 		log.u_bbr.flex3 = 0;
1893 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1894 		log.u_bbr.flex7 = reason;
1895 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1896 		log.u_bbr.flex8 = 0;
1897 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1898 		    &bbr->rc_inp->inp_socket->so_rcv,
1899 		    &bbr->rc_inp->inp_socket->so_snd,
1900 		    BBR_LOG_BW_RED_EV, 0,
1901 		    0, &log, false, &bbr->rc_tv);
1902 	}
1903 }
1904 
1905 static void
1906 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1907 {
1908 	if (tcp_bblogging_on(bbr->rc_tp)) {
1909 		union tcp_log_stackspecific log;
1910 
1911 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1912 		log.u_bbr.flex1 = seq;
1913 		log.u_bbr.flex2 = count;
1914 		log.u_bbr.flex8 = mode;
1915 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1916 		    &bbr->rc_inp->inp_socket->so_rcv,
1917 		    &bbr->rc_inp->inp_socket->so_snd,
1918 		    BBR_LOG_LOWGAIN, 0,
1919 		    0, &log, false, &bbr->rc_tv);
1920 	}
1921 }
1922 
1923 static void
1924 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1925     uint8_t reason, uint32_t p_maxseg, int len)
1926 {
1927 	if (tcp_bblogging_on(bbr->rc_tp)) {
1928 		union tcp_log_stackspecific log;
1929 
1930 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1931 		log.u_bbr.flex1 = p_maxseg;
1932 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1933 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1934 		log.u_bbr.flex4 = reason;
1935 		log.u_bbr.flex5 = bbr->rc_in_persist;
1936 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1937 		log.u_bbr.flex7 = p_maxseg;
1938 		log.u_bbr.flex8 = bbr->rc_in_persist;
1939 		log.u_bbr.pkts_out = 0;
1940 		log.u_bbr.applimited = len;
1941 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1942 		    &bbr->rc_inp->inp_socket->so_rcv,
1943 		    &bbr->rc_inp->inp_socket->so_snd,
1944 		    BBR_LOG_JUSTRET, 0,
1945 		    tlen, &log, false, &bbr->rc_tv);
1946 	}
1947 }
1948 
1949 static void
1950 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1951 {
1952 	if (tcp_bblogging_on(bbr->rc_tp)) {
1953 		union tcp_log_stackspecific log;
1954 
1955 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1956 		log.u_bbr.flex1 = seq;
1957 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1958 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1959 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1960 		    &bbr->rc_inp->inp_socket->so_rcv,
1961 		    &bbr->rc_inp->inp_socket->so_snd,
1962 		    BBR_LOG_ENTREC, 0,
1963 		    0, &log, false, &bbr->rc_tv);
1964 	}
1965 }
1966 
1967 static void
1968 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)
1969 {
1970 	if (tcp_bblogging_on(tp)) {
1971 		union tcp_log_stackspecific log;
1972 
1973 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1974 		log.u_bbr.flex1 = tso;
1975 		log.u_bbr.flex2 = maxseg;
1976 		log.u_bbr.flex3 = mtu;
1977 		log.u_bbr.flex4 = csum_flags;
1978 		TCP_LOG_EVENTP(tp, NULL,
1979 		    &bbr->rc_inp->inp_socket->so_rcv,
1980 		    &bbr->rc_inp->inp_socket->so_snd,
1981 		    BBR_LOG_MSGSIZE, 0,
1982 		    0, &log, false, &bbr->rc_tv);
1983 	}
1984 }
1985 
1986 static void
1987 bbr_log_flowend(struct tcp_bbr *bbr)
1988 {
1989 	if (tcp_bblogging_on(bbr->rc_tp)) {
1990 		union tcp_log_stackspecific log;
1991 		struct sockbuf *r, *s;
1992 		struct timeval tv;
1993 
1994 		if (bbr->rc_inp->inp_socket) {
1995 			r = &bbr->rc_inp->inp_socket->so_rcv;
1996 			s = &bbr->rc_inp->inp_socket->so_snd;
1997 		} else {
1998 			r = s = NULL;
1999 		}
2000 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2001 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2002 		    r, s,
2003 		    TCP_LOG_FLOWEND, 0,
2004 		    0, &log, false, &tv);
2005 	}
2006 }
2007 
2008 static void
2009 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2010     uint32_t lost, uint32_t del)
2011 {
2012 	if (tcp_bblogging_on(bbr->rc_tp)) {
2013 		union tcp_log_stackspecific log;
2014 
2015 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2016 		log.u_bbr.flex1 = lost;
2017 		log.u_bbr.flex2 = del;
2018 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2019 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2020 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2021 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2022 		log.u_bbr.flex7 = line;
2023 		log.u_bbr.flex8 = 0;
2024 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2025 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2026 		    &bbr->rc_inp->inp_socket->so_rcv,
2027 		    &bbr->rc_inp->inp_socket->so_snd,
2028 		    BBR_LOG_PKT_EPOCH, 0,
2029 		    0, &log, false, &bbr->rc_tv);
2030 	}
2031 }
2032 
2033 static void
2034 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2035 {
2036 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2037 		union tcp_log_stackspecific log;
2038 
2039 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2040 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2041 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2042 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2043 		log.u_bbr.flex7 = line;
2044 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2045 		    &bbr->rc_inp->inp_socket->so_rcv,
2046 		    &bbr->rc_inp->inp_socket->so_snd,
2047 		    BBR_LOG_TIME_EPOCH, 0,
2048 		    0, &log, false, &bbr->rc_tv);
2049 	}
2050 }
2051 
2052 static void
2053 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2054 {
2055 	if (tcp_bblogging_on(bbr->rc_tp)) {
2056 		union tcp_log_stackspecific log;
2057 
2058 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2059 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2060 		log.u_bbr.flex2 = new_tar;
2061 		log.u_bbr.flex3 = line;
2062 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2063 		log.u_bbr.flex5 = bbr_quanta;
2064 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2065 		log.u_bbr.flex7 = bbr->rc_last_options;
2066 		log.u_bbr.flex8 = meth;
2067 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2068 		    &bbr->rc_inp->inp_socket->so_rcv,
2069 		    &bbr->rc_inp->inp_socket->so_snd,
2070 		    BBR_LOG_STATE_TARGET, 0,
2071 		    0, &log, false, &bbr->rc_tv);
2072 	}
2073 
2074 }
2075 
2076 static void
2077 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2078 {
2079 	if (tcp_bblogging_on(bbr->rc_tp)) {
2080 		union tcp_log_stackspecific log;
2081 
2082 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2083 		log.u_bbr.flex1 = line;
2084 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2085 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2086 		if (bbr_state_is_pkt_epoch)
2087 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2088 		else
2089 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2090 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2091 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2092 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2093 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2094 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2095 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2096 		    &bbr->rc_inp->inp_socket->so_rcv,
2097 		    &bbr->rc_inp->inp_socket->so_snd,
2098 		    BBR_LOG_STATE, 0,
2099 		    0, &log, false, &bbr->rc_tv);
2100 	}
2101 }
2102 
2103 static void
2104 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2105 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2106 {
2107 	if (tcp_bblogging_on(bbr->rc_tp)) {
2108 		union tcp_log_stackspecific log;
2109 
2110 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2111 		log.u_bbr.flex1 = line;
2112 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2113 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2114 		log.u_bbr.flex4 = applied;
2115 		log.u_bbr.flex5 = rtt;
2116 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2117 		log.u_bbr.flex7 = cond;
2118 		log.u_bbr.flex8 = reas;
2119 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2120 		    &bbr->rc_inp->inp_socket->so_rcv,
2121 		    &bbr->rc_inp->inp_socket->so_snd,
2122 		    BBR_LOG_RTT_SHRINKS, 0,
2123 		    0, &log, false, &bbr->rc_tv);
2124 	}
2125 }
2126 
2127 static void
2128 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2129 {
2130 	if (tcp_bblogging_on(bbr->rc_tp)) {
2131 		union tcp_log_stackspecific log;
2132 
2133 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2134 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2135 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2136 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2137 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2138 		    &bbr->rc_inp->inp_socket->so_rcv,
2139 		    &bbr->rc_inp->inp_socket->so_snd,
2140 		    BBR_LOG_EXITREC, 0,
2141 		    0, &log, false, &bbr->rc_tv);
2142 	}
2143 }
2144 
2145 static void
2146 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2147     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2148 {
2149 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2150 		union tcp_log_stackspecific log;
2151 
2152 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2153 		log.u_bbr.flex1 = line;
2154 		log.u_bbr.flex2 = prev_acked;
2155 		log.u_bbr.flex3 = bytes_this_ack;
2156 		log.u_bbr.flex4 = chg;
2157 		log.u_bbr.flex5 = th_ack;
2158 		log.u_bbr.flex6 = target;
2159 		log.u_bbr.flex8 = meth;
2160 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2161 		    &bbr->rc_inp->inp_socket->so_rcv,
2162 		    &bbr->rc_inp->inp_socket->so_snd,
2163 		    BBR_LOG_CWND, 0,
2164 		    0, &log, false, &bbr->rc_tv);
2165 	}
2166 }
2167 
2168 static void
2169 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2170 {
2171 	/*
2172 	 * Log the rtt sample we are applying to the srtt algorithm in
2173 	 * useconds.
2174 	 */
2175 	if (tcp_bblogging_on(bbr->rc_tp)) {
2176 		union tcp_log_stackspecific log;
2177 
2178 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2179 		log.u_bbr.flex1 = rtt;
2180 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2181 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2182 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2183 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2184 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2185 		log.u_bbr.flex6 = tsin;
2186 		log.u_bbr.flex7 = 0;
2187 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2188 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2189 		    &bbr->rc_inp->inp_socket->so_rcv,
2190 		    &bbr->rc_inp->inp_socket->so_snd,
2191 		    TCP_LOG_RTT, 0,
2192 		    0, &log, false, &bbr->rc_tv);
2193 	}
2194 }
2195 
2196 static void
2197 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2198 {
2199 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2200 		union tcp_log_stackspecific log;
2201 
2202 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2203 		log.u_bbr.flex1 = time_in;
2204 		log.u_bbr.flex2 = line;
2205 		log.u_bbr.flex8 = enter_exit;
2206 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2207 		    &bbr->rc_inp->inp_socket->so_rcv,
2208 		    &bbr->rc_inp->inp_socket->so_snd,
2209 		    BBR_LOG_PERSIST, 0,
2210 		    0, &log, false, &bbr->rc_tv);
2211 	}
2212 }
2213 static void
2214 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2215 {
2216 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2217 		union tcp_log_stackspecific log;
2218 
2219 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2220 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2221 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2222 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2223 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2224 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2225 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2226 		    &bbr->rc_inp->inp_socket->so_rcv,
2227 		    &bbr->rc_inp->inp_socket->so_snd,
2228 		    BBR_LOG_ACKCLEAR, 0,
2229 		    0, &log, false, &bbr->rc_tv);
2230 	}
2231 }
2232 
2233 static void
2234 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2235 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2236 {
2237 	if (tcp_bblogging_on(bbr->rc_tp)) {
2238 		union tcp_log_stackspecific log;
2239 		struct timeval tv;
2240 
2241 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2242 		log.u_bbr.flex1 = nsegs;
2243 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2244 		if (m) {
2245 			struct timespec ts;
2246 
2247 			log.u_bbr.flex3 = m->m_flags;
2248 			if (m->m_flags & M_TSTMP) {
2249 				mbuf_tstmp2timespec(m, &ts);
2250 				tv.tv_sec = ts.tv_sec;
2251 				tv.tv_usec = ts.tv_nsec / 1000;
2252 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2253 			} else {
2254 				log.u_bbr.lt_epoch = 0;
2255 			}
2256 			if (m->m_flags & M_TSTMP_LRO) {
2257 				mbuf_tstmp2timeval(m, &tv);
2258 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2259 			} else {
2260 				/* No arrival timestamp */
2261 				log.u_bbr.flex5 = 0;
2262 			}
2263 
2264 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2265 		} else {
2266 			log.u_bbr.flex3 = 0;
2267 			log.u_bbr.flex5 = 0;
2268 			log.u_bbr.flex6 = 0;
2269 			log.u_bbr.pkts_out = 0;
2270 		}
2271 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2272 		log.u_bbr.flex7 = bbr->r_wanted_output;
2273 		log.u_bbr.flex8 = bbr->rc_in_persist;
2274 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2275 		    &bbr->rc_inp->inp_socket->so_rcv,
2276 		    &bbr->rc_inp->inp_socket->so_snd,
2277 		    TCP_LOG_IN, 0,
2278 		    tlen, &log, true, &bbr->rc_tv);
2279 	}
2280 }
2281 
2282 static void
2283 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2284 {
2285 	if (tcp_bblogging_on(bbr->rc_tp)) {
2286 		union tcp_log_stackspecific log;
2287 
2288 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2289 		log.u_bbr.flex1 = did_out;
2290 		log.u_bbr.flex2 = nxt_pkt;
2291 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2292 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2293 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2294 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2295 		log.u_bbr.flex7 = bbr->r_wanted_output;
2296 		log.u_bbr.flex8 = bbr->rc_in_persist;
2297 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2298 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2299 		    &bbr->rc_inp->inp_socket->so_rcv,
2300 		    &bbr->rc_inp->inp_socket->so_snd,
2301 		    BBR_LOG_DOSEG_DONE, 0,
2302 		    0, &log, true, &bbr->rc_tv);
2303 	}
2304 }
2305 
2306 static void
2307 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2308     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2309 {
2310 	if (tcp_bblogging_on(bbr->rc_tp)) {
2311 		union tcp_log_stackspecific log;
2312 
2313 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2314 		log.u_bbr.flex1 = line;
2315 		log.u_bbr.flex2 = o_len;
2316 		log.u_bbr.flex3 = segcnt;
2317 		log.u_bbr.flex4 = segsiz;
2318 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2319 		    &bbr->rc_inp->inp_socket->so_rcv,
2320 		    &bbr->rc_inp->inp_socket->so_snd,
2321 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2322 		    len, &log, true, &bbr->rc_tv);
2323 	}
2324 }
2325 
2326 static void
2327 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2328 {
2329 	if (tcp_bblogging_on(bbr->rc_tp)) {
2330 		union tcp_log_stackspecific log;
2331 
2332 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2333 		log.u_bbr.flex1 = timers;
2334 		log.u_bbr.flex2 = ret;
2335 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2336 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2337 		log.u_bbr.flex5 = cts;
2338 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2339 		log.u_bbr.flex8 = hpts_calling;
2340 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2341 		    &bbr->rc_inp->inp_socket->so_rcv,
2342 		    &bbr->rc_inp->inp_socket->so_snd,
2343 		    BBR_LOG_TO_PROCESS, 0,
2344 		    0, &log, false, &bbr->rc_tv);
2345 	}
2346 }
2347 
2348 static void
2349 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2350 {
2351 	if (tcp_bblogging_on(bbr->rc_tp)) {
2352 		union tcp_log_stackspecific log;
2353 		uint64_t ar;
2354 
2355 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2356 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2357 		log.u_bbr.flex2 = 0;
2358 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2359 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2360 		ar >>= 32;
2361 		ar &= 0x00000000ffffffff;
2362 		log.u_bbr.flex4 = (uint32_t)ar;
2363 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2364 		ar &= 0x00000000ffffffff;
2365 		log.u_bbr.flex5 = (uint32_t)ar;
2366 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2367 		log.u_bbr.flex8 = to_num;
2368 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2369 		    &bbr->rc_inp->inp_socket->so_rcv,
2370 		    &bbr->rc_inp->inp_socket->so_snd,
2371 		    BBR_LOG_RTO, 0,
2372 		    0, &log, false, &bbr->rc_tv);
2373 	}
2374 }
2375 
2376 static void
2377 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2378 {
2379 	if (tcp_bblogging_on(bbr->rc_tp)) {
2380 		union tcp_log_stackspecific log;
2381 
2382 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2383 		log.u_bbr.flex1 = flex1;
2384 		log.u_bbr.flex2 = flex2;
2385 		log.u_bbr.flex3 = flex3;
2386 		log.u_bbr.flex4 = 0;
2387 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2388 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2389 		log.u_bbr.flex8 = reason;
2390 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2391 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2392 		    &bbr->rc_inp->inp_socket->so_rcv,
2393 		    &bbr->rc_inp->inp_socket->so_snd,
2394 		    BBR_LOG_REDUCE, 0,
2395 		    0, &log, false, &bbr->rc_tv);
2396 	}
2397 }
2398 
2399 static void
2400 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2401 {
2402 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2403 		union tcp_log_stackspecific log;
2404 
2405 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2406 		log.u_bbr.flex1 = diag->p_nxt_slot;
2407 		log.u_bbr.flex2 = diag->p_cur_slot;
2408 		log.u_bbr.flex3 = diag->slot_req;
2409 		log.u_bbr.flex4 = diag->inp_hptsslot;
2410 		log.u_bbr.flex5 = diag->slot_remaining;
2411 		log.u_bbr.flex6 = diag->need_new_to;
2412 		log.u_bbr.flex7 = diag->p_hpts_active;
2413 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2414 		/* Hijack other fields as needed  */
2415 		log.u_bbr.epoch = diag->have_slept;
2416 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2417 		log.u_bbr.pkts_out = diag->co_ret;
2418 		log.u_bbr.applimited = diag->hpts_sleep_time;
2419 		log.u_bbr.delivered = diag->p_prev_slot;
2420 		log.u_bbr.inflight = diag->p_runningslot;
2421 		log.u_bbr.bw_inuse = diag->wheel_slot;
2422 		log.u_bbr.rttProp = diag->wheel_cts;
2423 		log.u_bbr.delRate = diag->maxslots;
2424 		log.u_bbr.cur_del_rate = diag->p_curtick;
2425 		log.u_bbr.cur_del_rate <<= 32;
2426 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2427 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2428 		    &bbr->rc_inp->inp_socket->so_rcv,
2429 		    &bbr->rc_inp->inp_socket->so_snd,
2430 		    BBR_LOG_HPTSDIAG, 0,
2431 		    0, &log, false, &bbr->rc_tv);
2432 	}
2433 }
2434 
2435 static void
2436 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2437     uint32_t thresh, uint32_t to)
2438 {
2439 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2440 		union tcp_log_stackspecific log;
2441 
2442 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2443 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2444 		log.u_bbr.flex2 = time_since_sent;
2445 		log.u_bbr.flex3 = srtt;
2446 		log.u_bbr.flex4 = thresh;
2447 		log.u_bbr.flex5 = to;
2448 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2449 		log.u_bbr.flex8 = mode;
2450 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2451 		    &bbr->rc_inp->inp_socket->so_rcv,
2452 		    &bbr->rc_inp->inp_socket->so_snd,
2453 		    BBR_LOG_TIMERPREP, 0,
2454 		    0, &log, false, &bbr->rc_tv);
2455 	}
2456 }
2457 
2458 static void
2459 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2460     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2461 {
2462 	if (tcp_bblogging_on(bbr->rc_tp)) {
2463 		union tcp_log_stackspecific log;
2464 
2465 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2466 		log.u_bbr.flex1 = usecs;
2467 		log.u_bbr.flex2 = len;
2468 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2469 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2470 		if (override)
2471 			log.u_bbr.flex5 = (1 << 2);
2472 		else
2473 			log.u_bbr.flex5 = 0;
2474 		log.u_bbr.flex6 = override;
2475 		log.u_bbr.flex7 = gain;
2476 		log.u_bbr.flex8 = mod;
2477 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2478 		    &bbr->rc_inp->inp_socket->so_rcv,
2479 		    &bbr->rc_inp->inp_socket->so_snd,
2480 		    BBR_LOG_HPTSI_CALC, 0,
2481 		    len, &log, false, &bbr->rc_tv);
2482 	}
2483 }
2484 
2485 static void
2486 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2487 {
2488 	if (tcp_bblogging_on(bbr->rc_tp)) {
2489 		union tcp_log_stackspecific log;
2490 
2491 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2492 
2493 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2494 		log.u_bbr.flex2 = to;
2495 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2496 		log.u_bbr.flex4 = slot;
2497 		log.u_bbr.flex5 = bbr->rc_tp->t_hpts_slot;
2498 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2499 		log.u_bbr.pkts_out = bbr->rc_tp->t_flags2;
2500 		log.u_bbr.flex8 = which;
2501 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2502 		    &bbr->rc_inp->inp_socket->so_rcv,
2503 		    &bbr->rc_inp->inp_socket->so_snd,
2504 		    BBR_LOG_TIMERSTAR, 0,
2505 		    0, &log, false, &bbr->rc_tv);
2506 	}
2507 }
2508 
2509 static void
2510 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)
2511 {
2512 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2513 		union tcp_log_stackspecific log;
2514 
2515 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2516 		log.u_bbr.flex1 = thresh;
2517 		log.u_bbr.flex2 = lro;
2518 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2519 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2520 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2521 		log.u_bbr.flex6 = srtt;
2522 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2523 		log.u_bbr.flex8 = frm;
2524 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2525 		    &bbr->rc_inp->inp_socket->so_rcv,
2526 		    &bbr->rc_inp->inp_socket->so_snd,
2527 		    BBR_LOG_THRESH_CALC, 0,
2528 		    0, &log, false, &bbr->rc_tv);
2529 	}
2530 }
2531 
2532 static void
2533 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2534 {
2535 	if (tcp_bblogging_on(bbr->rc_tp)) {
2536 		union tcp_log_stackspecific log;
2537 
2538 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2539 		log.u_bbr.flex1 = line;
2540 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2541 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2542 		log.u_bbr.flex4 = bbr->rc_in_persist;
2543 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2544 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2545 		log.u_bbr.flex8 = hpts_removed;
2546 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2547 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2548 		    &bbr->rc_inp->inp_socket->so_rcv,
2549 		    &bbr->rc_inp->inp_socket->so_snd,
2550 		    BBR_LOG_TIMERCANC, 0,
2551 		    0, &log, false, &bbr->rc_tv);
2552 	}
2553 }
2554 
2555 static void
2556 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2557 {
2558 	if (tcp_bblogging_on(bbr->rc_tp)) {
2559 		union tcp_log_stackspecific log;
2560 
2561 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2562 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2563 		log.u_bbr.flex2 = (peer_delta >> 32);
2564 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2565 		log.u_bbr.flex4 = (delta >> 32);
2566 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2567 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2568 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2569 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2570 		    &bbr->rc_inp->inp_socket->so_rcv,
2571 		    &bbr->rc_inp->inp_socket->so_snd,
2572 		    BBR_LOG_TSTMP_VAL, 0,
2573 		    0, &log, false, &bbr->rc_tv);
2574 	}
2575 }
2576 
2577 static void
2578 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)
2579 {
2580 	if (tcp_bblogging_on(bbr->rc_tp)) {
2581 		union tcp_log_stackspecific log;
2582 
2583 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2584 		log.u_bbr.flex1 = tsosz;
2585 		log.u_bbr.flex2 = tls;
2586 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2587 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2588 		log.u_bbr.flex5 = old_val;
2589 		log.u_bbr.flex6 = maxseg;
2590 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2591 		log.u_bbr.flex7 <<= 1;
2592 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2593 		if (hdwr)
2594 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2595 		else
2596 			log.u_bbr.flex8 = bbr->rc_use_google;
2597 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2598 		    &bbr->rc_inp->inp_socket->so_rcv,
2599 		    &bbr->rc_inp->inp_socket->so_snd,
2600 		    BBR_LOG_BBRTSO, 0,
2601 		    0, &log, false, &bbr->rc_tv);
2602 	}
2603 }
2604 
2605 static void
2606 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2607 		      uint32_t flags, uint32_t line)
2608 {
2609 	if (tcp_bblogging_on(bbr->rc_tp)) {
2610 		union tcp_log_stackspecific log;
2611 
2612 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2613 		log.u_bbr.flex1 = line;
2614 		log.u_bbr.flex2 = rsm->r_start;
2615 		log.u_bbr.flex3 = rsm->r_end;
2616 		log.u_bbr.flex4 = rsm->r_delivered;
2617 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2618 		log.u_bbr.flex6 = rsm->r_dupack;
2619 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2620 		log.u_bbr.flex8 = rsm->r_flags;
2621 		/* Hijack the pkts_out fids */
2622 		log.u_bbr.applimited = flags;
2623 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2624 		    &bbr->rc_inp->inp_socket->so_rcv,
2625 		    &bbr->rc_inp->inp_socket->so_snd,
2626 		    BBR_RSM_CLEARED, 0,
2627 		    0, &log, false, &bbr->rc_tv);
2628 	}
2629 }
2630 
2631 static void
2632 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2633     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2634     uint32_t flex6, uint32_t pkts_out, int flex7,
2635     uint32_t flex4, uint32_t flex1)
2636 {
2637 
2638 	if (tcp_bblogging_on(bbr->rc_tp)) {
2639 		union tcp_log_stackspecific log;
2640 
2641 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2642 		log.u_bbr.flex1 = flex1;
2643 		log.u_bbr.flex2 = flex2;
2644 		log.u_bbr.flex3 = flex3;
2645 		log.u_bbr.flex4 = flex4;
2646 		log.u_bbr.flex5 = flex5;
2647 		log.u_bbr.flex6 = flex6;
2648 		log.u_bbr.flex7 = flex7;
2649 		/* Hijack the pkts_out fids */
2650 		log.u_bbr.pkts_out = pkts_out;
2651 		log.u_bbr.flex8 = flex8;
2652 		if (bbr->rc_ack_was_delayed)
2653 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2654 		else
2655 			log.u_bbr.epoch = 0;
2656 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2657 		    &bbr->rc_inp->inp_socket->so_rcv,
2658 		    &bbr->rc_inp->inp_socket->so_snd,
2659 		    BBR_LOG_BBRUPD, 0,
2660 		    flex2, &log, false, &bbr->rc_tv);
2661 	}
2662 }
2663 
2664 static void
2665 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2666 	uint32_t newbw, uint32_t obw, uint32_t diff,
2667 	uint32_t tim)
2668 {
2669 	if (/*bbr_verbose_logging && */tcp_bblogging_on(bbr->rc_tp)) {
2670 		union tcp_log_stackspecific log;
2671 
2672 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2673 		log.u_bbr.flex1 = reason;
2674 		log.u_bbr.flex2 = newbw;
2675 		log.u_bbr.flex3 = obw;
2676 		log.u_bbr.flex4 = diff;
2677 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2678 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2679 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2680 		log.u_bbr.pkts_out = tim;
2681 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2682 		if (bbr->rc_lt_use_bw == 0)
2683 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2684 		else
2685 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2686 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2687 		    &bbr->rc_inp->inp_socket->so_rcv,
2688 		    &bbr->rc_inp->inp_socket->so_snd,
2689 		    BBR_LOG_BWSAMP, 0,
2690 		    0, &log, false, &bbr->rc_tv);
2691 	}
2692 }
2693 
2694 static inline void
2695 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2696 {
2697 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2698 		union tcp_log_stackspecific log;
2699 
2700 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2701 		log.u_bbr.flex1 = line;
2702 		log.u_bbr.flex2 = tick;
2703 		log.u_bbr.flex3 = tp->t_maxunacktime;
2704 		log.u_bbr.flex4 = tp->t_acktime;
2705 		log.u_bbr.flex8 = event;
2706 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2707 		    &bbr->rc_inp->inp_socket->so_rcv,
2708 		    &bbr->rc_inp->inp_socket->so_snd,
2709 		    BBR_LOG_PROGRESS, 0,
2710 		    0, &log, false, &bbr->rc_tv);
2711 	}
2712 }
2713 
2714 static void
2715 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2716 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2717 			 int error)
2718 {
2719 	if (tcp_bblogging_on(bbr->rc_tp)) {
2720 		union tcp_log_stackspecific log;
2721 
2722 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2723 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2724 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2725 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2726 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2727 		log.u_bbr.bw_inuse = rate;
2728 		log.u_bbr.flex5 = line;
2729 		log.u_bbr.flex6 = error;
2730 		log.u_bbr.flex8 = bbr->skip_gain;
2731 		log.u_bbr.flex8 <<= 1;
2732 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2733 		log.u_bbr.flex8 <<= 1;
2734 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2735 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2736 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2737 		    &bbr->rc_inp->inp_socket->so_rcv,
2738 		    &bbr->rc_inp->inp_socket->so_snd,
2739 		    BBR_LOG_HDWR_PACE, 0,
2740 		    0, &log, false, &bbr->rc_tv);
2741 	}
2742 }
2743 
2744 static void
2745 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)
2746 {
2747 	if (tcp_bblogging_on(bbr->rc_tp)) {
2748 		union tcp_log_stackspecific log;
2749 
2750 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2751 		log.u_bbr.flex1 = slot;
2752 		log.u_bbr.flex2 = del_by;
2753 		log.u_bbr.flex3 = prev_delay;
2754 		log.u_bbr.flex4 = line;
2755 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2756 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2757 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2758 		log.u_bbr.flex8 = bbr->rc_in_persist;
2759 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2760 		    &bbr->rc_inp->inp_socket->so_rcv,
2761 		    &bbr->rc_inp->inp_socket->so_snd,
2762 		    BBR_LOG_BBRSND, 0,
2763 		    len, &log, false, &bbr->rc_tv);
2764 	}
2765 }
2766 
2767 static void
2768 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)
2769 {
2770 	if (tcp_bblogging_on(bbr->rc_tp)) {
2771 		union tcp_log_stackspecific log;
2772 
2773 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2774 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2775 		log.u_bbr.flex2 = 0;
2776 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2777 		log.u_bbr.flex4 = end;
2778 		log.u_bbr.flex5 = seq;
2779 		log.u_bbr.flex6 = t;
2780 		log.u_bbr.flex7 = match;
2781 		log.u_bbr.flex8 = flags;
2782 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2783 		    &bbr->rc_inp->inp_socket->so_rcv,
2784 		    &bbr->rc_inp->inp_socket->so_snd,
2785 		    BBR_LOG_BBRRTT, 0,
2786 		    0, &log, false, &bbr->rc_tv);
2787 	}
2788 }
2789 
2790 static void
2791 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2792 {
2793 	if (tcp_bblogging_on(bbr->rc_tp)) {
2794 		union tcp_log_stackspecific log;
2795 
2796 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2797 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2798 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2799 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2800 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2801 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2802 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2803 		log.u_bbr.flex7 = 0;
2804 		log.u_bbr.flex8 = entry_method;
2805 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2806 		    &bbr->rc_inp->inp_socket->so_rcv,
2807 		    &bbr->rc_inp->inp_socket->so_snd,
2808 		    BBR_LOG_EXIT_GAIN, 0,
2809 		    0, &log, false, &bbr->rc_tv);
2810 	}
2811 }
2812 
2813 static void
2814 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2815 {
2816 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2817 		union tcp_log_stackspecific log;
2818 
2819 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2820 		/* R-HU */
2821 		log.u_bbr.flex1 = 0;
2822 		log.u_bbr.flex2 = 0;
2823 		log.u_bbr.flex3 = 0;
2824 		log.u_bbr.flex4 = 0;
2825 		log.u_bbr.flex7 = 0;
2826 		log.u_bbr.flex8 = settings_desired;
2827 
2828 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2829 		    &bbr->rc_inp->inp_socket->so_rcv,
2830 		    &bbr->rc_inp->inp_socket->so_snd,
2831 		    BBR_LOG_SETTINGS_CHG, 0,
2832 		    0, &log, false, &bbr->rc_tv);
2833 	}
2834 }
2835 
2836 /*
2837  * Returns the bw from the our filter.
2838  */
2839 static inline uint64_t
2840 bbr_get_full_bw(struct tcp_bbr *bbr)
2841 {
2842 	uint64_t bw;
2843 
2844 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2845 
2846 	return (bw);
2847 }
2848 
2849 static inline void
2850 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2851 {
2852 	uint64_t calclr;
2853 	uint32_t lost, del;
2854 
2855 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2856 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2857 	else
2858 		lost = 0;
2859 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2860 	if (lost == 0)  {
2861 		calclr = 0;
2862 	} else if (del) {
2863 		calclr = lost;
2864 		calclr *= (uint64_t)1000;
2865 		calclr /= (uint64_t)del;
2866 	} else {
2867 		/* Nothing delivered? 100.0% loss */
2868 		calclr = 1000;
2869 	}
2870 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2871 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2872 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2873 	bbr->r_ctl.rc_pkt_epoch++;
2874 	if (bbr->rc_no_pacing &&
2875 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2876 		bbr->rc_no_pacing = 0;
2877 		tcp_bbr_tso_size_check(bbr, cts);
2878 	}
2879 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2880 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2881 	/* What was our loss rate */
2882 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2883 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2884 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2885 }
2886 
2887 static inline void
2888 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2889 {
2890 	uint32_t epoch_time;
2891 
2892 	/* Tick the RTT clock */
2893 	bbr->r_ctl.rc_rtt_epoch++;
2894 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2895 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2896 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2897 }
2898 
2899 static inline void
2900 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2901 {
2902 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2903 		bbr->rc_is_pkt_epoch_now = 1;
2904 	}
2905 }
2906 
2907 /*
2908  * Returns the bw from either the b/w filter
2909  * or from the lt_bw (if the connection is being
2910  * policed).
2911  */
2912 static inline uint64_t
2913 __bbr_get_bw(struct tcp_bbr *bbr)
2914 {
2915 	uint64_t bw, min_bw;
2916 	uint64_t rtt;
2917 	int gm_measure_cnt = 1;
2918 
2919 	/*
2920 	 * For startup we make, like google, a
2921 	 * minimum b/w. This is generated from the
2922 	 * IW and the rttProp. We do fall back to srtt
2923 	 * if for some reason (initial handshake) we don't
2924 	 * have a rttProp. We, in the worst case, fall back
2925 	 * to the configured min_bw (rc_initial_hptsi_bw).
2926 	 */
2927 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2928 		/* Attempt first to use rttProp */
2929 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2930 		if (rtt && (rtt < 0xffffffff)) {
2931 measure:
2932 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2933 				((uint64_t)1000000);
2934 			min_bw /= rtt;
2935 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2936 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2937 			}
2938 
2939 		} else if (bbr->rc_tp->t_srtt != 0) {
2940 			/* No rttProp, use srtt? */
2941 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2942 			goto measure;
2943 		} else {
2944 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2945 		}
2946 	} else
2947 		min_bw = 0;
2948 
2949 	if ((bbr->rc_past_init_win == 0) &&
2950 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2951 		bbr->rc_past_init_win = 1;
2952 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2953 		gm_measure_cnt = 0;
2954 	if (gm_measure_cnt &&
2955 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2956 	     (bbr->rc_past_init_win == 0))) {
2957 		/* For google we use our guess rate until we get 1 measurement */
2958 
2959 use_initial_window:
2960 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2961 		if (rtt && (rtt < 0xffffffff)) {
2962 			/*
2963 			 * We have an RTT measurement. Use that in
2964 			 * combination with our initial window to calculate
2965 			 * a b/w.
2966 			 */
2967 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2968 				((uint64_t)1000000);
2969 			bw /= rtt;
2970 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2971 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2972 			}
2973 		} else {
2974 			/* Drop back to the 40 and punt to a default */
2975 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2976 		}
2977 		if (bw < 1)
2978 			/* Probably should panic */
2979 			bw = 1;
2980 		if (bw > min_bw)
2981 			return (bw);
2982 		else
2983 			return (min_bw);
2984 	}
2985 	if (bbr->rc_lt_use_bw)
2986 		bw = bbr->r_ctl.rc_lt_bw;
2987 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2988 		bw = bbr->r_ctl.red_bw;
2989 	else
2990 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2991 	if (bw == 0) {
2992 		/* We should not be at 0, go to the initial window then  */
2993 		goto use_initial_window;
2994 	}
2995 	if (bw < 1)
2996 		/* Probably should panic */
2997 		bw = 1;
2998 	if (bw < min_bw)
2999 		bw = min_bw;
3000 	return (bw);
3001 }
3002 
3003 static inline uint64_t
3004 bbr_get_bw(struct tcp_bbr *bbr)
3005 {
3006 	uint64_t bw;
3007 
3008 	bw = __bbr_get_bw(bbr);
3009 	return (bw);
3010 }
3011 
3012 static inline void
3013 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3014 {
3015 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3016 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3017 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3018 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3019 }
3020 
3021 static inline void
3022 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3023 {
3024 	bbr->rc_lt_is_sampling = 0;
3025 	bbr->rc_lt_use_bw = 0;
3026 	bbr->r_ctl.rc_lt_bw = 0;
3027 	bbr_reset_lt_bw_interval(bbr, cts);
3028 }
3029 
3030 static inline void
3031 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3032 {
3033 	uint64_t diff;
3034 
3035 	/* Do we have a previous sample? */
3036 	if (bbr->r_ctl.rc_lt_bw) {
3037 		/* Get the diff in bytes per second */
3038 		if (bbr->r_ctl.rc_lt_bw > bw)
3039 			diff = bbr->r_ctl.rc_lt_bw - bw;
3040 		else
3041 			diff = bw - bbr->r_ctl.rc_lt_bw;
3042 		if ((diff <= bbr_lt_bw_diff) ||
3043 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3044 			/* Consider us policed */
3045 			uint32_t saved_bw;
3046 
3047 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3048 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3049 			bbr->rc_lt_use_bw = 1;
3050 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3051 			/*
3052 			 * Use pkt based epoch for measuring length of
3053 			 * policer up
3054 			 */
3055 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3056 			/*
3057 			 * reason 4 is we need to start consider being
3058 			 * policed
3059 			 */
3060 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3061 			return;
3062 		}
3063 	}
3064 	bbr->r_ctl.rc_lt_bw = bw;
3065 	bbr_reset_lt_bw_interval(bbr, cts);
3066 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3067 }
3068 
3069 static void
3070 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3071 {
3072 	uint32_t ran, deduct;
3073 
3074 	ran = arc4random_uniform(bbr_rand_ot);
3075 	if (ran) {
3076 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3077 		bbr->r_ctl.rc_level_state_extra -= deduct;
3078 	}
3079 }
3080 /*
3081  * Return randomly the starting state
3082  * to use in probebw.
3083  */
3084 static uint8_t
3085 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3086 {
3087 	uint32_t ran;
3088 	uint8_t ret_val;
3089 
3090 	/* Initialize the offset to 0 */
3091 	bbr->r_ctl.rc_exta_time_gd = 0;
3092 	bbr->rc_hit_state_1 = 0;
3093 	bbr->r_ctl.rc_level_state_extra = 0;
3094 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3095 	/*
3096 	 * The math works funny here :) the return value is used to set the
3097 	 * substate and then the state change is called which increments by
3098 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3099 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3100 	 * we return 1 - 7, so we dont return 0 and end up starting in
3101 	 * state 1 (DRAIN).
3102 	 */
3103 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3104 	/* Set an epoch */
3105 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3106 		bbr_set_epoch(bbr, cts, __LINE__);
3107 
3108 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3109 	return (ret_val);
3110 }
3111 
3112 static void
3113 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3114 {
3115 	uint32_t diff, d_time;
3116 	uint64_t del_time, bw, lost, delivered;
3117 
3118 	if (bbr->r_use_policer == 0)
3119 		return;
3120 	if (bbr->rc_lt_use_bw) {
3121 		/* We are using lt bw do we stop yet? */
3122 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3123 		if (diff > bbr_lt_bw_max_rtts) {
3124 			/* Reset it all */
3125 reset_all:
3126 			bbr_reset_lt_bw_sampling(bbr, cts);
3127 			if (bbr->rc_filled_pipe) {
3128 				bbr_set_epoch(bbr, cts, __LINE__);
3129 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3130 				bbr_substate_change(bbr, cts, __LINE__, 0);
3131 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3132 				bbr_log_type_statechange(bbr, cts, __LINE__);
3133 			} else {
3134 				/*
3135 				 * This should not happen really
3136 				 * unless we remove the startup/drain
3137 				 * restrictions above.
3138 				 */
3139 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3140 				bbr_set_epoch(bbr, cts, __LINE__);
3141 				bbr->r_ctl.rc_bbr_state_time = cts;
3142 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3143 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3144 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3145 				bbr_set_state_target(bbr, __LINE__);
3146 				bbr_log_type_statechange(bbr, cts, __LINE__);
3147 			}
3148 			/* reason 0 is to stop using lt-bw */
3149 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3150 			return;
3151 		}
3152 		if (bbr_lt_intvl_fp == 0) {
3153 			/* Not doing false-positive detection */
3154 			return;
3155 		}
3156 		/* False positive detection */
3157 		if (diff == bbr_lt_intvl_fp) {
3158 			/* At bbr_lt_intvl_fp we record the lost */
3159 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3160 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3161 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3162 			/* Now is our loss rate still high? */
3163 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3164 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3165 			if ((delivered == 0) ||
3166 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3167 				/* No still below our threshold */
3168 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3169 			} else {
3170 				/* Yikes its still high, it must be a false positive */
3171 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3172 				goto reset_all;
3173 			}
3174 		}
3175 		return;
3176 	}
3177 	/*
3178 	 * Wait for the first loss before sampling, to let the policer
3179 	 * exhaust its tokens and estimate the steady-state rate allowed by
3180 	 * the policer. Starting samples earlier includes bursts that
3181 	 * over-estimate the bw.
3182 	 */
3183 	if (bbr->rc_lt_is_sampling == 0) {
3184 		/* reason 1 is to begin doing the sampling  */
3185 		if (loss_detected == 0)
3186 			return;
3187 		bbr_reset_lt_bw_interval(bbr, cts);
3188 		bbr->rc_lt_is_sampling = 1;
3189 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3190 		return;
3191 	}
3192 	/* Now how long were we delivering long term last> */
3193 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3194 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3195 	else
3196 		d_time = 0;
3197 
3198 	/* To avoid underestimates, reset sampling if we run out of data. */
3199 	if (bbr->r_ctl.r_app_limited_until) {
3200 		/* Can not measure in app-limited state */
3201 		bbr_reset_lt_bw_sampling(bbr, cts);
3202 		/* reason 2 is to reset sampling due to app limits  */
3203 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3204 		return;
3205 	}
3206 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3207 	if (diff < bbr_lt_intvl_min_rtts) {
3208 		/*
3209 		 * need more samples (we don't
3210 		 * start on a round like linux so
3211 		 * we need 1 more).
3212 		 */
3213 		/* 6 is not_enough time or no-loss */
3214 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3215 		return;
3216 	}
3217 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3218 		/*
3219 		 * For now if we wait too long, reset all sampling. We need
3220 		 * to do some research here, its possible that we should
3221 		 * base this on how much loss as occurred.. something like
3222 		 * if its under 10% (or some thresh) reset all otherwise
3223 		 * don't.  Thats for phase II I guess.
3224 		 */
3225 		bbr_reset_lt_bw_sampling(bbr, cts);
3226  		/* reason 3 is to reset sampling due too long of sampling */
3227 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3228 		return;
3229 	}
3230 	/*
3231 	 * End sampling interval when a packet is lost, so we estimate the
3232 	 * policer tokens were exhausted. Stopping the sampling before the
3233 	 * tokens are exhausted under-estimates the policed rate.
3234 	 */
3235 	if (loss_detected == 0) {
3236 		/* 6 is not_enough time or no-loss */
3237 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3238 		return;
3239 	}
3240 	/* Calculate packets lost and delivered in sampling interval. */
3241 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3242 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3243 	if ((delivered == 0) ||
3244 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3245 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3246 		return;
3247 	}
3248 	if (d_time < 1000) {
3249 		/* Not enough time. wait */
3250 		/* 6 is not_enough time or no-loss */
3251 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3252 		return;
3253 	}
3254 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3255 		/* Too long */
3256 		bbr_reset_lt_bw_sampling(bbr, cts);
3257  		/* reason 3 is to reset sampling due too long of sampling */
3258 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3259 		return;
3260 	}
3261 	del_time = d_time;
3262 	bw = delivered;
3263 	bw *= (uint64_t)USECS_IN_SECOND;
3264 	bw /= del_time;
3265 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3266 }
3267 
3268 /*
3269  * Allocate a sendmap from our zone.
3270  */
3271 static struct bbr_sendmap *
3272 bbr_alloc(struct tcp_bbr *bbr)
3273 {
3274 	struct bbr_sendmap *rsm;
3275 
3276 	BBR_STAT_INC(bbr_to_alloc);
3277 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3278 	if (rsm) {
3279 		bbr->r_ctl.rc_num_maps_alloced++;
3280 		return (rsm);
3281 	}
3282 	if (bbr->r_ctl.rc_free_cnt) {
3283 		BBR_STAT_INC(bbr_to_alloc_emerg);
3284 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3285 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3286 		bbr->r_ctl.rc_free_cnt--;
3287 		return (rsm);
3288 	}
3289 	BBR_STAT_INC(bbr_to_alloc_failed);
3290 	return (NULL);
3291 }
3292 
3293 static struct bbr_sendmap *
3294 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3295 {
3296 	if ((V_tcp_map_entries_limit > 0) &&
3297 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3298 		BBR_STAT_INC(bbr_alloc_limited);
3299 		if (!bbr->alloc_limit_reported) {
3300 			bbr->alloc_limit_reported = 1;
3301 			BBR_STAT_INC(bbr_alloc_limited_conns);
3302 		}
3303 		return (NULL);
3304 	}
3305 	return (bbr_alloc(bbr));
3306 }
3307 
3308 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3309 static struct bbr_sendmap *
3310 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3311 {
3312 	struct bbr_sendmap *rsm;
3313 
3314 	if (limit_type) {
3315 		/* currently there is only one limit type */
3316 		if (V_tcp_map_split_limit > 0 &&
3317 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3318 			BBR_STAT_INC(bbr_split_limited);
3319 			if (!bbr->alloc_limit_reported) {
3320 				bbr->alloc_limit_reported = 1;
3321 				BBR_STAT_INC(bbr_alloc_limited_conns);
3322 			}
3323 			return (NULL);
3324 		}
3325 	}
3326 
3327 	/* allocate and mark in the limit type, if set */
3328 	rsm = bbr_alloc(bbr);
3329 	if (rsm != NULL && limit_type) {
3330 		rsm->r_limit_type = limit_type;
3331 		bbr->r_ctl.rc_num_split_allocs++;
3332 	}
3333 	return (rsm);
3334 }
3335 
3336 static void
3337 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3338 {
3339 	if (rsm->r_limit_type) {
3340 		/* currently there is only one limit type */
3341 		bbr->r_ctl.rc_num_split_allocs--;
3342 	}
3343 	if (rsm->r_is_smallmap)
3344 		bbr->r_ctl.rc_num_small_maps_alloced--;
3345 	if (bbr->r_ctl.rc_tlp_send == rsm)
3346 		bbr->r_ctl.rc_tlp_send = NULL;
3347 	if (bbr->r_ctl.rc_resend == rsm) {
3348 		bbr->r_ctl.rc_resend = NULL;
3349 	}
3350 	if (bbr->r_ctl.rc_next == rsm)
3351 		bbr->r_ctl.rc_next = NULL;
3352 	if (bbr->r_ctl.rc_sacklast == rsm)
3353 		bbr->r_ctl.rc_sacklast = NULL;
3354 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3355 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3356 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3357 		rsm->r_limit_type = 0;
3358 		bbr->r_ctl.rc_free_cnt++;
3359 		return;
3360 	}
3361 	bbr->r_ctl.rc_num_maps_alloced--;
3362 	uma_zfree(bbr_zone, rsm);
3363 }
3364 
3365 /*
3366  * Returns the BDP.
3367  */
3368 static uint64_t
3369 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3370 	/*
3371 	 * Calculate the bytes in flight needed given the bw (in bytes per
3372 	 * second) and the specifyed rtt in useconds. We need to put out the
3373 	 * returned value per RTT to match that rate. Gain will normally
3374 	 * raise it up from there.
3375 	 *
3376 	 * This should not overflow as long as the bandwidth is below 1
3377 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3378 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3379 	 */
3380 	uint64_t usec_per_sec;
3381 
3382 	usec_per_sec = USECS_IN_SECOND;
3383 	return ((rtt * bw) / usec_per_sec);
3384 }
3385 
3386 /*
3387  * Return the initial cwnd.
3388  */
3389 static uint32_t
3390 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3391 {
3392 	uint32_t i_cwnd;
3393 
3394 	if (bbr->rc_init_win) {
3395 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3396 	} else if (V_tcp_initcwnd_segments)
3397 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3398 		    max(2 * tp->t_maxseg, 14600));
3399 	else if (V_tcp_do_rfc3390)
3400 		i_cwnd = min(4 * tp->t_maxseg,
3401 		    max(2 * tp->t_maxseg, 4380));
3402 	else {
3403 		/* Per RFC5681 Section 3.1 */
3404 		if (tp->t_maxseg > 2190)
3405 			i_cwnd = 2 * tp->t_maxseg;
3406 		else if (tp->t_maxseg > 1095)
3407 			i_cwnd = 3 * tp->t_maxseg;
3408 		else
3409 			i_cwnd = 4 * tp->t_maxseg;
3410 	}
3411 	return (i_cwnd);
3412 }
3413 
3414 /*
3415  * Given a specified gain, return the target
3416  * cwnd based on that gain.
3417  */
3418 static uint32_t
3419 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3420 {
3421 	uint64_t bdp, rtt;
3422 	uint32_t cwnd;
3423 
3424 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3425 	    (bbr_get_full_bw(bbr) == 0)) {
3426 		/* No measurements yet */
3427 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3428 	}
3429 	/*
3430 	 * Get bytes per RTT needed (rttProp is normally in
3431 	 * bbr_cwndtarget_rtt_touse)
3432 	 */
3433 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3434 	/* Get the bdp from the two values */
3435 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3436 	/* Now apply the gain */
3437 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3438 
3439 	return (cwnd);
3440 }
3441 
3442 static uint32_t
3443 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3444 {
3445 	uint32_t cwnd, mss;
3446 
3447 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3448 	/* Get the base cwnd with gain rounded to a mss */
3449 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3450 	/*
3451 	 * Add in N (2 default since we do not have a
3452 	 * fq layer to trap packets in) quanta's per the I-D
3453 	 * section 4.2.3.2 quanta adjust.
3454 	 */
3455 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3456 	if (bbr->rc_use_google) {
3457 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3458 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3459 			/*
3460 			 * The linux implementation adds
3461 			 * an extra 2 x mss in gain cycle which
3462 			 * is documented no-where except in the code.
3463 			 * so we add more for Neal undocumented feature
3464 			 */
3465 			cwnd += 2 * mss;
3466 		}
3467  		if ((cwnd / mss) & 0x1) {
3468 			/* Round up for odd num mss */
3469 			cwnd += mss;
3470 		}
3471 	}
3472 	/* Are we below the min cwnd? */
3473 	if (cwnd < get_min_cwnd(bbr))
3474 		return (get_min_cwnd(bbr));
3475 	return (cwnd);
3476 }
3477 
3478 static uint16_t
3479 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3480 {
3481 	if (gain < 1)
3482 		gain = 1;
3483 	return (gain);
3484 }
3485 
3486 static uint32_t
3487 bbr_get_header_oh(struct tcp_bbr *bbr)
3488 {
3489 	int seg_oh;
3490 
3491 	seg_oh = 0;
3492 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3493 		/* Do we include TCP overhead? */
3494 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3495 	}
3496 	if (bbr->r_ctl.rc_inc_ip_oh) {
3497 		/* Do we include IP overhead? */
3498 #ifdef INET6
3499 		if (bbr->r_is_v6) {
3500 			seg_oh += sizeof(struct ip6_hdr);
3501 		} else
3502 #endif
3503 		{
3504 
3505 #ifdef INET
3506 			seg_oh += sizeof(struct ip);
3507 #endif
3508 		}
3509 	}
3510 	if (bbr->r_ctl.rc_inc_enet_oh) {
3511 		/* Do we include the ethernet overhead?  */
3512 		seg_oh += sizeof(struct ether_header);
3513 	}
3514 	return(seg_oh);
3515 }
3516 
3517 static uint32_t
3518 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3519 {
3520 	uint64_t divor, res, tim;
3521 
3522 	if (useconds_time == 0)
3523 		return (0);
3524 	gain = bbr_gain_adjust(bbr, gain);
3525 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3526 	tim = useconds_time;
3527 	res = (tim * bw * gain) / divor;
3528 	if (res == 0)
3529 		res = 1;
3530 	return ((uint32_t)res);
3531 }
3532 
3533 /*
3534  * Given a gain and a length return the delay in useconds that
3535  * should be used to evenly space out packets
3536  * on the connection (based on the gain factor).
3537  */
3538 static uint32_t
3539 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3540 {
3541 	uint64_t bw, lentim, res;
3542 	uint32_t usecs, srtt, over = 0;
3543 	uint32_t seg_oh, num_segs, maxseg;
3544 
3545 	if (len == 0)
3546 		return (0);
3547 
3548 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3549 	num_segs = (len + maxseg - 1) / maxseg;
3550 	if (bbr->rc_use_google == 0) {
3551 		seg_oh = bbr_get_header_oh(bbr);
3552 		len += (num_segs * seg_oh);
3553 	}
3554 	gain = bbr_gain_adjust(bbr, gain);
3555 	bw = bbr_get_bw(bbr);
3556 	if (bbr->rc_use_google) {
3557 		uint64_t cbw;
3558 
3559 		/*
3560 		 * Reduce the b/w by the google discount
3561 		 * factor 10 = 1%.
3562 		 */
3563 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3564 		cbw /= (uint64_t)1000;
3565 		/* We don't apply a discount if it results in 0 */
3566 		if (cbw > 0)
3567 			bw = cbw;
3568 	}
3569 	lentim = ((uint64_t)len *
3570 		  (uint64_t)USECS_IN_SECOND *
3571 		  (uint64_t)BBR_UNIT);
3572 	res = lentim / ((uint64_t)gain * bw);
3573 	if (res == 0)
3574 		res = 1;
3575 	usecs = (uint32_t)res;
3576 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3577 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3578 	    (bbr->rc_use_google == 0) &&
3579 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3580 		/*
3581 		 * We cannot let the delay be more than 1/2 the srtt time.
3582 		 * Otherwise we cannot pace out or send properly.
3583 		 */
3584 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3585 		BBR_STAT_INC(bbr_hpts_min_time);
3586 	}
3587 	if (!nolog)
3588 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3589 	return (usecs);
3590 }
3591 
3592 static void
3593 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3594 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3595 {
3596 	uint64_t bw;
3597 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3598 	int32_t meth;
3599 
3600 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3601 
3602 #ifdef STATS
3603 	if ((tp->t_flags & TF_GPUTINPROG) &&
3604 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3605 		/*
3606 		 * Strech acks and compressed acks will cause this to
3607 		 * oscillate but we are doing it the same way as the main
3608 		 * stack so it will be compariable (though possibly not
3609 		 * ideal).
3610 		 */
3611 		int32_t cgput;
3612 		int64_t gput, time_stamp;
3613 
3614 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3615 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3616 		cgput = gput / time_stamp;
3617 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3618 					 cgput);
3619 		if (tp->t_stats_gput_prev > 0)
3620 			stats_voi_update_abs_s32(tp->t_stats,
3621 						 VOI_TCP_GPUT_ND,
3622 						 ((gput - tp->t_stats_gput_prev) * 100) /
3623 						 tp->t_stats_gput_prev);
3624 		tp->t_flags &= ~TF_GPUTINPROG;
3625 		tp->t_stats_gput_prev = cgput;
3626 	}
3627 #endif
3628 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3629 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3630 		/* We don't change anything in probe-rtt */
3631 		return;
3632 	}
3633 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3634 	saved_bytes = bytes_this_ack;
3635 	bytes_this_ack += sack_changed;
3636 	if (bytes_this_ack > prev_acked) {
3637 		bytes_this_ack -= prev_acked;
3638 		/*
3639 		 * A byte ack'd gives us a full mss
3640 		 * to be like linux i.e. they count packets.
3641 		 */
3642 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3643 			bytes_this_ack = maxseg;
3644 	} else {
3645 		/* Unlikely */
3646 		bytes_this_ack = 0;
3647 	}
3648 	cwnd = tp->snd_cwnd;
3649 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3650 	if (bw)
3651 		target_cwnd = bbr_get_target_cwnd(bbr,
3652 						  bw,
3653 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3654 	else
3655 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3656 	if (IN_RECOVERY(tp->t_flags) &&
3657 	    (bbr->bbr_prev_in_rec == 0)) {
3658 		/*
3659 		 * We are entering recovery and
3660 		 * thus packet conservation.
3661 		 */
3662 		bbr->pkt_conservation = 1;
3663 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3664 		cwnd = ctf_flight_size(tp,
3665 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3666 			bytes_this_ack;
3667 	}
3668 	if (IN_RECOVERY(tp->t_flags)) {
3669 		uint32_t flight;
3670 
3671 		bbr->bbr_prev_in_rec = 1;
3672 		if (cwnd > losses) {
3673 			cwnd -= losses;
3674 			if (cwnd < maxseg)
3675 				cwnd = maxseg;
3676 		} else
3677 			cwnd = maxseg;
3678 		flight = ctf_flight_size(tp,
3679 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3680 		bbr_log_type_cwndupd(bbr, flight, 0,
3681 				     losses, 10, 0, 0, line);
3682 		if (bbr->pkt_conservation) {
3683 			uint32_t time_in;
3684 
3685 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3686 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3687 			else
3688 				time_in = 0;
3689 
3690 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3691 				/* Clear packet conservation after an rttProp */
3692 				bbr->pkt_conservation = 0;
3693 			} else {
3694 				if ((flight + bytes_this_ack) > cwnd)
3695 					cwnd = flight + bytes_this_ack;
3696 				if (cwnd < get_min_cwnd(bbr))
3697 					cwnd = get_min_cwnd(bbr);
3698 				tp->snd_cwnd = cwnd;
3699 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3700 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3701 				return;
3702 			}
3703 		}
3704 	} else
3705 		bbr->bbr_prev_in_rec = 0;
3706 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3707 		bbr->r_ctl.restrict_growth--;
3708 		if (bytes_this_ack > maxseg)
3709 			bytes_this_ack = maxseg;
3710 	}
3711 	if (bbr->rc_filled_pipe) {
3712 		/*
3713 		 * Here we have exited startup and filled the pipe. We will
3714 		 * thus allow the cwnd to shrink to the target. We hit here
3715 		 * mostly.
3716 		 */
3717 		uint32_t s_cwnd;
3718 
3719 		meth = 2;
3720 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3721 		if (s_cwnd > cwnd)
3722 			cwnd = s_cwnd;
3723 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3724 			cwnd = s_cwnd;
3725 	} else {
3726 		/*
3727 		 * Here we are still in startup, we increase cwnd by what
3728 		 * has been acked.
3729 		 */
3730 		if ((cwnd < target_cwnd) ||
3731 		    (bbr->rc_past_init_win == 0)) {
3732 			meth = 3;
3733 			cwnd += bytes_this_ack;
3734 		} else {
3735 			/*
3736 			 * Method 4 means we are at target so no gain in
3737 			 * startup and past the initial window.
3738 			 */
3739 			meth = 4;
3740 		}
3741 	}
3742 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3743 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3744 }
3745 
3746 static void
3747 tcp_bbr_partialack(struct tcpcb *tp)
3748 {
3749 	struct tcp_bbr *bbr;
3750 
3751 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3752 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3753 	if (ctf_flight_size(tp,
3754 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3755 	    tp->snd_cwnd) {
3756 		bbr->r_wanted_output = 1;
3757 	}
3758 }
3759 
3760 static void
3761 bbr_post_recovery(struct tcpcb *tp)
3762 {
3763 	struct tcp_bbr *bbr;
3764 	uint32_t  flight;
3765 
3766 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3767 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3768 	/*
3769 	 * Here we just exit recovery.
3770 	 */
3771 	EXIT_RECOVERY(tp->t_flags);
3772 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3773 	bbr->r_recovery_bw = 0;
3774 	tp->snd_recover = tp->snd_una;
3775 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3776 	bbr->pkt_conservation = 0;
3777 	if (bbr->rc_use_google == 0) {
3778 		/*
3779 		 * For non-google mode lets
3780 		 * go ahead and make sure we clear
3781 		 * the recovery state so if we
3782 		 * bounce back in to recovery we
3783 		 * will do PC.
3784 		 */
3785 		bbr->bbr_prev_in_rec = 0;
3786 	}
3787 	bbr_log_type_exit_rec(bbr);
3788 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3789 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3790 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3791 	} else {
3792 		/* For probe-rtt case lets fix up its saved_cwnd */
3793 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3794 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3795 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3796 		}
3797 	}
3798 	flight = ctf_flight_size(tp,
3799 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3800 	if ((bbr->rc_use_google == 0) &&
3801 	    bbr_do_red) {
3802 		uint64_t val, lr2use;
3803 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3804 		uint32_t *cwnd_p;
3805 
3806 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3807 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3808 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3809 			ratio = (uint32_t)val;
3810 		} else
3811 			ratio = 1000;
3812 
3813 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3814 				     bbr->r_ctl.recovery_lr, 21,
3815 				     ratio,
3816 				     bbr->r_ctl.rc_red_cwnd_pe,
3817 				     __LINE__);
3818 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3819 			goto done;
3820 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3821 		     bbr_prtt_slam_cwnd) ||
3822 		    (bbr_sub_drain_slam_cwnd &&
3823 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3824 		     bbr->rc_hit_state_1 &&
3825 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3826 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3827 		     bbr_slam_cwnd_in_main_drain)) {
3828 			/*
3829 			 * Here we must poke at the saved cwnd
3830 			 * as well as the cwnd.
3831 			 */
3832 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3833 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3834 		} else {
3835  			cwnd = tp->snd_cwnd;
3836 			cwnd_p = &tp->snd_cwnd;
3837 		}
3838 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3839 		/* Add the overall lr with the recovery lr */
3840 		if (bbr->r_ctl.rc_lost == 0)
3841 			lr2use = 0;
3842 		else if (bbr->r_ctl.rc_delivered == 0)
3843 			lr2use = 1000;
3844 		else {
3845 			lr2use = bbr->r_ctl.rc_lost * 1000;
3846 			lr2use /= bbr->r_ctl.rc_delivered;
3847 		}
3848 		lr2use += bbr->r_ctl.recovery_lr;
3849 		acks_inflight = (flight / (maxseg * 2));
3850 		if (bbr_red_scale) {
3851 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3852 			lr2use /= bbr_red_scale;
3853 			if ((bbr_red_growth_restrict) &&
3854 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3855 			    bbr->r_ctl.restrict_growth += acks_inflight;
3856 		}
3857 		if (lr2use) {
3858 			val = (uint64_t)cwnd * lr2use;
3859 			val /= 1000;
3860 			if (cwnd > val)
3861 				newcwnd = roundup((cwnd - val), maxseg);
3862 			else
3863 				newcwnd = maxseg;
3864 		} else {
3865 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3866 			val /= (uint64_t)bbr_red_div;
3867 			newcwnd = roundup((uint32_t)val, maxseg);
3868 		}
3869 		/* with standard delayed acks how many acks can I expect? */
3870 		if (bbr_drop_limit == 0) {
3871 			/*
3872 			 * Anticpate how much we will
3873 			 * raise the cwnd based on the acks.
3874 			 */
3875 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3876 				/* We do enforce the min (with the acks) */
3877 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3878 			}
3879 		} else {
3880 			/*
3881 			 * A strict drop limit of N is inplace
3882 			 */
3883 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3884 				newcwnd = bbr_drop_limit * maxseg;
3885 			}
3886 		}
3887 		/* For the next N acks do we restrict the growth */
3888 		*cwnd_p = newcwnd;
3889 		if (tp->snd_cwnd > newcwnd)
3890 			tp->snd_cwnd = newcwnd;
3891 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3892 				     (uint32_t)lr2use,
3893 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3894 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3895 	}
3896 done:
3897 	bbr->r_ctl.recovery_lr = 0;
3898 	if (flight <= tp->snd_cwnd) {
3899 		bbr->r_wanted_output = 1;
3900 	}
3901 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3902 }
3903 
3904 static void
3905 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3906 {
3907 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3908 	/* Limit the drop in b/w to 1/2 our current filter. */
3909 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3910 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3911 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3912 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3913 	tcp_bbr_tso_size_check(bbr, cts);
3914 }
3915 
3916 static void
3917 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3918 {
3919 	struct tcp_bbr *bbr;
3920 
3921 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3922 #ifdef STATS
3923 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3924 #endif
3925 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3926 	switch (type) {
3927 	case CC_NDUPACK:
3928 		if (!IN_RECOVERY(tp->t_flags)) {
3929 			tp->snd_recover = tp->snd_max;
3930 			/* Start a new epoch */
3931 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3932 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3933 				/*
3934 				 * Move forward the lt epoch
3935 				 * so it won't count the truncated
3936 				 * epoch.
3937 				 */
3938 				bbr->r_ctl.rc_lt_epoch++;
3939 			}
3940 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3941 				/*
3942 				 * Just like the policer detection code
3943 				 * if we are in startup we must push
3944 				 * forward the last startup epoch
3945 				 * to hide the truncated PE.
3946 				 */
3947 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3948 			}
3949 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3950 			ENTER_RECOVERY(tp->t_flags);
3951 			bbr->rc_tlp_rtx_out = 0;
3952 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3953 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3954 			if (tcp_in_hpts(bbr->rc_tp) &&
3955 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3956 				/*
3957 				 * When we enter recovery, we need to restart
3958 				 * any timers. This may mean we gain an agg
3959 				 * early, which will be made up for at the last
3960 				 * rxt out.
3961 				 */
3962 				bbr->rc_timer_first = 1;
3963 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3964 			}
3965 			/*
3966 			 * Calculate a new cwnd based on to the current
3967 			 * delivery rate with no gain. We get the bdp
3968 			 * without gaining it up like we normally would and
3969 			 * we use the last cur_del_rate.
3970 			 */
3971 			if ((bbr->rc_use_google == 0) &&
3972 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3973 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3974 				tp->snd_cwnd = ctf_flight_size(tp,
3975 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3976 					(tp->t_maxseg - bbr->rc_last_options);
3977 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3978 					/* We always gate to min cwnd */
3979 					tp->snd_cwnd = get_min_cwnd(bbr);
3980 				}
3981 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3982 			}
3983 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3984 		}
3985 		break;
3986 	case CC_RTO_ERR:
3987 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
3988 		/* RTO was unnecessary, so reset everything. */
3989 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
3990 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3991 			tp->snd_cwnd = tp->snd_cwnd_prev;
3992 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
3993 			tp->snd_recover = tp->snd_recover_prev;
3994 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3995 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
3996 		}
3997 		tp->t_badrxtwin = 0;
3998 		break;
3999 	}
4000 }
4001 
4002 /*
4003  * Indicate whether this ack should be delayed.  We can delay the ack if
4004  * following conditions are met:
4005  *	- There is no delayed ack timer in progress.
4006  *	- Our last ack wasn't a 0-sized window. We never want to delay
4007  *	  the ack that opens up a 0-sized window.
4008  *	- LRO wasn't used for this segment. We make sure by checking that the
4009  *	  segment size is not larger than the MSS.
4010  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4011  *	  connection.
4012  *	- The data being acked is less than a full segment (a stretch ack
4013  *        of more than a segment we should ack.
4014  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4015  */
4016 #define DELAY_ACK(tp, bbr, nsegs)				\
4017 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4018 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4019 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4020 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4021 
4022 /*
4023  * Return the lowest RSM in the map of
4024  * packets still in flight that is not acked.
4025  * This should normally find on the first one
4026  * since we remove packets from the send
4027  * map after they are marked ACKED.
4028  */
4029 static struct bbr_sendmap *
4030 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4031 {
4032 	struct bbr_sendmap *rsm;
4033 
4034 	/*
4035 	 * Walk the time-order transmitted list looking for an rsm that is
4036 	 * not acked. This will be the one that was sent the longest time
4037 	 * ago that is still outstanding.
4038 	 */
4039 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4040 		if (rsm->r_flags & BBR_ACKED) {
4041 			continue;
4042 		}
4043 		goto finish;
4044 	}
4045 finish:
4046 	return (rsm);
4047 }
4048 
4049 static struct bbr_sendmap *
4050 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4051 {
4052 	struct bbr_sendmap *prsm;
4053 
4054 	/*
4055 	 * Walk the sequence order list backward until we hit and arrive at
4056 	 * the highest seq not acked. In theory when this is called it
4057 	 * should be the last segment (which it was not).
4058 	 */
4059 	prsm = rsm;
4060 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4061 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4062 			continue;
4063 		}
4064 		return (prsm);
4065 	}
4066 	return (NULL);
4067 }
4068 
4069 /*
4070  * Returns to the caller the number of microseconds that
4071  * the packet can be outstanding before we think we
4072  * should have had an ack returned.
4073  */
4074 static uint32_t
4075 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4076 {
4077 	/*
4078 	 * lro is the flag we use to determine if we have seen reordering.
4079 	 * If it gets set we have seen reordering. The reorder logic either
4080 	 * works in one of two ways:
4081 	 *
4082 	 * If reorder-fade is configured, then we track the last time we saw
4083 	 * re-ordering occur. If we reach the point where enough time as
4084 	 * passed we no longer consider reordering has occuring.
4085 	 *
4086 	 * Or if reorder-face is 0, then once we see reordering we consider
4087 	 * the connection to alway be subject to reordering and just set lro
4088 	 * to 1.
4089 	 *
4090 	 * In the end if lro is non-zero we add the extra time for
4091 	 * reordering in.
4092 	 */
4093 	int32_t lro;
4094 	uint32_t thresh, t_rxtcur;
4095 
4096 	if (srtt == 0)
4097 		srtt = 1;
4098 	if (bbr->r_ctl.rc_reorder_ts) {
4099 		if (bbr->r_ctl.rc_reorder_fade) {
4100 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4101 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4102 				if (lro == 0) {
4103 					/*
4104 					 * No time as passed since the last
4105 					 * reorder, mark it as reordering.
4106 					 */
4107 					lro = 1;
4108 				}
4109 			} else {
4110 				/* Negative time? */
4111 				lro = 0;
4112 			}
4113 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4114 				/* Turn off reordering seen too */
4115 				bbr->r_ctl.rc_reorder_ts = 0;
4116 				lro = 0;
4117 			}
4118 		} else {
4119 			/* Reodering does not fade */
4120 			lro = 1;
4121 		}
4122 	} else {
4123 		lro = 0;
4124 	}
4125 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4126 	if (lro) {
4127 		/* It must be set, if not you get 1/4 rtt */
4128 		if (bbr->r_ctl.rc_reorder_shift)
4129 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4130 		else
4131 			thresh += (srtt >> 2);
4132 	} else {
4133 		thresh += 1000;
4134 	}
4135 	/* We don't let the rack timeout be above a RTO */
4136 	if ((bbr->rc_tp)->t_srtt == 0)
4137 		t_rxtcur = BBR_INITIAL_RTO;
4138 	else
4139 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4140 	if (thresh > t_rxtcur) {
4141 		thresh = t_rxtcur;
4142 	}
4143 	/* And we don't want it above the RTO max either */
4144 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4145 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4146 	}
4147 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4148 	return (thresh);
4149 }
4150 
4151 /*
4152  * Return to the caller the amount of time in mico-seconds
4153  * that should be used for the TLP timer from the last
4154  * send time of this packet.
4155  */
4156 static uint32_t
4157 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4158     struct bbr_sendmap *rsm, uint32_t srtt,
4159     uint32_t cts)
4160 {
4161 	uint32_t thresh, len, maxseg, t_rxtcur;
4162 	struct bbr_sendmap *prsm;
4163 
4164 	if (srtt == 0)
4165 		srtt = 1;
4166 	if (bbr->rc_tlp_threshold)
4167 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4168 	else
4169 		thresh = (srtt * 2);
4170 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4171 	/* Get the previous sent packet, if any  */
4172 	len = rsm->r_end - rsm->r_start;
4173 
4174 	/* 2.1 behavior */
4175 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4176 	if (prsm && (len <= maxseg)) {
4177 		/*
4178 		 * Two packets outstanding, thresh should be (2*srtt) +
4179 		 * possible inter-packet delay (if any).
4180 		 */
4181 		uint32_t inter_gap = 0;
4182 		int idx, nidx;
4183 
4184 		idx = rsm->r_rtr_cnt - 1;
4185 		nidx = prsm->r_rtr_cnt - 1;
4186 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4187 			/* Yes it was sent later (or at the same time) */
4188 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4189 		}
4190 		thresh += inter_gap;
4191 	} else if (len <= maxseg) {
4192 		/*
4193 		 * Possibly compensate for delayed-ack.
4194 		 */
4195 		uint32_t alt_thresh;
4196 
4197 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4198 		if (alt_thresh > thresh)
4199 			thresh = alt_thresh;
4200 	}
4201 	/* Not above the current  RTO */
4202 	if (tp->t_srtt == 0)
4203 		t_rxtcur = BBR_INITIAL_RTO;
4204 	else
4205 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4206 
4207 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4208 	/* Not above an RTO */
4209 	if (thresh > t_rxtcur) {
4210 		thresh = t_rxtcur;
4211 	}
4212 	/* Not above a RTO max */
4213 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4214 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4215 	}
4216 	/* And now apply the user TLP min */
4217 	if (thresh < bbr_tlp_min) {
4218 		thresh = bbr_tlp_min;
4219 	}
4220 	return (thresh);
4221 }
4222 
4223 /*
4224  * Return one of three RTTs to use (in microseconds).
4225  */
4226 static __inline uint32_t
4227 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4228 {
4229 	uint32_t f_rtt;
4230 	uint32_t srtt;
4231 
4232 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4233 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4234 		/* We have no rtt at all */
4235 		if (bbr->rc_tp->t_srtt == 0)
4236 			f_rtt = BBR_INITIAL_RTO;
4237 		else
4238 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4239 		/*
4240 		 * Since we don't know how good the rtt is apply a
4241 		 * delayed-ack min
4242 		 */
4243 		if (f_rtt < bbr_delayed_ack_time) {
4244 			f_rtt = bbr_delayed_ack_time;
4245 		}
4246 	}
4247 	/* Take the filter version or last measured pkt-rtt */
4248 	if (rtt_type == BBR_RTT_PROP) {
4249 		srtt = f_rtt;
4250 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4251 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4252 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4253 		} else {
4254 			/* No pkt rtt yet */
4255 			srtt = f_rtt;
4256 		}
4257 	} else if (rtt_type == BBR_RTT_RACK) {
4258 		srtt = bbr->r_ctl.rc_last_rtt;
4259 		/* We need to add in any internal delay for our timer */
4260 		if (bbr->rc_ack_was_delayed)
4261 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4262 	} else if (rtt_type == BBR_SRTT) {
4263 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4264 	} else {
4265 		/* TSNH */
4266 		srtt = f_rtt;
4267 #ifdef BBR_INVARIANTS
4268 		panic("Unknown rtt request type %d", rtt_type);
4269 #endif
4270 	}
4271 	return (srtt);
4272 }
4273 
4274 static int
4275 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4276 {
4277 	uint32_t thresh;
4278 
4279 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4280 				      cts, rsm);
4281 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4282 		/* It is lost (past time) */
4283 		return (1);
4284 	}
4285 	return (0);
4286 }
4287 
4288 /*
4289  * Return a sendmap if we need to retransmit something.
4290  */
4291 static struct bbr_sendmap *
4292 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4293 {
4294 	/*
4295 	 * Check to see that we don't need to fall into recovery. We will
4296 	 * need to do so if our oldest transmit is past the time we should
4297 	 * have had an ack.
4298 	 */
4299 
4300 	struct bbr_sendmap *rsm;
4301 	int32_t idx;
4302 
4303 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4304 		/* Nothing outstanding that we know of */
4305 		return (NULL);
4306 	}
4307 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4308 	if (rsm == NULL) {
4309 		/* Nothing in the transmit map */
4310 		return (NULL);
4311 	}
4312 	if (tp->t_flags & TF_SENTFIN) {
4313 		/* Fin restricted, don't find anything once a fin is sent */
4314 		return (NULL);
4315 	}
4316 	if (rsm->r_flags & BBR_ACKED) {
4317 		/*
4318 		 * Ok the first one is acked (this really should not happen
4319 		 * since we remove the from the tmap once they are acked)
4320 		 */
4321 		rsm = bbr_find_lowest_rsm(bbr);
4322 		if (rsm == NULL)
4323 			return (NULL);
4324 	}
4325 	idx = rsm->r_rtr_cnt - 1;
4326 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4327 		/* Send timestamp is the same or less? can't be ready */
4328 		return (NULL);
4329 	}
4330 	/* Get our RTT time */
4331 	if (bbr_is_lost(bbr, rsm, cts) &&
4332 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4333 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4334 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4335 			rsm->r_flags |= BBR_MARKED_LOST;
4336 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4337 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4338 		}
4339 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4340 #ifdef BBR_INVARIANTS
4341 		if ((rsm->r_end - rsm->r_start) == 0)
4342 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4343 #endif
4344 		return (rsm);
4345 	}
4346 	return (NULL);
4347 }
4348 
4349 /*
4350  * RACK Timer, here we simply do logging and house keeping.
4351  * the normal bbr_output_wtime() function will call the
4352  * appropriate thing to check if we need to do a RACK retransmit.
4353  * We return 1, saying don't proceed with bbr_output_wtime only
4354  * when all timers have been stopped (destroyed PCB?).
4355  */
4356 static int
4357 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4358 {
4359 	/*
4360 	 * This timer simply provides an internal trigger to send out data.
4361 	 * The check_recovery_mode call will see if there are needed
4362 	 * retransmissions, if so we will enter fast-recovery. The output
4363 	 * call may or may not do the same thing depending on sysctl
4364 	 * settings.
4365 	 */
4366 	uint32_t lost;
4367 
4368 	if (bbr->rc_all_timers_stopped) {
4369 		return (1);
4370 	}
4371 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4372 		/* Its not time yet */
4373 		return (0);
4374 	}
4375 	BBR_STAT_INC(bbr_to_tot);
4376 	lost = bbr->r_ctl.rc_lost;
4377 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4378 		bbr_set_state(tp, bbr, 0);
4379 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4380 	if (bbr->r_ctl.rc_resend == NULL) {
4381 		/* Lets do the check here */
4382 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4383 	}
4384 	if (bbr_policer_call_from_rack_to)
4385 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4386 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4387 	return (0);
4388 }
4389 
4390 static __inline void
4391 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4392 {
4393 	int idx;
4394 
4395 	nrsm->r_start = start;
4396 	nrsm->r_end = rsm->r_end;
4397 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4398 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4399 	nrsm->r_flags = rsm->r_flags;
4400 	/* We don't transfer forward the SYN flag */
4401 	nrsm->r_flags &= ~BBR_HAS_SYN;
4402 	/* We move forward the FIN flag, not that this should happen */
4403 	rsm->r_flags &= ~BBR_HAS_FIN;
4404 	nrsm->r_dupack = rsm->r_dupack;
4405 	nrsm->r_rtr_bytes = 0;
4406 	nrsm->r_is_gain = rsm->r_is_gain;
4407 	nrsm->r_is_drain = rsm->r_is_drain;
4408 	nrsm->r_delivered = rsm->r_delivered;
4409 	nrsm->r_ts_valid = rsm->r_ts_valid;
4410 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4411 	nrsm->r_del_time = rsm->r_del_time;
4412 	nrsm->r_app_limited = rsm->r_app_limited;
4413 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4414 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4415 	/* We split a piece the lower section looses any just_ret flag. */
4416 	nrsm->r_bbr_state = rsm->r_bbr_state;
4417 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4418 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4419 	}
4420 	rsm->r_end = nrsm->r_start;
4421 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4422 	idx /= 8;
4423 	/* Check if we got too small */
4424 	if ((rsm->r_is_smallmap == 0) &&
4425 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4426 		bbr->r_ctl.rc_num_small_maps_alloced++;
4427 		rsm->r_is_smallmap = 1;
4428 	}
4429 	/* Check the new one as well */
4430 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4431 		bbr->r_ctl.rc_num_small_maps_alloced++;
4432 		nrsm->r_is_smallmap = 1;
4433 	}
4434 }
4435 
4436 static int
4437 bbr_sack_mergable(struct bbr_sendmap *at,
4438 		  uint32_t start, uint32_t end)
4439 {
4440 	/*
4441 	 * Given a sack block defined by
4442 	 * start and end, and a current position
4443 	 * at. Return 1 if either side of at
4444 	 * would show that the block is mergable
4445 	 * to that side. A block to be mergable
4446 	 * must have overlap with the start/end
4447 	 * and be in the SACK'd state.
4448 	 */
4449 	struct bbr_sendmap *l_rsm;
4450 	struct bbr_sendmap *r_rsm;
4451 
4452 	/* first get the either side blocks */
4453 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4454 	r_rsm = TAILQ_NEXT(at, r_next);
4455 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4456 		/* Potentially mergeable */
4457 		if ((l_rsm->r_end == start) ||
4458 		    (SEQ_LT(start, l_rsm->r_end) &&
4459 		     SEQ_GT(end, l_rsm->r_end))) {
4460 			    /*
4461 			     * map blk   |------|
4462 			     * sack blk         |------|
4463 			     * <or>
4464 			     * map blk   |------|
4465 			     * sack blk      |------|
4466 			     */
4467 			    return (1);
4468 		    }
4469 	}
4470 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4471 		/* Potentially mergeable */
4472 		if ((r_rsm->r_start == end) ||
4473 		    (SEQ_LT(start, r_rsm->r_start) &&
4474 		     SEQ_GT(end, r_rsm->r_start))) {
4475 			/*
4476 			 * map blk          |---------|
4477 			 * sack blk    |----|
4478 			 * <or>
4479 			 * map blk          |---------|
4480 			 * sack blk    |-------|
4481 			 */
4482 			return (1);
4483 		}
4484 	}
4485 	return (0);
4486 }
4487 
4488 static struct bbr_sendmap *
4489 bbr_merge_rsm(struct tcp_bbr *bbr,
4490 	      struct bbr_sendmap *l_rsm,
4491 	      struct bbr_sendmap *r_rsm)
4492 {
4493 	/*
4494 	 * We are merging two ack'd RSM's,
4495 	 * the l_rsm is on the left (lower seq
4496 	 * values) and the r_rsm is on the right
4497 	 * (higher seq value). The simplest way
4498 	 * to merge these is to move the right
4499 	 * one into the left. I don't think there
4500 	 * is any reason we need to try to find
4501 	 * the oldest (or last oldest retransmitted).
4502 	 */
4503 	l_rsm->r_end = r_rsm->r_end;
4504 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4505 		l_rsm->r_dupack = r_rsm->r_dupack;
4506 	if (r_rsm->r_rtr_bytes)
4507 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4508 	if (r_rsm->r_in_tmap) {
4509 		/* This really should not happen */
4510 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4511 	}
4512 	if (r_rsm->r_app_limited)
4513 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4514 	/* Now the flags */
4515 	if (r_rsm->r_flags & BBR_HAS_FIN)
4516 		l_rsm->r_flags |= BBR_HAS_FIN;
4517 	if (r_rsm->r_flags & BBR_TLP)
4518 		l_rsm->r_flags |= BBR_TLP;
4519 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4520 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4521 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4522 		/* This really should not happen */
4523 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4524 	}
4525 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4526 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4527 		/* Transfer the split limit to the map we free */
4528 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4529 		l_rsm->r_limit_type = 0;
4530 	}
4531 	bbr_free(bbr, r_rsm);
4532 	return(l_rsm);
4533 }
4534 
4535 /*
4536  * TLP Timer, here we simply setup what segment we want to
4537  * have the TLP expire on, the normal bbr_output_wtime() will then
4538  * send it out.
4539  *
4540  * We return 1, saying don't proceed with bbr_output_wtime only
4541  * when all timers have been stopped (destroyed PCB?).
4542  */
4543 static int
4544 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4545 {
4546 	/*
4547 	 * Tail Loss Probe.
4548 	 */
4549 	struct bbr_sendmap *rsm = NULL;
4550 	struct socket *so;
4551 	uint32_t amm;
4552 	uint32_t out, avail;
4553 	uint32_t maxseg;
4554 	int collapsed_win = 0;
4555 
4556 	if (bbr->rc_all_timers_stopped) {
4557 		return (1);
4558 	}
4559 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4560 		/* Its not time yet */
4561 		return (0);
4562 	}
4563 	if (ctf_progress_timeout_check(tp, true)) {
4564 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4565 		return (-ETIMEDOUT);	/* tcp_drop() */
4566 	}
4567 	/* Did we somehow get into persists? */
4568 	if (bbr->rc_in_persist) {
4569 		return (0);
4570 	}
4571 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4572 		bbr_set_state(tp, bbr, 0);
4573 	BBR_STAT_INC(bbr_tlp_tot);
4574 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4575 	/*
4576 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4577 	 * need to figure out how to force a full MSS segment out.
4578 	 */
4579 	so = tptosocket(tp);
4580 	avail = sbavail(&so->so_snd);
4581 	out = ctf_outstanding(tp);
4582 	if (out > tp->snd_wnd) {
4583 		/* special case, we need a retransmission */
4584 		collapsed_win = 1;
4585 		goto need_retran;
4586 	}
4587 	if (avail > out) {
4588 		/* New data is available */
4589 		amm = avail - out;
4590 		if (amm > maxseg) {
4591 			amm = maxseg;
4592 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4593 			/* not enough to fill a MTU and no-delay is off */
4594 			goto need_retran;
4595 		}
4596 		/* Set the send-new override */
4597 		if ((out + amm) <= tp->snd_wnd) {
4598 			bbr->rc_tlp_new_data = 1;
4599 		} else {
4600 			goto need_retran;
4601 		}
4602 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4603 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4604 		bbr->r_ctl.rc_tlp_send = NULL;
4605 		/* cap any slots */
4606 		BBR_STAT_INC(bbr_tlp_newdata);
4607 		goto send;
4608 	}
4609 need_retran:
4610 	/*
4611 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4612 	 * optionally the first un-acked segment.
4613 	 */
4614 	if (collapsed_win == 0) {
4615 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4616 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4617 			rsm = bbr_find_high_nonack(bbr, rsm);
4618 		}
4619 		if (rsm == NULL) {
4620 			goto restore;
4621 		}
4622 	} else {
4623 		/*
4624 		 * We must find the last segment
4625 		 * that was acceptable by the client.
4626 		 */
4627 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4628 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4629 				/* Found one */
4630 				break;
4631 			}
4632 		}
4633 		if (rsm == NULL) {
4634 			/* None? if so send the first */
4635 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4636 			if (rsm == NULL)
4637 				goto restore;
4638 		}
4639 	}
4640 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4641 		/*
4642 		 * We need to split this the last segment in two.
4643 		 */
4644 		struct bbr_sendmap *nrsm;
4645 
4646 		nrsm = bbr_alloc_full_limit(bbr);
4647 		if (nrsm == NULL) {
4648 			/*
4649 			 * We can't get memory to split, we can either just
4650 			 * not split it. Or retransmit the whole piece, lets
4651 			 * do the large send (BTLP :-) ).
4652 			 */
4653 			goto go_for_it;
4654 		}
4655 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4656 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4657 		if (rsm->r_in_tmap) {
4658 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4659 			nrsm->r_in_tmap = 1;
4660 		}
4661 		rsm->r_flags &= (~BBR_HAS_FIN);
4662 		rsm = nrsm;
4663 	}
4664 go_for_it:
4665 	bbr->r_ctl.rc_tlp_send = rsm;
4666 	bbr->rc_tlp_rtx_out = 1;
4667 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4668 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4669 		tp->t_rxtshift++;
4670 	} else {
4671 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4672 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4673 	}
4674 send:
4675 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4676 		/*
4677 		 * Can't [re]/transmit a segment we have retransmitted the
4678 		 * max times. We need the retransmit timer to take over.
4679 		 */
4680 restore:
4681 		bbr->rc_tlp_new_data = 0;
4682 		bbr->r_ctl.rc_tlp_send = NULL;
4683 		if (rsm)
4684 			rsm->r_flags &= ~BBR_TLP;
4685 		BBR_STAT_INC(bbr_tlp_retran_fail);
4686 		return (0);
4687 	} else if (rsm) {
4688 		rsm->r_flags |= BBR_TLP;
4689 	}
4690 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4691 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4692 		/*
4693 		 * We have retransmitted to many times for TLP. Switch to
4694 		 * the regular RTO timer
4695 		 */
4696 		goto restore;
4697 	}
4698 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4699 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4700 	return (0);
4701 }
4702 
4703 /*
4704  * Delayed ack Timer, here we simply need to setup the
4705  * ACK_NOW flag and remove the DELACK flag. From there
4706  * the output routine will send the ack out.
4707  *
4708  * We only return 1, saying don't proceed, if all timers
4709  * are stopped (destroyed PCB?).
4710  */
4711 static int
4712 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4713 {
4714 	if (bbr->rc_all_timers_stopped) {
4715 		return (1);
4716 	}
4717 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4718 	tp->t_flags &= ~TF_DELACK;
4719 	tp->t_flags |= TF_ACKNOW;
4720 	KMOD_TCPSTAT_INC(tcps_delack);
4721 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4722 	return (0);
4723 }
4724 
4725 /*
4726  * Here we send a KEEP-ALIVE like probe to the
4727  * peer, we do not send data.
4728  *
4729  * We only return 1, saying don't proceed, if all timers
4730  * are stopped (destroyed PCB?).
4731  */
4732 static int
4733 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4734 {
4735 	struct tcptemp *t_template;
4736 	int32_t retval = 1;
4737 
4738 	if (bbr->rc_all_timers_stopped) {
4739 		return (1);
4740 	}
4741 	if (bbr->rc_in_persist == 0)
4742 		return (0);
4743 
4744 	/*
4745 	 * Persistence timer into zero window. Force a byte to be output, if
4746 	 * possible.
4747 	 */
4748 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4749 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4750 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4751 	/*
4752 	 * Have we exceeded the user specified progress time?
4753 	 */
4754 	if (ctf_progress_timeout_check(tp, true)) {
4755 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4756 		return (-ETIMEDOUT);	/* tcp_drop() */
4757 	}
4758 	/*
4759 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4760 	 * window is closed.  After a full backoff, drop the connection if
4761 	 * the idle time (no responses to probes) reaches the maximum
4762 	 * backoff that we would use if retransmitting.
4763 	 */
4764 	if (tp->t_rxtshift >= V_tcp_retries &&
4765 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4766 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4767 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4768 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4769 		return (-ETIMEDOUT);	/* tcp_drop() */
4770 	}
4771 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4772 	    tp->snd_una == tp->snd_max) {
4773 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4774 		retval = 0;
4775 		goto out;
4776 	}
4777 	/*
4778 	 * If the user has closed the socket then drop a persisting
4779 	 * connection after a much reduced timeout.
4780 	 */
4781 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4782 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4783 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4784 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4785 		return (-ETIMEDOUT);	/* tcp_drop() */
4786 	}
4787 	t_template = tcpip_maketemplate(bbr->rc_inp);
4788 	if (t_template) {
4789 		tcp_respond(tp, t_template->tt_ipgen,
4790 			    &t_template->tt_t, (struct mbuf *)NULL,
4791 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4792 		/* This sends an ack */
4793 		if (tp->t_flags & TF_DELACK)
4794 			tp->t_flags &= ~TF_DELACK;
4795 		free(t_template, M_TEMP);
4796 	}
4797 	if (tp->t_rxtshift < V_tcp_retries)
4798 		tp->t_rxtshift++;
4799 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4800 out:
4801 	return (retval);
4802 }
4803 
4804 /*
4805  * If a keepalive goes off, we had no other timers
4806  * happening. We always return 1 here since this
4807  * routine either drops the connection or sends
4808  * out a segment with respond.
4809  */
4810 static int
4811 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4812 {
4813 	struct tcptemp *t_template;
4814 	struct inpcb *inp = tptoinpcb(tp);
4815 
4816 	if (bbr->rc_all_timers_stopped) {
4817 		return (1);
4818 	}
4819 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4820 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4821 	/*
4822 	 * Keep-alive timer went off; send something or drop connection if
4823 	 * idle for too long.
4824 	 */
4825 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4826 	if (tp->t_state < TCPS_ESTABLISHED)
4827 		goto dropit;
4828 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4829 	    tp->t_state <= TCPS_CLOSING) {
4830 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4831 			goto dropit;
4832 		/*
4833 		 * Send a packet designed to force a response if the peer is
4834 		 * up and reachable: either an ACK if the connection is
4835 		 * still alive, or an RST if the peer has closed the
4836 		 * connection due to timeout or reboot. Using sequence
4837 		 * number tp->snd_una-1 causes the transmitted zero-length
4838 		 * segment to lie outside the receive window; by the
4839 		 * protocol spec, this requires the correspondent TCP to
4840 		 * respond.
4841 		 */
4842 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4843 		t_template = tcpip_maketemplate(inp);
4844 		if (t_template) {
4845 			tcp_respond(tp, t_template->tt_ipgen,
4846 			    &t_template->tt_t, (struct mbuf *)NULL,
4847 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4848 			free(t_template, M_TEMP);
4849 		}
4850 	}
4851 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4852 	return (1);
4853 dropit:
4854 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4855 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4856 	return (-ETIMEDOUT);	/* tcp_drop() */
4857 }
4858 
4859 /*
4860  * Retransmit helper function, clear up all the ack
4861  * flags and take care of important book keeping.
4862  */
4863 static void
4864 bbr_remxt_tmr(struct tcpcb *tp)
4865 {
4866 	/*
4867 	 * The retransmit timer went off, all sack'd blocks must be
4868 	 * un-acked.
4869 	 */
4870 	struct bbr_sendmap *rsm, *trsm = NULL;
4871 	struct tcp_bbr *bbr;
4872 	uint32_t cts, lost;
4873 
4874 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4875 	cts = tcp_get_usecs(&bbr->rc_tv);
4876 	lost = bbr->r_ctl.rc_lost;
4877 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4878 		bbr_set_state(tp, bbr, 0);
4879 
4880 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4881 		if (rsm->r_flags & BBR_ACKED) {
4882 			uint32_t old_flags;
4883 
4884 			rsm->r_dupack = 0;
4885 			if (rsm->r_in_tmap == 0) {
4886 				/* We must re-add it back to the tlist */
4887 				if (trsm == NULL) {
4888 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4889 				} else {
4890 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4891 				}
4892 				rsm->r_in_tmap = 1;
4893 			}
4894 			old_flags = rsm->r_flags;
4895 			rsm->r_flags |= BBR_RXT_CLEARED;
4896 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4897 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4898 		} else {
4899 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4900 			    (rsm->r_start == tp->snd_una)) {
4901 				/*
4902 				 * Special case for TCP FO. Where
4903 				 * we sent more data beyond the snd_max.
4904 				 * We don't mark that as lost and stop here.
4905 				 */
4906 				break;
4907 			}
4908 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4909 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4910 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4911 			}
4912 			if (bbr_marks_rxt_sack_passed) {
4913 				/*
4914 				 * With this option, we will rack out
4915 				 * in 1ms increments the rest of the packets.
4916 				 */
4917 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4918 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4919 			} else {
4920 				/*
4921 				 * With this option we only mark them lost
4922 				 * and remove all sack'd markings. We will run
4923 				 * another RXT or a TLP. This will cause
4924 				 * us to eventually send more based on what
4925 				 * ack's come in.
4926 				 */
4927 				rsm->r_flags |= BBR_MARKED_LOST;
4928 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4929 				rsm->r_flags &= ~BBR_SACK_PASSED;
4930 			}
4931 		}
4932 		trsm = rsm;
4933 	}
4934 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4935 	/* Clear the count (we just un-acked them) */
4936 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4937 	bbr->rc_tlp_new_data = 0;
4938 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4939 	/* zap the behindness on a rxt */
4940 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4941 	bbr->r_agg_early_set = 0;
4942 	bbr->r_ctl.rc_agg_early = 0;
4943 	bbr->rc_tlp_rtx_out = 0;
4944 	bbr->r_ctl.rc_sacked = 0;
4945 	bbr->r_ctl.rc_sacklast = NULL;
4946 	bbr->r_timer_override = 1;
4947 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4948 }
4949 
4950 /*
4951  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4952  * we will setup to retransmit the lowest seq number outstanding.
4953  */
4954 static int
4955 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4956 {
4957 	struct inpcb *inp = tptoinpcb(tp);
4958 	int32_t rexmt;
4959 	int32_t retval = 0;
4960 	bool isipv6;
4961 
4962 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4963 	if (bbr->rc_all_timers_stopped) {
4964 		return (1);
4965 	}
4966 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4967 	    (tp->snd_una == tp->snd_max)) {
4968 		/* Nothing outstanding .. nothing to do */
4969 		return (0);
4970 	}
4971 	/*
4972 	 * Retransmission timer went off.  Message has not been acked within
4973 	 * retransmit interval.  Back off to a longer retransmit interval
4974 	 * and retransmit one segment.
4975 	 */
4976 	if (ctf_progress_timeout_check(tp, true)) {
4977 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4978 		return (-ETIMEDOUT);	/* tcp_drop() */
4979 	}
4980 	bbr_remxt_tmr(tp);
4981 	if ((bbr->r_ctl.rc_resend == NULL) ||
4982 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4983 		/*
4984 		 * If the rwnd collapsed on
4985 		 * the one we are retransmitting
4986 		 * it does not count against the
4987 		 * rxt count.
4988 		 */
4989 		tp->t_rxtshift++;
4990 	}
4991 	if (tp->t_rxtshift > V_tcp_retries) {
4992 		tp->t_rxtshift = V_tcp_retries;
4993 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
4994 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
4995 		/* XXXGL: previously t_softerror was casted to uint16_t */
4996 		MPASS(tp->t_softerror >= 0);
4997 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
4998 		return (retval);	/* tcp_drop() */
4999 	}
5000 	if (tp->t_state == TCPS_SYN_SENT) {
5001 		/*
5002 		 * If the SYN was retransmitted, indicate CWND to be limited
5003 		 * to 1 segment in cc_conn_init().
5004 		 */
5005 		tp->snd_cwnd = 1;
5006 	} else if (tp->t_rxtshift == 1) {
5007 		/*
5008 		 * first retransmit; record ssthresh and cwnd so they can be
5009 		 * recovered if this turns out to be a "bad" retransmit. A
5010 		 * retransmit is considered "bad" if an ACK for this segment
5011 		 * is received within RTT/2 interval; the assumption here is
5012 		 * that the ACK was already in flight.  See "On Estimating
5013 		 * End-to-End Network Path Properties" by Allman and Paxson
5014 		 * for more details.
5015 		 */
5016 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5017 		if (!IN_RECOVERY(tp->t_flags)) {
5018 			tp->snd_cwnd_prev = tp->snd_cwnd;
5019 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5020 			tp->snd_recover_prev = tp->snd_recover;
5021 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5022 			tp->t_flags |= TF_PREVVALID;
5023 		} else {
5024 			tp->t_flags &= ~TF_PREVVALID;
5025 		}
5026 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5027 	} else {
5028 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5029 		tp->t_flags &= ~TF_PREVVALID;
5030 	}
5031 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5032 	if ((tp->t_state == TCPS_SYN_SENT) ||
5033 	    (tp->t_state == TCPS_SYN_RECEIVED))
5034 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5035 	else
5036 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5037 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5038 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5039 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5040 	/*
5041 	 * We enter the path for PLMTUD if connection is established or, if
5042 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5043 	 * amount of data we send is very small, we could send it in couple
5044 	 * of packets and process straight to FIN. In that case we won't
5045 	 * catch ESTABLISHED state.
5046 	 */
5047 #ifdef INET6
5048 	isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
5049 #else
5050 	isipv6 = false;
5051 #endif
5052 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5053 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5054 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5055 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5056 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5057 		/*
5058 		 * Idea here is that at each stage of mtu probe (usually,
5059 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5060 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5061 		 * should take care of that.
5062 		 */
5063 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5064 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5065 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5066 		    tp->t_rxtshift % 2 == 0)) {
5067 			/*
5068 			 * Enter Path MTU Black-hole Detection mechanism: -
5069 			 * Disable Path MTU Discovery (IP "DF" bit). -
5070 			 * Reduce MTU to lower value than what we negotiated
5071 			 * with peer.
5072 			 */
5073 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5074 				/*
5075 				 * Record that we may have found a black
5076 				 * hole.
5077 				 */
5078 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5079 				/* Keep track of previous MSS. */
5080 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5081 			}
5082 			/*
5083 			 * Reduce the MSS to blackhole value or to the
5084 			 * default in an attempt to retransmit.
5085 			 */
5086 #ifdef INET6
5087 			isipv6 = bbr->r_is_v6;
5088 			if (isipv6 &&
5089 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5090 				/* Use the sysctl tuneable blackhole MSS. */
5091 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5092 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5093 			} else if (isipv6) {
5094 				/* Use the default MSS. */
5095 				tp->t_maxseg = V_tcp_v6mssdflt;
5096 				/*
5097 				 * Disable Path MTU Discovery when we switch
5098 				 * to minmss.
5099 				 */
5100 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5101 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5102 			}
5103 #endif
5104 #if defined(INET6) && defined(INET)
5105 			else
5106 #endif
5107 #ifdef INET
5108 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5109 				/* Use the sysctl tuneable blackhole MSS. */
5110 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5111 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5112 			} else {
5113 				/* Use the default MSS. */
5114 				tp->t_maxseg = V_tcp_mssdflt;
5115 				/*
5116 				 * Disable Path MTU Discovery when we switch
5117 				 * to minmss.
5118 				 */
5119 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5120 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5121 			}
5122 #endif
5123 		} else {
5124 			/*
5125 			 * If further retransmissions are still unsuccessful
5126 			 * with a lowered MTU, maybe this isn't a blackhole
5127 			 * and we restore the previous MSS and blackhole
5128 			 * detection flags. The limit '6' is determined by
5129 			 * giving each probe stage (1448, 1188, 524) 2
5130 			 * chances to recover.
5131 			 */
5132 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5133 			    (tp->t_rxtshift >= 6)) {
5134 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5135 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5136 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5137 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5138 			}
5139 		}
5140 	}
5141 	/*
5142 	 * Disable RFC1323 and SACK if we haven't got any response to our
5143 	 * third SYN to work-around some broken terminal servers (most of
5144 	 * which have hopefully been retired) that have bad VJ header
5145 	 * compression code which trashes TCP segments containing
5146 	 * unknown-to-them TCP options.
5147 	 */
5148 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5149 	    (tp->t_rxtshift == 3))
5150 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5151 	/*
5152 	 * If we backed off this far, our srtt estimate is probably bogus.
5153 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5154 	 * move the current srtt into rttvar to keep the current retransmit
5155 	 * times until then.
5156 	 */
5157 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5158 #ifdef INET6
5159 		if (bbr->r_is_v6)
5160 			in6_losing(inp);
5161 		else
5162 #endif
5163 			in_losing(inp);
5164 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5165 		tp->t_srtt = 0;
5166 	}
5167 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5168 	tp->snd_recover = tp->snd_max;
5169 	tp->t_flags |= TF_ACKNOW;
5170 	tp->t_rtttime = 0;
5171 
5172 	return (retval);
5173 }
5174 
5175 static int
5176 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5177 {
5178 	int32_t ret = 0;
5179 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5180 
5181 	if (timers == 0) {
5182 		return (0);
5183 	}
5184 	if (tp->t_state == TCPS_LISTEN) {
5185 		/* no timers on listen sockets */
5186 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5187 			return (0);
5188 		return (1);
5189 	}
5190 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5191 		uint32_t left;
5192 
5193 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5194 			ret = -1;
5195 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5196 			return (0);
5197 		}
5198 		if (hpts_calling == 0) {
5199 			ret = -2;
5200 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5201 			return (0);
5202 		}
5203 		/*
5204 		 * Ok our timer went off early and we are not paced false
5205 		 * alarm, go back to sleep.
5206 		 */
5207 		left = bbr->r_ctl.rc_timer_exp - cts;
5208 		ret = -3;
5209 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5210 		tcp_hpts_insert(tp, HPTS_USEC_TO_SLOTS(left));
5211 		return (1);
5212 	}
5213 	bbr->rc_tmr_stopped = 0;
5214 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5215 	if (timers & PACE_TMR_DELACK) {
5216 		ret = bbr_timeout_delack(tp, bbr, cts);
5217 	} else if (timers & PACE_TMR_PERSIT) {
5218 		ret = bbr_timeout_persist(tp, bbr, cts);
5219 	} else if (timers & PACE_TMR_RACK) {
5220 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5221 		ret = bbr_timeout_rack(tp, bbr, cts);
5222 	} else if (timers & PACE_TMR_TLP) {
5223 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5224 		ret = bbr_timeout_tlp(tp, bbr, cts);
5225 	} else if (timers & PACE_TMR_RXT) {
5226 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5227 		ret = bbr_timeout_rxt(tp, bbr, cts);
5228 	} else if (timers & PACE_TMR_KEEP) {
5229 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5230 	}
5231 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5232 	return (ret);
5233 }
5234 
5235 static void
5236 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5237 {
5238 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5239 		uint8_t hpts_removed = 0;
5240 
5241 		if (tcp_in_hpts(bbr->rc_tp) &&
5242 		    (bbr->rc_timer_first == 1)) {
5243 			/*
5244 			 * If we are canceling timer's when we have the
5245 			 * timer ahead of the output being paced. We also
5246 			 * must remove ourselves from the hpts.
5247 			 */
5248 			hpts_removed = 1;
5249 			tcp_hpts_remove(bbr->rc_tp);
5250 			if (bbr->r_ctl.rc_last_delay_val) {
5251 				/* Update the last hptsi delay too */
5252 				uint32_t time_since_send;
5253 
5254 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5255 					time_since_send = cts - bbr->rc_pacer_started;
5256 				else
5257 					time_since_send = 0;
5258 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5259 					/* Cut down our slot time */
5260 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5261 				} else {
5262 					bbr->r_ctl.rc_last_delay_val = 0;
5263 				}
5264 				bbr->rc_pacer_started = cts;
5265 			}
5266 		}
5267 		bbr->rc_timer_first = 0;
5268 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5269 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5270 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5271 	}
5272 }
5273 
5274 static int
5275 bbr_stopall(struct tcpcb *tp)
5276 {
5277 	struct tcp_bbr *bbr;
5278 
5279 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5280 	bbr->rc_all_timers_stopped = 1;
5281 	return (0);
5282 }
5283 
5284 static uint32_t
5285 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5286 {
5287 	struct bbr_sendmap *rsm;
5288 
5289 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5290 	if ((rsm == NULL) || (u_rsm == rsm))
5291 		return (cts);
5292 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5293 }
5294 
5295 static void
5296 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5297      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5298 {
5299 	int32_t idx;
5300 
5301 	rsm->r_rtr_cnt++;
5302 	rsm->r_dupack = 0;
5303 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5304 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5305 		rsm->r_flags |= BBR_OVERMAX;
5306 	}
5307 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5308 		/* Take off the collapsed flag at rxt */
5309 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5310 	}
5311 	if (rsm->r_flags & BBR_MARKED_LOST) {
5312 		/* We have retransmitted, its no longer lost */
5313 		rsm->r_flags &= ~BBR_MARKED_LOST;
5314 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5315 	}
5316 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5317 		/*
5318 		 * We hit a RXT timer on it and
5319 		 * we cleared the "acked" flag.
5320 		 * We now have it going back into
5321 		 * flight, we can remove the cleared
5322 		 * flag and possibly do accounting on
5323 		 * this piece.
5324 		 */
5325 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5326 	}
5327 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5328 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5329 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5330 	}
5331 	idx = rsm->r_rtr_cnt - 1;
5332 	rsm->r_tim_lastsent[idx] = cts;
5333 	rsm->r_pacing_delay = pacing_time;
5334 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5335 	rsm->r_ts_valid = bbr->rc_ts_valid;
5336 	if (bbr->rc_ts_valid)
5337 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5338 	if (bbr->r_ctl.r_app_limited_until)
5339 		rsm->r_app_limited = 1;
5340 	else
5341 		rsm->r_app_limited = 0;
5342 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5343 		rsm->r_bbr_state = bbr_state_val(bbr);
5344 	else
5345 		rsm->r_bbr_state = 8;
5346 	if (rsm->r_flags & BBR_ACKED) {
5347 		/* Problably MTU discovery messing with us */
5348 		uint32_t old_flags;
5349 
5350 		old_flags = rsm->r_flags;
5351 		rsm->r_flags &= ~BBR_ACKED;
5352 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5353 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5354 		if (bbr->r_ctl.rc_sacked == 0)
5355 			bbr->r_ctl.rc_sacklast = NULL;
5356 	}
5357 	if (rsm->r_in_tmap) {
5358 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5359 	}
5360 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5361 	rsm->r_in_tmap = 1;
5362 	if (rsm->r_flags & BBR_SACK_PASSED) {
5363 		/* We have retransmitted due to the SACK pass */
5364 		rsm->r_flags &= ~BBR_SACK_PASSED;
5365 		rsm->r_flags |= BBR_WAS_SACKPASS;
5366 	}
5367 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5368 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5369 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5370 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5371 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5372 		rsm->r_is_gain = 1;
5373 		rsm->r_is_drain = 0;
5374 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5375 		rsm->r_is_drain = 1;
5376 		rsm->r_is_gain = 0;
5377 	} else {
5378 		rsm->r_is_drain = 0;
5379 		rsm->r_is_gain = 0;
5380 	}
5381 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5382 }
5383 
5384 /*
5385  * Returns 0, or the sequence where we stopped
5386  * updating. We also update the lenp to be the amount
5387  * of data left.
5388  */
5389 
5390 static uint32_t
5391 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5392     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5393 {
5394 	/*
5395 	 * We (re-)transmitted starting at rsm->r_start for some length
5396 	 * (possibly less than r_end.
5397 	 */
5398 	struct bbr_sendmap *nrsm;
5399 	uint32_t c_end;
5400 	int32_t len;
5401 
5402 	len = *lenp;
5403 	c_end = rsm->r_start + len;
5404 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5405 		/*
5406 		 * We retransmitted the whole piece or more than the whole
5407 		 * slopping into the next rsm.
5408 		 */
5409 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5410 		if (c_end == rsm->r_end) {
5411 			*lenp = 0;
5412 			return (0);
5413 		} else {
5414 			int32_t act_len;
5415 
5416 			/* Hangs over the end return whats left */
5417 			act_len = rsm->r_end - rsm->r_start;
5418 			*lenp = (len - act_len);
5419 			return (rsm->r_end);
5420 		}
5421 		/* We don't get out of this block. */
5422 	}
5423 	/*
5424 	 * Here we retransmitted less than the whole thing which means we
5425 	 * have to split this into what was transmitted and what was not.
5426 	 */
5427 	nrsm = bbr_alloc_full_limit(bbr);
5428 	if (nrsm == NULL) {
5429 		*lenp = 0;
5430 		return (0);
5431 	}
5432 	/*
5433 	 * So here we are going to take the original rsm and make it what we
5434 	 * retransmitted. nrsm will be the tail portion we did not
5435 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5436 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5437 	 * 1, 6 and the new piece will be 6, 11.
5438 	 */
5439 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5440 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5441 	nrsm->r_dupack = 0;
5442 	if (rsm->r_in_tmap) {
5443 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5444 		nrsm->r_in_tmap = 1;
5445 	}
5446 	rsm->r_flags &= (~BBR_HAS_FIN);
5447 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5448 	*lenp = 0;
5449 	return (0);
5450 }
5451 
5452 static uint64_t
5453 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5454 {
5455 	uint64_t bw;
5456 
5457 	bw = bbr_get_bw(bbr);
5458 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5459 	bw /= (uint64_t)BBR_UNIT;
5460 	return(bw);
5461 }
5462 
5463 static void
5464 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5465 		       uint64_t act_rate, uint64_t rate_wanted)
5466 {
5467 	/*
5468 	 * We could not get a full gains worth
5469 	 * of rate.
5470 	 */
5471 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5472 		/* we can't even get the real rate */
5473 		uint64_t red;
5474 
5475 		bbr->skip_gain = 1;
5476 		bbr->gain_is_limited = 0;
5477 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5478 		if (red)
5479 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5480 	} else {
5481 		/* We can use a lower gain */
5482 		bbr->skip_gain = 0;
5483 		bbr->gain_is_limited = 1;
5484 	}
5485 }
5486 
5487 static void
5488 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5489 {
5490 	const struct tcp_hwrate_limit_table *nrte;
5491 	int error, rate = -1;
5492 
5493 	if (bbr->r_ctl.crte == NULL)
5494 		return;
5495 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5496 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5497 		/* Lost our routes? */
5498 		/* Clear the way for a re-attempt */
5499 		bbr->bbr_attempt_hdwr_pace = 0;
5500 lost_rate:
5501 		bbr->gain_is_limited = 0;
5502 		bbr->skip_gain = 0;
5503 		bbr->bbr_hdrw_pacing = 0;
5504 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5505 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5506 		tcp_bbr_tso_size_check(bbr, cts);
5507 		return;
5508 	}
5509 	rate = bbr_get_hardware_rate(bbr);
5510 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5511 				   bbr->rc_tp,
5512 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5513 				   rate,
5514 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5515 				   &error, NULL);
5516 	if (nrte == NULL) {
5517 		goto lost_rate;
5518 	}
5519 	if (nrte != bbr->r_ctl.crte) {
5520 		bbr->r_ctl.crte = nrte;
5521 		if (error == 0)  {
5522 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5523 			if (bbr->r_ctl.crte->rate < rate) {
5524 				/* We have a problem */
5525 				bbr_setup_less_of_rate(bbr, cts,
5526 						       bbr->r_ctl.crte->rate, rate);
5527 			} else {
5528 				/* We are good */
5529 				bbr->gain_is_limited = 0;
5530 				bbr->skip_gain = 0;
5531 			}
5532 		} else {
5533 			/* A failure should release the tag */
5534 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5535 			bbr->gain_is_limited = 0;
5536 			bbr->skip_gain = 0;
5537 			bbr->bbr_hdrw_pacing = 0;
5538 		}
5539 		bbr_type_log_hdwr_pacing(bbr,
5540 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5541 					 rate,
5542 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5543 					 __LINE__,
5544 					 cts,
5545 					 error);
5546 	}
5547 }
5548 
5549 static void
5550 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5551 {
5552 	/*
5553 	 * If we have hardware pacing support
5554 	 * we need to factor that in for our
5555 	 * TSO size.
5556 	 */
5557 	const struct tcp_hwrate_limit_table *rlp;
5558 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5559 
5560 	if ((bbr->bbr_hdrw_pacing == 0) ||
5561 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5562 	    (bbr->r_ctl.crte == NULL))
5563 		return;
5564 	if (bbr->hw_pacing_set == 0) {
5565 		/* Not yet by the hdwr pacing count delay */
5566 		return;
5567 	}
5568 	if (bbr_hdwr_pace_adjust == 0) {
5569 		/* No adjustment */
5570 		return;
5571 	}
5572 	rlp = bbr->r_ctl.crte;
5573 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5574 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5575 	else
5576 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5577 	/*
5578 	 * So lets first get the
5579 	 * time we will take between
5580 	 * TSO sized sends currently without
5581 	 * hardware help.
5582 	 */
5583 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5584 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5585 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5586 	hdwr_delay *= rlp->time_between;
5587 	if (cur_delay > hdwr_delay)
5588 		delta = cur_delay - hdwr_delay;
5589 	else
5590 		delta = 0;
5591 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5592 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5593 			     1);
5594 	if (delta &&
5595 	    (delta < (max(rlp->time_between,
5596 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5597 		/*
5598 		 * Now lets divide by the pacing
5599 		 * time between each segment the
5600 		 * hardware sends rounding up and
5601 		 * derive a bytes from that. We multiply
5602 		 * that by bbr_hdwr_pace_adjust to get
5603 		 * more bang for our buck.
5604 		 *
5605 		 * The goal is to have the software pacer
5606 		 * waiting no more than an additional
5607 		 * pacing delay if we can (without the
5608 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5609 		 */
5610 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5611 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5612 		seg_sz *= bbr_hdwr_pace_adjust;
5613 		if (bbr_hdwr_pace_floor &&
5614 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5615 			/* Currently hardware paces
5616 			 * out rs_min_seg segments at a time.
5617 			 * We need to make sure we always send at least
5618 			 * a full burst of bbr_hdwr_pace_floor down.
5619 			 */
5620 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5621 		}
5622 		seg_sz *= maxseg;
5623 	} else if (delta == 0) {
5624 		/*
5625 		 * The highest pacing rate is
5626 		 * above our b/w gained. This means
5627 		 * we probably are going quite fast at
5628 		 * the hardware highest rate. Lets just multiply
5629 		 * the calculated TSO size by the
5630 		 * multiplier factor (its probably
5631 		 * 4 segments in the default config for
5632 		 * mlx).
5633 		 */
5634 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5635 		if (bbr_hdwr_pace_floor &&
5636 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5637 			/* Currently hardware paces
5638 			 * out rs_min_seg segments at a time.
5639 			 * We need to make sure we always send at least
5640 			 * a full burst of bbr_hdwr_pace_floor down.
5641 			 */
5642 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5643 		}
5644 	} else {
5645 		/*
5646 		 * The pacing time difference is so
5647 		 * big that the hardware will
5648 		 * pace out more rapidly then we
5649 		 * really want and then we
5650 		 * will have a long delay. Lets just keep
5651 		 * the same TSO size so its as if
5652 		 * we were not using hdwr pacing (we
5653 		 * just gain a bit of spacing from the
5654 		 * hardware if seg_sz > 1).
5655 		 */
5656 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5657 	}
5658 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5659 		new_tso = seg_sz;
5660 	else
5661 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5662 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5663 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5664 
5665 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5666 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5667 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5668 	}
5669 }
5670 
5671 static void
5672 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5673 {
5674 	uint64_t bw;
5675 	uint32_t old_tso = 0, new_tso;
5676 	uint32_t maxseg, bytes;
5677 	uint32_t tls_seg=0;
5678 	/*
5679 	 * Google/linux uses the following algorithm to determine
5680 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5681 	 *
5682 	 *  bytes = bw_in_bytes_per_second / 1000
5683 	 *  bytes = min(bytes, 64k)
5684 	 *  tso_segs = bytes / MSS
5685 	 *  if (bw < 1.2Mbs)
5686 	 *      min_tso_segs = 1
5687 	 *  else
5688 	 *	min_tso_segs = 2
5689 	 * tso_segs = max(tso_segs, min_tso_segs)
5690 	 *
5691 	 * * Note apply a device specific limit (we apply this in the
5692 	 *   tcp_m_copym).
5693 	 * Note that before the initial measurement is made google bursts out
5694 	 * a full iwnd just like new-reno/cubic.
5695 	 *
5696 	 * We do not use this algorithm. Instead we
5697 	 * use a two phased approach:
5698 	 *
5699 	 *  if ( bw <= per-tcb-cross-over)
5700 	 *     goal_tso =  calculate how much with this bw we
5701 	 *                 can send in goal-time seconds.
5702 	 *     if (goal_tso > mss)
5703 	 *         seg = goal_tso / mss
5704 	 *         tso = seg * mss
5705 	 *     else
5706 	 *         tso = mss
5707 	 *     if (tso > per-tcb-max)
5708 	 *         tso = per-tcb-max
5709 	 *  else if ( bw > 512Mbps)
5710 	 *     tso = max-tso (64k/mss)
5711 	 *  else
5712 	 *     goal_tso = bw / per-tcb-divsor
5713 	 *     seg = (goal_tso + mss-1)/mss
5714 	 *     tso = seg * mss
5715 	 *
5716 	 * if (tso < per-tcb-floor)
5717 	 *    tso = per-tcb-floor
5718 	 * if (tso > per-tcb-utter_max)
5719 	 *    tso = per-tcb-utter_max
5720 	 *
5721 	 * Note the default per-tcb-divisor is 1000 (same as google).
5722 	 * the goal cross over is 30Mbps however. To recreate googles
5723 	 * algorithm you need to set:
5724 	 *
5725 	 * cross-over = 23,168,000 bps
5726 	 * goal-time = 18000
5727 	 * per-tcb-max = 2
5728 	 * per-tcb-divisor = 1000
5729 	 * per-tcb-floor = 1
5730 	 *
5731 	 * This will get you "google bbr" behavior with respect to tso size.
5732 	 *
5733 	 * Note we do set anything TSO size until we are past the initial
5734 	 * window. Before that we gnerally use either a single MSS
5735 	 * or we use the full IW size (so we burst a IW at a time)
5736 	 */
5737 
5738 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5739 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5740 	} else {
5741 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5742 	}
5743 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5744 	if (bbr->rc_past_init_win == 0) {
5745 		/*
5746 		 * Not enough data has been acknowledged to make a
5747 		 * judgement. Set up the initial TSO based on if we
5748 		 * are sending a full IW at once or not.
5749 		 */
5750 		if (bbr->rc_use_google)
5751 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5752 		else if (bbr->bbr_init_win_cheat)
5753 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5754 		else
5755 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5756 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5757 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5758 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5759 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5760 		}
5761 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5762 			bbr_adjust_for_hw_pacing(bbr, cts);
5763 		return;
5764 	}
5765 	/**
5766 	 * Now lets set the TSO goal based on our delivery rate in
5767 	 * bytes per second. Note we only do this if
5768 	 * we have acked at least the initial cwnd worth of data.
5769 	 */
5770 	bw = bbr_get_bw(bbr);
5771 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5772 	     (bbr->rc_use_google == 0)) {
5773 		/* We clamp to one MSS in recovery */
5774 		new_tso = maxseg;
5775 	} else if (bbr->rc_use_google) {
5776 		int min_tso_segs;
5777 
5778 		/* Google considers the gain too */
5779 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5780 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5781 			bw /= BBR_UNIT;
5782 		}
5783 		bytes = bw / 1024;
5784 		if (bytes > (64 * 1024))
5785 			bytes = 64 * 1024;
5786 		new_tso = bytes / maxseg;
5787 		if (bw < ONE_POINT_TWO_MEG)
5788 			min_tso_segs = 1;
5789 		else
5790 			min_tso_segs = 2;
5791 		if (new_tso < min_tso_segs)
5792 			new_tso = min_tso_segs;
5793 		new_tso *= maxseg;
5794 	} else if (bbr->rc_no_pacing) {
5795 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5796 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5797 		/*
5798 		 * Calculate the worse case b/w TSO if we are inserting no
5799 		 * more than a delay_target number of TSO's.
5800 		 */
5801 		uint32_t tso_len, min_tso;
5802 
5803 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5804 		if (tso_len > maxseg) {
5805 			new_tso = tso_len / maxseg;
5806 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5807 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5808 			new_tso *= maxseg;
5809 		} else {
5810 			/*
5811 			 * less than a full sized frame yikes.. long rtt or
5812 			 * low bw?
5813 			 */
5814 			min_tso = bbr_minseg(bbr);
5815 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5816 				new_tso = rounddown(tso_len, min_tso);
5817 			else
5818 				new_tso = min_tso;
5819 		}
5820 	} else if (bw > FIVETWELVE_MBPS) {
5821 		/*
5822 		 * This guy is so fast b/w wise that we can TSO as large as
5823 		 * possible of segments that the NIC will allow.
5824 		 */
5825 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5826 	} else {
5827 		/*
5828 		 * This formula is based on attempting to send a segment or
5829 		 * more every bbr_hptsi_per_second. The default is 1000
5830 		 * which means you are targeting what you can send every 1ms
5831 		 * based on the peers bw.
5832 		 *
5833 		 * If the number drops to say 500, then you are looking more
5834 		 * at 2ms and you will raise how much we send in a single
5835 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5836 		 * trade off of course is you will send more at once and
5837 		 * thus tend to clump up the sends into larger "bursts"
5838 		 * building a queue.
5839 		 */
5840 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5841 		new_tso = roundup(bw, (uint64_t)maxseg);
5842 		/*
5843 		 * Gate the floor to match what our lower than 48Mbps
5844 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5845 		 * becomes the floor for this calculation.
5846 		 */
5847 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5848 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5849 	}
5850 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5851 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5852 	if (new_tso > PACE_MAX_IP_BYTES)
5853 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5854 	/* Enforce an utter maximum. */
5855 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5856 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5857 	}
5858 	if (old_tso != new_tso) {
5859 		/* Only log changes */
5860 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5861 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5862 	}
5863 	/* We have hardware pacing! */
5864 	bbr_adjust_for_hw_pacing(bbr, cts);
5865 }
5866 
5867 static void
5868 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5869     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5870     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5871     struct sockbuf *sb)
5872 {
5873 
5874 	struct bbr_sendmap *rsm, *nrsm;
5875 	register uint32_t snd_max, snd_una;
5876 	uint32_t pacing_time;
5877 	/*
5878 	 * Add to the RACK log of packets in flight or retransmitted. If
5879 	 * there is a TS option we will use the TS echoed, if not we will
5880 	 * grab a TS.
5881 	 *
5882 	 * Retransmissions will increment the count and move the ts to its
5883 	 * proper place. Note that if options do not include TS's then we
5884 	 * won't be able to effectively use the ACK for an RTT on a retran.
5885 	 *
5886 	 * Notes about r_start and r_end. Lets consider a send starting at
5887 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5888 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5889 	 * This means that r_end is actually the first sequence for the next
5890 	 * slot (11).
5891 	 *
5892 	 */
5893 	INP_WLOCK_ASSERT(tptoinpcb(tp));
5894 	if (err) {
5895 		/*
5896 		 * We don't log errors -- we could but snd_max does not
5897 		 * advance in this case either.
5898 		 */
5899 		return;
5900 	}
5901 	if (th_flags & TH_RST) {
5902 		/*
5903 		 * We don't log resets and we return immediately from
5904 		 * sending
5905 		 */
5906 		*abandon = 1;
5907 		return;
5908 	}
5909 	snd_una = tp->snd_una;
5910 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5911 		/*
5912 		 * The call to bbr_log_output is made before bumping
5913 		 * snd_max. This means we can record one extra byte on a SYN
5914 		 * or FIN if seq_out is adding more on and a FIN is present
5915 		 * (and we are not resending).
5916 		 */
5917 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5918 			len++;
5919 		if (th_flags & TH_FIN)
5920 			len++;
5921 	}
5922 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5923 		/* Are sending an old segment to induce an ack (keep-alive)? */
5924 		return;
5925 	}
5926 	if (SEQ_LT(seq_out, snd_una)) {
5927 		/* huh? should we panic? */
5928 		uint32_t end;
5929 
5930 		end = seq_out + len;
5931 		seq_out = snd_una;
5932 		len = end - seq_out;
5933 	}
5934 	snd_max = tp->snd_max;
5935 	if (len == 0) {
5936 		/* We don't log zero window probes */
5937 		return;
5938 	}
5939 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5940 	/* First question is it a retransmission? */
5941 	if (seq_out == snd_max) {
5942 again:
5943 		rsm = bbr_alloc(bbr);
5944 		if (rsm == NULL) {
5945 			return;
5946 		}
5947 		rsm->r_flags = 0;
5948 		if (th_flags & TH_SYN)
5949 			rsm->r_flags |= BBR_HAS_SYN;
5950 		if (th_flags & TH_FIN)
5951 			rsm->r_flags |= BBR_HAS_FIN;
5952 		rsm->r_tim_lastsent[0] = cts;
5953 		rsm->r_rtr_cnt = 1;
5954 		rsm->r_rtr_bytes = 0;
5955 		rsm->r_start = seq_out;
5956 		rsm->r_end = rsm->r_start + len;
5957 		rsm->r_dupack = 0;
5958 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5959 		rsm->r_pacing_delay = pacing_time;
5960 		rsm->r_ts_valid = bbr->rc_ts_valid;
5961 		if (bbr->rc_ts_valid)
5962 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5963 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
5964 		if (bbr->r_ctl.r_app_limited_until)
5965 			rsm->r_app_limited = 1;
5966 		else
5967 			rsm->r_app_limited = 0;
5968 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5969 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5970 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5971 		/*
5972 		 * Here we must also add in this rsm since snd_max
5973 		 * is updated after we return from a new send.
5974 		 */
5975 		rsm->r_flight_at_send += len;
5976 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
5977 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5978 		rsm->r_in_tmap = 1;
5979 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5980 			rsm->r_bbr_state = bbr_state_val(bbr);
5981 		else
5982 			rsm->r_bbr_state = 8;
5983 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5984 			rsm->r_is_gain = 1;
5985 			rsm->r_is_drain = 0;
5986 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5987 			rsm->r_is_drain = 1;
5988 			rsm->r_is_gain = 0;
5989 		} else {
5990 			rsm->r_is_drain = 0;
5991 			rsm->r_is_gain = 0;
5992 		}
5993 		return;
5994 	}
5995 	/*
5996 	 * If we reach here its a retransmission and we need to find it.
5997 	 */
5998 more:
5999 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6000 		rsm = hintrsm;
6001 		hintrsm = NULL;
6002 	} else if (bbr->r_ctl.rc_next) {
6003 		/* We have a hint from a previous run */
6004 		rsm = bbr->r_ctl.rc_next;
6005 	} else {
6006 		/* No hints sorry */
6007 		rsm = NULL;
6008 	}
6009 	if ((rsm) && (rsm->r_start == seq_out)) {
6010 		/*
6011 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6012 		 * likely case.
6013 		 */
6014 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6015 		if (len == 0) {
6016 			return;
6017 		} else {
6018 			goto more;
6019 		}
6020 	}
6021 	/* Ok it was not the last pointer go through it the hard way. */
6022 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6023 		if (rsm->r_start == seq_out) {
6024 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6025 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6026 			if (len == 0) {
6027 				return;
6028 			} else {
6029 				continue;
6030 			}
6031 		}
6032 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6033 			/* Transmitted within this piece */
6034 			/*
6035 			 * Ok we must split off the front and then let the
6036 			 * update do the rest
6037 			 */
6038 			nrsm = bbr_alloc_full_limit(bbr);
6039 			if (nrsm == NULL) {
6040 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6041 				return;
6042 			}
6043 			/*
6044 			 * copy rsm to nrsm and then trim the front of rsm
6045 			 * to not include this part.
6046 			 */
6047 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6048 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6049 			if (rsm->r_in_tmap) {
6050 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6051 				nrsm->r_in_tmap = 1;
6052 			}
6053 			rsm->r_flags &= (~BBR_HAS_FIN);
6054 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6055 			if (len == 0) {
6056 				return;
6057 			}
6058 		}
6059 	}
6060 	/*
6061 	 * Hmm not found in map did they retransmit both old and on into the
6062 	 * new?
6063 	 */
6064 	if (seq_out == tp->snd_max) {
6065 		goto again;
6066 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6067 #ifdef BBR_INVARIANTS
6068 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6069 		    seq_out, len, tp->snd_una, tp->snd_max);
6070 		printf("Starting Dump of all rack entries\n");
6071 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6072 			printf("rsm:%p start:%u end:%u\n",
6073 			    rsm, rsm->r_start, rsm->r_end);
6074 		}
6075 		printf("Dump complete\n");
6076 		panic("seq_out not found rack:%p tp:%p",
6077 		    bbr, tp);
6078 #endif
6079 	} else {
6080 #ifdef BBR_INVARIANTS
6081 		/*
6082 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6083 		 * flag)
6084 		 */
6085 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6086 		    seq_out, len, tp->snd_max, tp);
6087 #endif
6088 	}
6089 }
6090 
6091 static void
6092 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6093 {
6094 	/*
6095 	 * Collapse timeout back the cum-ack moved.
6096 	 */
6097 	tp->t_rxtshift = 0;
6098 	tp->t_softerror = 0;
6099 }
6100 
6101 static void
6102 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6103 {
6104 	bbr->rtt_valid = 1;
6105 	bbr->r_ctl.cur_rtt = rtt_usecs;
6106 	bbr->r_ctl.ts_in = tsin;
6107 	if (rsm_send_time)
6108 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6109 }
6110 
6111 static void
6112 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6113 {
6114 	/**
6115 	 * We have in our bbr control:
6116 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6117 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6118 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6119 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6120 	 *
6121 	 * Now we can calculate the time between the sends by doing:
6122 	 *
6123 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6124 	 *
6125 	 * And the peer's time between receiving them by doing:
6126 	 *
6127 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6128 	 *
6129 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6130 	 * We also may find that we can't use the timestamps if say we see
6131 	 * that the peer_delta indicates that though we may have taken 10ms to
6132 	 * pace out the data, it only saw 1ms between the two packets. This would
6133 	 * indicate that somewhere on the path is a batching entity that is giving
6134 	 * out time-slices of the actual b/w. This would mean we could not use
6135 	 * reliably the peers timestamps.
6136 	 *
6137 	 * We expect delta > peer_delta initially. Until we figure out the
6138 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6139 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6140 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6141 	 * put a 1 there. If the value is faster then ours, we will disable the
6142 	 * use of timestamps (though we could revist this later if we find it to be not
6143 	 * just an isolated one or two flows)).
6144 	 *
6145 	 * To detect the batching middle boxes we will come up with our compensation and
6146 	 * if with it in place, we find the peer is drastically off (by some margin) in
6147 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6148 	 *
6149 	 */
6150 	uint64_t delta, peer_delta, delta_up;
6151 
6152 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6153 	if (delta < bbr_min_usec_delta) {
6154 		/*
6155 		 * Have not seen a min amount of time
6156 		 * between our send times so we can
6157 		 * make a determination of the timestamp
6158 		 * yet.
6159 		 */
6160 		return;
6161 	}
6162 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6163 	if (peer_delta < bbr_min_peer_delta) {
6164 		/*
6165 		 * We may have enough in the form of
6166 		 * our delta but the peers number
6167 		 * has not changed that much. It could
6168 		 * be its clock ratio is such that
6169 		 * we need more data (10ms tick) or
6170 		 * there may be other compression scenarios
6171 		 * going on. In any event we need the
6172 		 * spread to be larger.
6173 		 */
6174 		return;
6175 	}
6176 	/* Ok lets first see which way our delta is going */
6177 	if (peer_delta > delta) {
6178 		/* Very unlikely, the peer without
6179 		 * compensation shows that it saw
6180 		 * the two sends arrive further apart
6181 		 * then we saw then in micro-seconds.
6182 		 */
6183 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6184 			/* well it looks like the peer is a micro-second clock. */
6185 			bbr->rc_ts_clock_set = 1;
6186 			bbr->r_ctl.bbr_peer_tsratio = 1;
6187 		} else {
6188 			bbr->rc_ts_cant_be_used = 1;
6189 			bbr->rc_ts_clock_set = 1;
6190 		}
6191 		return;
6192 	}
6193 	/* Ok we know that the peer_delta is smaller than our send distance */
6194 	bbr->rc_ts_clock_set = 1;
6195 	/* First question is it within the percentage that they are using usec time? */
6196 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6197 	if ((peer_delta + delta_up) >= delta) {
6198 		/* Its a usec clock */
6199 		bbr->r_ctl.bbr_peer_tsratio = 1;
6200 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6201 		return;
6202 	}
6203 	/* Ok if not usec, what about 10usec (though unlikely)? */
6204 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6205 	if (((peer_delta * 10) + delta_up) >= delta) {
6206 		bbr->r_ctl.bbr_peer_tsratio = 10;
6207 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6208 		return;
6209 	}
6210 	/* And what about 100usec (though again unlikely)? */
6211 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6212 	if (((peer_delta * 100) + delta_up) >= delta) {
6213 		bbr->r_ctl.bbr_peer_tsratio = 100;
6214 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6215 		return;
6216 	}
6217 	/* And how about 1 msec (the most likely one)? */
6218 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6219 	if (((peer_delta * 1000) + delta_up) >= delta) {
6220 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6221 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6222 		return;
6223 	}
6224 	/* Ok if not msec could it be 10 msec? */
6225 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6226 	if (((peer_delta * 10000) + delta_up) >= delta) {
6227 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6228 		return;
6229 	}
6230 	/* If we fall down here the clock tick so slowly we can't use it */
6231 	bbr->rc_ts_cant_be_used = 1;
6232 	bbr->r_ctl.bbr_peer_tsratio = 0;
6233 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6234 }
6235 
6236 /*
6237  * Collect new round-trip time estimate
6238  * and update averages and current timeout.
6239  */
6240 static void
6241 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6242 {
6243 	int32_t delta;
6244 	uint32_t rtt, tsin;
6245 	int32_t rtt_ticks;
6246 
6247 	if (bbr->rtt_valid == 0)
6248 		/* No valid sample */
6249 		return;
6250 
6251 	rtt = bbr->r_ctl.cur_rtt;
6252 	tsin = bbr->r_ctl.ts_in;
6253 	if (bbr->rc_prtt_set_ts) {
6254 		/*
6255 		 * We are to force feed the rttProp filter due
6256 		 * to an entry into PROBE_RTT. This assures
6257 		 * that the times are sync'd between when we
6258 		 * go into PROBE_RTT and the filter expiration.
6259 		 *
6260 		 * Google does not use a true filter, so they do
6261 		 * this implicitly since they only keep one value
6262 		 * and when they enter probe-rtt they update the
6263 		 * value to the newest rtt.
6264 		 */
6265 		uint32_t rtt_prop;
6266 
6267 		bbr->rc_prtt_set_ts = 0;
6268 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6269 		if (rtt > rtt_prop)
6270 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6271 		else
6272 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6273 	}
6274 #ifdef STATS
6275 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_PATHRTT, imax(0, rtt));
6276 #endif
6277 	if (bbr->rc_ack_was_delayed)
6278 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6279 
6280 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6281 		bbr->r_ctl.rc_lowest_rtt = rtt;
6282 	bbr_log_rtt_sample(bbr, rtt, tsin);
6283 	if (bbr->r_init_rtt) {
6284 		/*
6285 		 * The initial rtt is not-trusted, nuke it and lets get
6286 		 * our first valid measurement in.
6287 		 */
6288 		bbr->r_init_rtt = 0;
6289 		tp->t_srtt = 0;
6290 	}
6291 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6292 		/*
6293 		 * So we have not yet figured out
6294 		 * what the peers TSTMP value is
6295 		 * in (most likely ms). We need a
6296 		 * series of cum-ack's to determine
6297 		 * this reliably.
6298 		 */
6299 		if (bbr->rc_ack_is_cumack) {
6300 			if (bbr->rc_ts_data_set) {
6301 				/* Lets attempt to determine the timestamp granularity. */
6302 				bbr_make_timestamp_determination(bbr);
6303 			} else {
6304 				bbr->rc_ts_data_set = 1;
6305 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6306 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6307 			}
6308 		} else {
6309 			/*
6310 			 * We have to have consecutive acks
6311 			 * reset any "filled" state to none.
6312 			 */
6313 			bbr->rc_ts_data_set = 0;
6314 		}
6315 	}
6316 	/* Round it up */
6317 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6318 	if (rtt_ticks == 0)
6319 		rtt_ticks = 1;
6320 	if (tp->t_srtt != 0) {
6321 		/*
6322 		 * srtt is stored as fixed point with 5 bits after the
6323 		 * binary point (i.e., scaled by 8).  The following magic is
6324 		 * equivalent to the smoothing algorithm in rfc793 with an
6325 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6326 		 * Adjust rtt to origin 0.
6327 		 */
6328 
6329 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6330 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6331 
6332 		tp->t_srtt += delta;
6333 		if (tp->t_srtt <= 0)
6334 			tp->t_srtt = 1;
6335 
6336 		/*
6337 		 * We accumulate a smoothed rtt variance (actually, a
6338 		 * smoothed mean difference), then set the retransmit timer
6339 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6340 		 * is stored as fixed point with 4 bits after the binary
6341 		 * point (scaled by 16).  The following is equivalent to
6342 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6343 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6344 		 * wired-in beta.
6345 		 */
6346 		if (delta < 0)
6347 			delta = -delta;
6348 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6349 		tp->t_rttvar += delta;
6350 		if (tp->t_rttvar <= 0)
6351 			tp->t_rttvar = 1;
6352 	} else {
6353 		/*
6354 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6355 		 * variance to half the rtt (so our first retransmit happens
6356 		 * at 3*rtt).
6357 		 */
6358 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6359 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6360 	}
6361 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6362 	if (tp->t_rttupdated < UCHAR_MAX)
6363 		tp->t_rttupdated++;
6364 #ifdef STATS
6365 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6366 #endif
6367 	/*
6368 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6369 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6370 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6371 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6372 	 * uncertainty in the firing of the timer.  The bias will give us
6373 	 * exactly the 1.5 tick we need.  But, because the bias is
6374 	 * statistical, we have to test that we don't drop below the minimum
6375 	 * feasible timer (which is 2 ticks).
6376 	 */
6377 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6378 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6379 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6380 
6381 	/*
6382 	 * We received an ack for a packet that wasn't retransmitted; it is
6383 	 * probably safe to discard any error indications we've received
6384 	 * recently.  This isn't quite right, but close enough for now (a
6385 	 * route might have failed after we sent a segment, and the return
6386 	 * path might not be symmetrical).
6387 	 */
6388 	tp->t_softerror = 0;
6389 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6390 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6391 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6392 }
6393 
6394 static void
6395 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6396 {
6397 	bbr->r_ctl.rc_rtt_shrinks = cts;
6398 	if (bbr_can_force_probertt &&
6399 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6400 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6401 		/*
6402 		 * We should enter probe-rtt its been too long
6403 		 * since we have been there.
6404 		 */
6405 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6406 	} else
6407 		bbr_check_probe_rtt_limits(bbr, cts);
6408 }
6409 
6410 static void
6411 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6412 {
6413 	uint64_t orig_bw;
6414 
6415 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6416 		/* We never apply a zero measurement */
6417 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6418 				    0, 0, 0, 0, 0, 0);
6419 		return;
6420 	}
6421 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6422 		bbr->r_ctl.r_measurement_count++;
6423 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6424 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6425 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6426 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6427 			    0, 0, 0, 0, 0, 0);
6428 	if (orig_bw &&
6429 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6430 		if (bbr->bbr_hdrw_pacing) {
6431 			/*
6432 			 * Apply a new rate to the hardware
6433 			 * possibly.
6434 			 */
6435 			bbr_update_hardware_pacing_rate(bbr, cts);
6436 		}
6437 		bbr_set_state_target(bbr, __LINE__);
6438 		tcp_bbr_tso_size_check(bbr, cts);
6439 		if (bbr->r_recovery_bw)  {
6440 			bbr_setup_red_bw(bbr, cts);
6441 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6442 		}
6443 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6444 		tcp_bbr_tso_size_check(bbr, cts);
6445 }
6446 
6447 static void
6448 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6449 {
6450 	if (bbr->rc_in_persist == 0) {
6451 		/* We log only when not in persist */
6452 		/* Translate to a Bytes Per Second */
6453 		uint64_t tim, bw, ts_diff, ts_bw;
6454 		uint32_t delivered;
6455 
6456 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6457 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6458 		else
6459 			tim = 1;
6460 		/*
6461 		 * Now that we have processed the tim (skipping the sample
6462 		 * or possibly updating the time, go ahead and
6463 		 * calculate the cdr.
6464 		 */
6465 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6466 		bw = (uint64_t)delivered;
6467 		bw *= (uint64_t)USECS_IN_SECOND;
6468 		bw /= tim;
6469 		if (bw == 0) {
6470 			/* We must have a calculatable amount */
6471 			return;
6472 		}
6473 		/*
6474 		 * If we are using this b/w shove it in now so we
6475 		 * can see in the trace viewer if it gets over-ridden.
6476 		 */
6477 		if (rsm->r_ts_valid &&
6478 		    bbr->rc_ts_valid &&
6479 		    bbr->rc_ts_clock_set &&
6480 		    (bbr->rc_ts_cant_be_used == 0) &&
6481 		    bbr->rc_use_ts_limit) {
6482 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6483 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6484 			if ((delivered == 0) ||
6485 			    (rtt < 1000)) {
6486 				/* Can't use the ts */
6487 				bbr_log_type_bbrupd(bbr, 61, cts,
6488 						    ts_diff,
6489 						    bbr->r_ctl.last_inbound_ts,
6490 						    rsm->r_del_ack_ts, 0,
6491 						    0, 0, 0, delivered);
6492 			} else {
6493 				ts_bw = (uint64_t)delivered;
6494 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6495 				ts_bw /= ts_diff;
6496 				bbr_log_type_bbrupd(bbr, 62, cts,
6497 						    (ts_bw >> 32),
6498 						    (ts_bw & 0xffffffff), 0, 0,
6499 						    0, 0, ts_diff, delivered);
6500 				if ((bbr->ts_can_raise) &&
6501 				    (ts_bw > bw)) {
6502 					bbr_log_type_bbrupd(bbr, 8, cts,
6503 							    delivered,
6504 							    ts_diff,
6505 							    (bw >> 32),
6506 							    (bw & 0x00000000ffffffff),
6507 							    0, 0, 0, 0);
6508 					bw = ts_bw;
6509 				} else if (ts_bw && (ts_bw < bw)) {
6510 					bbr_log_type_bbrupd(bbr, 7, cts,
6511 							    delivered,
6512 							    ts_diff,
6513 							    (bw >> 32),
6514 							    (bw & 0x00000000ffffffff),
6515 							    0, 0, 0, 0);
6516 					bw = ts_bw;
6517 				}
6518 			}
6519 		}
6520 		if (rsm->r_first_sent_time &&
6521 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6522 			uint64_t sbw, sti;
6523 			/*
6524 			 * We use what was in flight at the time of our
6525 			 * send  and the size of this send to figure
6526 			 * out what we have been sending at (amount).
6527 			 * For the time we take from the time of
6528 			 * the send of the first send outstanding
6529 			 * until this send plus this sends pacing
6530 			 * time. This gives us a good calculation
6531 			 * as to the rate we have been sending at.
6532 			 */
6533 
6534 			sbw = (uint64_t)(rsm->r_flight_at_send);
6535 			sbw *= (uint64_t)USECS_IN_SECOND;
6536 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6537 			sti += rsm->r_pacing_delay;
6538 			sbw /= sti;
6539 			if (sbw < bw) {
6540 				bbr_log_type_bbrupd(bbr, 6, cts,
6541 						    delivered,
6542 						    (uint32_t)sti,
6543 						    (bw >> 32),
6544 						    (uint32_t)bw,
6545 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6546 						    (uint32_t)sbw);
6547 				bw = sbw;
6548 			}
6549 		}
6550 		/* Use the google algorithm for b/w measurements */
6551 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6552 		if ((rsm->r_app_limited == 0) ||
6553 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6554 			tcp_bbr_commit_bw(bbr, cts);
6555 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6556 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6557 		}
6558 	}
6559 }
6560 
6561 static void
6562 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6563 {
6564 	if (bbr->rc_in_persist == 0) {
6565 		/* We log only when not in persist */
6566 		/* Translate to a Bytes Per Second */
6567 		uint64_t tim, bw;
6568 		uint32_t delivered;
6569 		int no_apply = 0;
6570 
6571 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6572 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6573 		else
6574 			tim = 1;
6575 		/*
6576 		 * Now that we have processed the tim (skipping the sample
6577 		 * or possibly updating the time, go ahead and
6578 		 * calculate the cdr.
6579 		 */
6580 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6581 		bw = (uint64_t)delivered;
6582 		bw *= (uint64_t)USECS_IN_SECOND;
6583 		bw /= tim;
6584 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6585 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6586 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6587 
6588 			no_apply = 1;
6589 		}
6590 		/*
6591 		 * If we are using this b/w shove it in now so we
6592 		 * can see in the trace viewer if it gets over-ridden.
6593 		 */
6594 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6595 		/* Gate by the sending rate */
6596 		if (rsm->r_first_sent_time &&
6597 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6598 			uint64_t sbw, sti;
6599 			/*
6600 			 * We use what was in flight at the time of our
6601 			 * send  and the size of this send to figure
6602 			 * out what we have been sending at (amount).
6603 			 * For the time we take from the time of
6604 			 * the send of the first send outstanding
6605 			 * until this send plus this sends pacing
6606 			 * time. This gives us a good calculation
6607 			 * as to the rate we have been sending at.
6608 			 */
6609 
6610 			sbw = (uint64_t)(rsm->r_flight_at_send);
6611 			sbw *= (uint64_t)USECS_IN_SECOND;
6612 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6613 			sti += rsm->r_pacing_delay;
6614 			sbw /= sti;
6615 			if (sbw < bw) {
6616 				bbr_log_type_bbrupd(bbr, 6, cts,
6617 						    delivered,
6618 						    (uint32_t)sti,
6619 						    (bw >> 32),
6620 						    (uint32_t)bw,
6621 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6622 						    (uint32_t)sbw);
6623 				bw = sbw;
6624 			}
6625 			if ((sti > tim) &&
6626 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6627 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6628 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6629 				no_apply = 1;
6630 			} else
6631 				no_apply = 0;
6632 		}
6633 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6634 		if ((no_apply == 0) &&
6635 		    ((rsm->r_app_limited == 0) ||
6636 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6637 			tcp_bbr_commit_bw(bbr, cts);
6638 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6639 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6640 		}
6641 	}
6642 }
6643 
6644 static void
6645 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6646     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6647 {
6648 	uint64_t old_rttprop;
6649 
6650 	/* Update our delivery time and amount */
6651 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6652 	bbr->r_ctl.rc_del_time = cts;
6653 	if (rtt == 0) {
6654 		/*
6655 		 * 0 means its a retransmit, for now we don't use these for
6656 		 * the rest of BBR.
6657 		 */
6658 		return;
6659 	}
6660 	if ((bbr->rc_use_google == 0) &&
6661 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6662 	    (match != BBR_RTT_BY_TIMESTAMP)){
6663 		/*
6664 		 * We get a lot of rtt updates, lets not pay attention to
6665 		 * any that are not an exact match. That way we don't have
6666 		 * to worry about timestamps and the whole nonsense of
6667 		 * unsure if its a retransmission etc (if we ever had the
6668 		 * timestamp fixed to always have the last thing sent this
6669 		 * would not be a issue).
6670 		 */
6671 		return;
6672 	}
6673 	if ((bbr_no_retran && bbr->rc_use_google) &&
6674 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6675 	    (match != BBR_RTT_BY_TIMESTAMP)){
6676 		/*
6677 		 * We only do measurements in google mode
6678 		 * with bbr_no_retran on for sure things.
6679 		 */
6680 		return;
6681 	}
6682 	/* Only update srtt if we know by exact match */
6683 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6684 	if (ack_type == BBR_CUM_ACKED)
6685 		bbr->rc_ack_is_cumack = 1;
6686 	else
6687 		bbr->rc_ack_is_cumack = 0;
6688 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6689 	/*
6690 	 * Note the following code differs to the original
6691 	 * BBR spec. It calls for <= not <. However after a
6692 	 * long discussion in email with Neal, he acknowledged
6693 	 * that it should be < than so that we will have flows
6694 	 * going into probe-rtt (we were seeing cases where that
6695 	 * did not happen and caused ugly things to occur). We
6696 	 * have added this agreed upon fix to our code base.
6697 	 */
6698 	if (rtt < old_rttprop) {
6699 		/* Update when we last saw a rtt drop */
6700 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6701 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6702 	}
6703 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6704 	    match, rsm->r_start, rsm->r_flags);
6705 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6706 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6707 		/*
6708 		 * The RTT-prop moved, reset the target (may be a
6709 		 * nop for some states).
6710 		 */
6711 		bbr_set_state_target(bbr, __LINE__);
6712 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6713 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6714 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6715 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6716 			/* It went up */
6717 			bbr_check_probe_rtt_limits(bbr, cts);
6718 	}
6719 	if ((bbr->rc_use_google == 0) &&
6720 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6721 		/*
6722 		 * We don't do b/w update with
6723 		 * these since they are not really
6724 		 * reliable.
6725 		 */
6726 		return;
6727 	}
6728 	if (bbr->r_ctl.r_app_limited_until &&
6729 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6730 		/* We are no longer app-limited */
6731 		bbr->r_ctl.r_app_limited_until = 0;
6732 	}
6733 	if (bbr->rc_use_google) {
6734 		bbr_google_measurement(bbr, rsm, rtt, cts);
6735 	} else {
6736 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6737 	}
6738 }
6739 
6740 /*
6741  * Convert a timestamp that the main stack
6742  * uses (milliseconds) into one that bbr uses
6743  * (microseconds). Return that converted timestamp.
6744  */
6745 static uint32_t
6746 bbr_ts_convert(uint32_t cts) {
6747 	uint32_t sec, msec;
6748 
6749 	sec = cts / MS_IN_USEC;
6750 	msec = cts - (MS_IN_USEC * sec);
6751 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6752 }
6753 
6754 /*
6755  * Return 0 if we did not update the RTT time, return
6756  * 1 if we did.
6757  */
6758 static int
6759 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6760     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6761 {
6762 	int32_t i;
6763 	uint32_t t, uts = 0;
6764 
6765 	if ((rsm->r_flags & BBR_ACKED) ||
6766 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6767 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6768 		/* Already done */
6769 		return (0);
6770 	}
6771 	if (rsm->r_rtt_not_allowed) {
6772 		/* Not allowed */
6773 		return (0);
6774 	}
6775 	if (rsm->r_rtr_cnt == 1) {
6776 		/*
6777 		 * Only one transmit. Hopefully the normal case.
6778 		 */
6779 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6780 			t = cts - rsm->r_tim_lastsent[0];
6781 		else
6782 			t = 1;
6783 		if ((int)t <= 0)
6784 			t = 1;
6785 		bbr->r_ctl.rc_last_rtt = t;
6786 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6787 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6788 		return (1);
6789 	}
6790 	/* Convert to usecs */
6791 	if ((bbr_can_use_ts_for_rtt == 1) &&
6792 	    (bbr->rc_use_google == 1) &&
6793 	    (ack_type == BBR_CUM_ACKED) &&
6794 	    (to->to_flags & TOF_TS) &&
6795 	    (to->to_tsecr != 0)) {
6796 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6797 		if (t < 1)
6798 			t = 1;
6799 		t *= MS_IN_USEC;
6800 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6801 				    BBR_RTT_BY_TIMESTAMP,
6802 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6803 				    ack_type, to);
6804 		return (1);
6805 	}
6806 	uts = bbr_ts_convert(to->to_tsecr);
6807 	if ((to->to_flags & TOF_TS) &&
6808 	    (to->to_tsecr != 0) &&
6809 	    (ack_type == BBR_CUM_ACKED) &&
6810 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6811 		/*
6812 		 * Now which timestamp does it match? In this block the ACK
6813 		 * may be coming from a previous transmission.
6814 		 */
6815 		uint32_t fudge;
6816 
6817 		fudge = BBR_TIMER_FUDGE;
6818 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6819 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6820 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6821 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6822 					t = cts - rsm->r_tim_lastsent[i];
6823 				else
6824 					t = 1;
6825 				if ((int)t <= 0)
6826 					t = 1;
6827 				bbr->r_ctl.rc_last_rtt = t;
6828 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6829 						    rsm->r_tim_lastsent[i], ack_type, to);
6830 				if ((i + 1) < rsm->r_rtr_cnt) {
6831 					/* Likely */
6832 					return (0);
6833 				} else if (rsm->r_flags & BBR_TLP) {
6834 					bbr->rc_tlp_rtx_out = 0;
6835 				}
6836 				return (1);
6837 			}
6838 		}
6839 		/* Fall through if we can't find a matching timestamp */
6840 	}
6841 	/*
6842 	 * Ok its a SACK block that we retransmitted. or a windows
6843 	 * machine without timestamps. We can tell nothing from the
6844 	 * time-stamp since its not there or the time the peer last
6845 	 * recieved a segment that moved forward its cum-ack point.
6846 	 *
6847 	 * Lets look at the last retransmit and see what we can tell
6848 	 * (with BBR for space we only keep 2 note we have to keep
6849 	 * at least 2 so the map can not be condensed more).
6850 	 */
6851 	i = rsm->r_rtr_cnt - 1;
6852 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6853 		t = cts - rsm->r_tim_lastsent[i];
6854 	else
6855 		goto not_sure;
6856 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6857 		/*
6858 		 * We retransmitted and the ack came back in less
6859 		 * than the smallest rtt we have observed in the
6860 		 * windowed rtt. We most likey did an improper
6861 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6862 		 * the rack-draft.
6863 		 *
6864 		 * Use the prior transmission to update all the
6865 		 * information as long as there is only one prior
6866 		 * transmission.
6867 		 */
6868 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6869 #ifdef BBR_INVARIANTS
6870 			if (rsm->r_rtr_cnt == 1)
6871 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6872 #endif
6873 			i = rsm->r_rtr_cnt - 2;
6874 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6875 				t = cts - rsm->r_tim_lastsent[i];
6876 			else
6877 				t = 1;
6878 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6879 					    rsm->r_tim_lastsent[i], ack_type, to);
6880 			return (0);
6881 		} else {
6882 			/*
6883 			 * Too many prior transmissions, just
6884 			 * updated BBR delivered
6885 			 */
6886 not_sure:
6887 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6888 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6889 		}
6890 	} else {
6891 		/*
6892 		 * We retransmitted it and the retransmit did the
6893 		 * job.
6894 		 */
6895 		if (rsm->r_flags & BBR_TLP)
6896 			bbr->rc_tlp_rtx_out = 0;
6897 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6898 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6899 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6900 		else
6901 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6902 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6903 		return (1);
6904 	}
6905 	return (0);
6906 }
6907 
6908 /*
6909  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6910  */
6911 static void
6912 bbr_log_sack_passed(struct tcpcb *tp,
6913     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6914 {
6915 	struct bbr_sendmap *nrsm;
6916 
6917 	nrsm = rsm;
6918 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6919 	    bbr_head, r_tnext) {
6920 		if (nrsm == rsm) {
6921 			/* Skip original segment he is acked */
6922 			continue;
6923 		}
6924 		if (nrsm->r_flags & BBR_ACKED) {
6925 			/* Skip ack'd segments */
6926 			continue;
6927 		}
6928 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6929 			/*
6930 			 * We found one that is already marked
6931 			 * passed, we have been here before and
6932 			 * so all others below this are marked.
6933 			 */
6934 			break;
6935 		}
6936 		BBR_STAT_INC(bbr_sack_passed);
6937 		nrsm->r_flags |= BBR_SACK_PASSED;
6938 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6939 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6940 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6941 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6942 			nrsm->r_flags |= BBR_MARKED_LOST;
6943 		}
6944 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6945 	}
6946 }
6947 
6948 /*
6949  * Returns the number of bytes that were
6950  * newly ack'd by sack blocks.
6951  */
6952 static uint32_t
6953 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6954     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6955 {
6956 	int32_t times = 0;
6957 	uint32_t start, end, changed = 0;
6958 	struct bbr_sendmap *rsm, *nrsm;
6959 	int32_t used_ref = 1;
6960 	uint8_t went_back = 0, went_fwd = 0;
6961 
6962 	start = sack->start;
6963 	end = sack->end;
6964 	rsm = *prsm;
6965 	if (rsm == NULL)
6966 		used_ref = 0;
6967 
6968 	/* Do we locate the block behind where we last were? */
6969 	if (rsm && SEQ_LT(start, rsm->r_start)) {
6970 		went_back = 1;
6971 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
6972 			if (SEQ_GEQ(start, rsm->r_start) &&
6973 			    SEQ_LT(start, rsm->r_end)) {
6974 				goto do_rest_ofb;
6975 			}
6976 		}
6977 	}
6978 start_at_beginning:
6979 	went_fwd = 1;
6980 	/*
6981 	 * Ok lets locate the block where this guy is fwd from rsm (if its
6982 	 * set)
6983 	 */
6984 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
6985 		if (SEQ_GEQ(start, rsm->r_start) &&
6986 		    SEQ_LT(start, rsm->r_end)) {
6987 			break;
6988 		}
6989 	}
6990 do_rest_ofb:
6991 	if (rsm == NULL) {
6992 		/*
6993 		 * This happens when we get duplicate sack blocks with the
6994 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
6995 		 * will not change there location so we would just start at
6996 		 * the end of the first one and get lost.
6997 		 */
6998 		if (tp->t_flags & TF_SENTFIN) {
6999 			/*
7000 			 * Check to see if we have not logged the FIN that
7001 			 * went out.
7002 			 */
7003 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7004 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7005 				/*
7006 				 * Ok we did not get the FIN logged.
7007 				 */
7008 				nrsm->r_end++;
7009 				rsm = nrsm;
7010 				goto do_rest_ofb;
7011 			}
7012 		}
7013 		if (times == 1) {
7014 #ifdef BBR_INVARIANTS
7015 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7016 			    tp, bbr, sack, to, prsm);
7017 #else
7018 			goto out;
7019 #endif
7020 		}
7021 		times++;
7022 		BBR_STAT_INC(bbr_sack_proc_restart);
7023 		rsm = NULL;
7024 		goto start_at_beginning;
7025 	}
7026 	/* Ok we have an ACK for some piece of rsm */
7027 	if (rsm->r_start != start) {
7028 		/*
7029 		 * Need to split this in two pieces the before and after.
7030 		 */
7031 		if (bbr_sack_mergable(rsm, start, end))
7032 			nrsm = bbr_alloc_full_limit(bbr);
7033 		else
7034 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7035 		if (nrsm == NULL) {
7036 			/* We could not allocate ignore the sack */
7037 			struct sackblk blk;
7038 
7039 			blk.start = start;
7040 			blk.end = end;
7041 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7042 			goto out;
7043 		}
7044 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7045 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7046 		if (rsm->r_in_tmap) {
7047 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7048 			nrsm->r_in_tmap = 1;
7049 		}
7050 		rsm->r_flags &= (~BBR_HAS_FIN);
7051 		rsm = nrsm;
7052 	}
7053 	if (SEQ_GEQ(end, rsm->r_end)) {
7054 		/*
7055 		 * The end of this block is either beyond this guy or right
7056 		 * at this guy.
7057 		 */
7058 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7059 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7060 			changed += (rsm->r_end - rsm->r_start);
7061 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7062 			bbr_log_sack_passed(tp, bbr, rsm);
7063 			if (rsm->r_flags & BBR_MARKED_LOST) {
7064 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7065 			}
7066 			/* Is Reordering occuring? */
7067 			if (rsm->r_flags & BBR_SACK_PASSED) {
7068 				BBR_STAT_INC(bbr_reorder_seen);
7069 				bbr->r_ctl.rc_reorder_ts = cts;
7070 				if (rsm->r_flags & BBR_MARKED_LOST) {
7071 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7072 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7073 						/* LT sampling also needs adjustment */
7074 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7075 				}
7076 			}
7077 			rsm->r_flags |= BBR_ACKED;
7078 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7079 			if (rsm->r_in_tmap) {
7080 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7081 				rsm->r_in_tmap = 0;
7082 			}
7083 		}
7084 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7085 		if (end == rsm->r_end) {
7086 			/* This block only - done */
7087 			goto out;
7088 		}
7089 		/* There is more not coverend by this rsm move on */
7090 		start = rsm->r_end;
7091 		nrsm = TAILQ_NEXT(rsm, r_next);
7092 		rsm = nrsm;
7093 		times = 0;
7094 		goto do_rest_ofb;
7095 	}
7096 	if (rsm->r_flags & BBR_ACKED) {
7097 		/* Been here done that */
7098 		goto out;
7099 	}
7100 	/* Ok we need to split off this one at the tail */
7101 	if (bbr_sack_mergable(rsm, start, end))
7102 		nrsm = bbr_alloc_full_limit(bbr);
7103 	else
7104 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7105 	if (nrsm == NULL) {
7106 		/* failed XXXrrs what can we do but loose the sack info? */
7107 		struct sackblk blk;
7108 
7109 		blk.start = start;
7110 		blk.end = end;
7111 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7112 		goto out;
7113 	}
7114 	/* Clone it */
7115 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7116 	/* The sack block does not cover this guy fully */
7117 	rsm->r_flags &= (~BBR_HAS_FIN);
7118 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7119 	if (rsm->r_in_tmap) {
7120 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7121 		nrsm->r_in_tmap = 1;
7122 	}
7123 	nrsm->r_dupack = 0;
7124 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7125 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7126 	changed += (rsm->r_end - rsm->r_start);
7127 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7128 	bbr_log_sack_passed(tp, bbr, rsm);
7129 	/* Is Reordering occuring? */
7130 	if (rsm->r_flags & BBR_MARKED_LOST) {
7131 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7132 	}
7133 	if (rsm->r_flags & BBR_SACK_PASSED) {
7134 		BBR_STAT_INC(bbr_reorder_seen);
7135 		bbr->r_ctl.rc_reorder_ts = cts;
7136 		if (rsm->r_flags & BBR_MARKED_LOST) {
7137 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7138 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7139 				/* LT sampling also needs adjustment */
7140 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7141 		}
7142 	}
7143 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7144 	rsm->r_flags |= BBR_ACKED;
7145 	if (rsm->r_in_tmap) {
7146 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7147 		rsm->r_in_tmap = 0;
7148 	}
7149 out:
7150 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7151 		/*
7152 		 * Now can we merge this newly acked
7153 		 * block with either the previous or
7154 		 * next block?
7155 		 */
7156 		nrsm = TAILQ_NEXT(rsm, r_next);
7157 		if (nrsm &&
7158 		    (nrsm->r_flags & BBR_ACKED)) {
7159 			/* yep this and next can be merged */
7160 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7161 		}
7162 		/* Now what about the previous? */
7163 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7164 		if (nrsm &&
7165 		    (nrsm->r_flags & BBR_ACKED)) {
7166 			/* yep the previous and this can be merged */
7167 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7168 		}
7169 	}
7170 	if (used_ref == 0) {
7171 		BBR_STAT_INC(bbr_sack_proc_all);
7172 	} else {
7173 		BBR_STAT_INC(bbr_sack_proc_short);
7174 	}
7175 	if (went_fwd && went_back) {
7176 		BBR_STAT_INC(bbr_sack_search_both);
7177 	} else if (went_fwd) {
7178 		BBR_STAT_INC(bbr_sack_search_fwd);
7179 	} else if (went_back) {
7180 		BBR_STAT_INC(bbr_sack_search_back);
7181 	}
7182 	/* Save off where the next seq is */
7183 	if (rsm)
7184 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7185 	else
7186 		bbr->r_ctl.rc_sacklast = NULL;
7187 	*prsm = rsm;
7188 	return (changed);
7189 }
7190 
7191 static void inline
7192 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7193 {
7194 	struct bbr_sendmap *tmap;
7195 
7196 	BBR_STAT_INC(bbr_reneges_seen);
7197 	tmap = NULL;
7198 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7199 		/* Its no longer sacked, mark it so */
7200 		uint32_t oflags;
7201 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7202 #ifdef BBR_INVARIANTS
7203 		if (rsm->r_in_tmap) {
7204 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7205 			    bbr, rsm, rsm->r_flags);
7206 		}
7207 #endif
7208 		oflags = rsm->r_flags;
7209 		if (rsm->r_flags & BBR_MARKED_LOST) {
7210 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7211 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7212 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7213 				/* LT sampling also needs adjustment */
7214 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7215 		}
7216 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7217 		rsm->r_flags |= BBR_WAS_RENEGED;
7218 		rsm->r_flags |= BBR_RXT_CLEARED;
7219 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7220 		/* Rebuild it into our tmap */
7221 		if (tmap == NULL) {
7222 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7223 			tmap = rsm;
7224 		} else {
7225 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7226 			tmap = rsm;
7227 		}
7228 		tmap->r_in_tmap = 1;
7229 		/*
7230 		 * XXXrrs Delivered? Should we do anything here?
7231 		 *
7232 		 * Of course we don't on a rxt timeout so maybe its ok that
7233 		 * we don't?
7234 		 *
7235 		 * For now lets not.
7236 		 */
7237 		rsm = TAILQ_NEXT(rsm, r_next);
7238 	}
7239 	/*
7240 	 * Now lets possibly clear the sack filter so we start recognizing
7241 	 * sacks that cover this area.
7242 	 */
7243 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7244 }
7245 
7246 static void
7247 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7248 {
7249 	struct tcp_bbr *bbr;
7250 	struct bbr_sendmap *rsm;
7251 	uint32_t cts;
7252 
7253 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7254 	cts = bbr->r_ctl.rc_rcvtime;
7255 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7256 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7257 		if ((rsm->r_end - rsm->r_start) <= 1) {
7258 			/* Log out the SYN completely */
7259 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7260 			rsm->r_rtr_bytes = 0;
7261 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7262 			if (rsm->r_in_tmap) {
7263 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7264 				rsm->r_in_tmap = 0;
7265 			}
7266 			if (bbr->r_ctl.rc_next == rsm) {
7267 				/* scoot along the marker */
7268 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7269 			}
7270 			if (to != NULL)
7271 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7272 			bbr_free(bbr, rsm);
7273 		} else {
7274 			/* There is more (Fast open)? strip out SYN. */
7275 			rsm->r_flags &= ~BBR_HAS_SYN;
7276 			rsm->r_start++;
7277 		}
7278 	}
7279 }
7280 
7281 /*
7282  * Returns the number of bytes that were
7283  * acknowledged by SACK blocks.
7284  */
7285 
7286 static uint32_t
7287 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7288     uint32_t *prev_acked)
7289 {
7290 	uint32_t changed, last_seq, entered_recovery = 0;
7291 	struct tcp_bbr *bbr;
7292 	struct bbr_sendmap *rsm;
7293 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7294 	register uint32_t th_ack;
7295 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7296 	uint32_t cts, acked, ack_point, sack_changed = 0;
7297 	uint32_t p_maxseg, maxseg, p_acked = 0;
7298 
7299 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7300 	if (tcp_get_flags(th) & TH_RST) {
7301 		/* We don't log resets */
7302 		return (0);
7303 	}
7304 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7305 	cts = bbr->r_ctl.rc_rcvtime;
7306 
7307 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7308 	changed = 0;
7309 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7310 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7311 	th_ack = th->th_ack;
7312 	if (SEQ_GT(th_ack, tp->snd_una)) {
7313 		acked = th_ack - tp->snd_una;
7314 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7315 		bbr->rc_tp->t_acktime = ticks;
7316 	} else
7317 		acked = 0;
7318 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7319 		/* Only sent here for sack processing */
7320 		goto proc_sack;
7321 	}
7322 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7323 		changed = th_ack - rsm->r_start;
7324 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7325 		/*
7326 		 * For the SYN incoming case we will not have called
7327 		 * tcp_output for the sending of the SYN, so there will be
7328 		 * no map. All other cases should probably be a panic.
7329 		 */
7330 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7331 			/*
7332 			 * We have a timestamp that can be used to generate
7333 			 * an initial RTT.
7334 			 */
7335 			uint32_t ts, now, rtt;
7336 
7337 			ts = bbr_ts_convert(to->to_tsecr);
7338 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7339 			rtt = now - ts;
7340 			if (rtt < 1)
7341 				rtt = 1;
7342 			bbr_log_type_bbrrttprop(bbr, rtt,
7343 						tp->iss, 0, cts,
7344 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7345 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7346 			changed = 1;
7347 			bbr->r_wanted_output = 1;
7348 			goto out;
7349 		}
7350 		goto proc_sack;
7351 	} else if (rsm == NULL) {
7352 		goto out;
7353 	}
7354 	if (changed) {
7355 		/*
7356 		 * The ACK point is advancing to th_ack, we must drop off
7357 		 * the packets in the rack log and calculate any eligble
7358 		 * RTT's.
7359 		 */
7360 		bbr->r_wanted_output = 1;
7361 more:
7362 		if (rsm == NULL) {
7363 			if (tp->t_flags & TF_SENTFIN) {
7364 				/* if we send a FIN we will not hav a map */
7365 				goto proc_sack;
7366 			}
7367 #ifdef BBR_INVARIANTS
7368 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7369 			    tp,
7370 			    th, tp->t_state, bbr,
7371 			    tp->snd_una, tp->snd_max, changed);
7372 #endif
7373 			goto proc_sack;
7374 		}
7375 	}
7376 	if (SEQ_LT(th_ack, rsm->r_start)) {
7377 		/* Huh map is missing this */
7378 #ifdef BBR_INVARIANTS
7379 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7380 		    rsm->r_start,
7381 		    th_ack, tp->t_state,
7382 		    bbr->r_state, bbr);
7383 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7384 #endif
7385 		goto proc_sack;
7386 	} else if (th_ack == rsm->r_start) {
7387 		/* None here to ack */
7388 		goto proc_sack;
7389 	}
7390 	/*
7391 	 * Clear the dup ack counter, it will
7392 	 * either be freed or if there is some
7393 	 * remaining we need to start it at zero.
7394 	 */
7395 	rsm->r_dupack = 0;
7396 	/* Now do we consume the whole thing? */
7397 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7398 		/* Its all consumed. */
7399 		uint32_t left;
7400 
7401 		if (rsm->r_flags & BBR_ACKED) {
7402 			/*
7403 			 * It was acked on the scoreboard -- remove it from
7404 			 * total
7405 			 */
7406 			p_acked += (rsm->r_end - rsm->r_start);
7407 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7408 			if (bbr->r_ctl.rc_sacked == 0)
7409 				bbr->r_ctl.rc_sacklast = NULL;
7410 		} else {
7411 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7412 			if (rsm->r_flags & BBR_MARKED_LOST) {
7413 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7414 			}
7415 			if (rsm->r_flags & BBR_SACK_PASSED) {
7416 				/*
7417 				 * There are acked segments ACKED on the
7418 				 * scoreboard further up. We are seeing
7419 				 * reordering.
7420 				 */
7421 				BBR_STAT_INC(bbr_reorder_seen);
7422 				bbr->r_ctl.rc_reorder_ts = cts;
7423 				if (rsm->r_flags & BBR_MARKED_LOST) {
7424 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7425 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7426 						/* LT sampling also needs adjustment */
7427 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7428 				}
7429 			}
7430 			rsm->r_flags &= ~BBR_MARKED_LOST;
7431 		}
7432 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7433 		rsm->r_rtr_bytes = 0;
7434 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7435 		if (rsm->r_in_tmap) {
7436 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7437 			rsm->r_in_tmap = 0;
7438 		}
7439 		if (bbr->r_ctl.rc_next == rsm) {
7440 			/* scoot along the marker */
7441 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7442 		}
7443 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7444 		/* Adjust the packet counts */
7445 		left = th_ack - rsm->r_end;
7446 		/* Free back to zone */
7447 		bbr_free(bbr, rsm);
7448 		if (left) {
7449 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7450 			goto more;
7451 		}
7452 		goto proc_sack;
7453 	}
7454 	if (rsm->r_flags & BBR_ACKED) {
7455 		/*
7456 		 * It was acked on the scoreboard -- remove it from total
7457 		 * for the part being cum-acked.
7458 		 */
7459 		p_acked += (rsm->r_end - rsm->r_start);
7460 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7461 		if (bbr->r_ctl.rc_sacked == 0)
7462 			bbr->r_ctl.rc_sacklast = NULL;
7463 	} else {
7464 		/*
7465 		 * It was acked up to th_ack point for the first time
7466 		 */
7467 		struct bbr_sendmap lrsm;
7468 
7469 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7470 		lrsm.r_end = th_ack;
7471 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7472 	}
7473 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7474 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7475 		/*
7476 		 * It was marked lost and partly ack'd now
7477 		 * for the first time. We lower the rc_lost_bytes
7478 		 * and still leave it MARKED.
7479 		 */
7480 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7481 	}
7482 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7483 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7484 	rsm->r_rtr_bytes = 0;
7485 	/* adjust packet count */
7486 	rsm->r_start = th_ack;
7487 proc_sack:
7488 	/* Check for reneging */
7489 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7490 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7491 		/*
7492 		 * The peer has moved snd_una up to the edge of this send,
7493 		 * i.e. one that it had previously acked. The only way that
7494 		 * can be true if the peer threw away data (space issues)
7495 		 * that it had previously sacked (else it would have given
7496 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7497 		 * markings here.
7498 		 *
7499 		 * Note we have to look to make sure th_ack is our
7500 		 * rsm->r_start in case we get an old ack where th_ack is
7501 		 * behind snd_una.
7502 		 */
7503 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7504 	}
7505 	if ((to->to_flags & TOF_SACK) == 0) {
7506 		/* We are done nothing left to log */
7507 		goto out;
7508 	}
7509 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7510 	if (rsm) {
7511 		last_seq = rsm->r_end;
7512 	} else {
7513 		last_seq = tp->snd_max;
7514 	}
7515 	/* Sack block processing */
7516 	if (SEQ_GT(th_ack, tp->snd_una))
7517 		ack_point = th_ack;
7518 	else
7519 		ack_point = tp->snd_una;
7520 	for (i = 0; i < to->to_nsacks; i++) {
7521 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7522 		    &sack, sizeof(sack));
7523 		sack.start = ntohl(sack.start);
7524 		sack.end = ntohl(sack.end);
7525 		if (SEQ_GT(sack.end, sack.start) &&
7526 		    SEQ_GT(sack.start, ack_point) &&
7527 		    SEQ_LT(sack.start, tp->snd_max) &&
7528 		    SEQ_GT(sack.end, ack_point) &&
7529 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7530 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7531 			    (SEQ_LT(sack.end, last_seq)) &&
7532 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7533 				/*
7534 				 * Not the last piece and its smaller than
7535 				 * 1/8th of a p_maxseg. We ignore this.
7536 				 */
7537 				BBR_STAT_INC(bbr_runt_sacks);
7538 				continue;
7539 			}
7540 			sack_blocks[num_sack_blks] = sack;
7541 			num_sack_blks++;
7542 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7543 		    SEQ_LEQ(sack.end, th_ack)) {
7544 			/*
7545 			 * Its a D-SACK block.
7546 			 */
7547 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7548 		}
7549 	}
7550 	if (num_sack_blks == 0)
7551 		goto out;
7552 	/*
7553 	 * Sort the SACK blocks so we can update the rack scoreboard with
7554 	 * just one pass.
7555 	 */
7556 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7557 				  num_sack_blks, th->th_ack);
7558 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7559 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7560 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7561 	num_sack_blks = new_sb;
7562 	if (num_sack_blks < 2) {
7563 		goto do_sack_work;
7564 	}
7565 	/* Sort the sacks */
7566 	for (i = 0; i < num_sack_blks; i++) {
7567 		for (j = i + 1; j < num_sack_blks; j++) {
7568 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7569 				sack = sack_blocks[i];
7570 				sack_blocks[i] = sack_blocks[j];
7571 				sack_blocks[j] = sack;
7572 			}
7573 		}
7574 	}
7575 	/*
7576 	 * Now are any of the sack block ends the same (yes some
7577 	 * implememtations send these)?
7578 	 */
7579 again:
7580 	if (num_sack_blks > 1) {
7581 		for (i = 0; i < num_sack_blks; i++) {
7582 			for (j = i + 1; j < num_sack_blks; j++) {
7583 				if (sack_blocks[i].end == sack_blocks[j].end) {
7584 					/*
7585 					 * Ok these two have the same end we
7586 					 * want the smallest end and then
7587 					 * throw away the larger and start
7588 					 * again.
7589 					 */
7590 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7591 						/*
7592 						 * The second block covers
7593 						 * more area use that
7594 						 */
7595 						sack_blocks[i].start = sack_blocks[j].start;
7596 					}
7597 					/*
7598 					 * Now collapse out the dup-sack and
7599 					 * lower the count
7600 					 */
7601 					for (k = (j + 1); k < num_sack_blks; k++) {
7602 						sack_blocks[j].start = sack_blocks[k].start;
7603 						sack_blocks[j].end = sack_blocks[k].end;
7604 						j++;
7605 					}
7606 					num_sack_blks--;
7607 					goto again;
7608 				}
7609 			}
7610 		}
7611 	}
7612 do_sack_work:
7613 	rsm = bbr->r_ctl.rc_sacklast;
7614 	for (i = 0; i < num_sack_blks; i++) {
7615 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7616 		if (acked) {
7617 			bbr->r_wanted_output = 1;
7618 			changed += acked;
7619 			sack_changed += acked;
7620 		}
7621 	}
7622 out:
7623 	*prev_acked = p_acked;
7624 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7625 		/*
7626 		 * Ok we have a high probability that we need to go in to
7627 		 * recovery since we have data sack'd
7628 		 */
7629 		struct bbr_sendmap *rsm;
7630 
7631 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7632 		if (rsm) {
7633 			/* Enter recovery */
7634 			entered_recovery = 1;
7635 			bbr->r_wanted_output = 1;
7636 			/*
7637 			 * When we enter recovery we need to assure we send
7638 			 * one packet.
7639 			 */
7640 			if (bbr->r_ctl.rc_resend == NULL) {
7641 				bbr->r_ctl.rc_resend = rsm;
7642 			}
7643 		}
7644 	}
7645 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7646 		/*
7647 		 * See if we need to rack-retransmit anything if so set it
7648 		 * up as the thing to resend assuming something else is not
7649 		 * already in that position.
7650 		 */
7651 		if (bbr->r_ctl.rc_resend == NULL) {
7652 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7653 		}
7654 	}
7655 	/*
7656 	 * We return the amount that changed via sack, this is used by the
7657 	 * ack-received code to augment what was changed between th_ack <->
7658 	 * snd_una.
7659 	 */
7660 	return (sack_changed);
7661 }
7662 
7663 static void
7664 bbr_strike_dupack(struct tcp_bbr *bbr)
7665 {
7666 	struct bbr_sendmap *rsm;
7667 
7668 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7669 	if (rsm && (rsm->r_dupack < 0xff)) {
7670 		rsm->r_dupack++;
7671 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7672 			bbr->r_wanted_output = 1;
7673 	}
7674 }
7675 
7676 /*
7677  * Return value of 1, we do not need to call bbr_process_data().
7678  * return value of 0, bbr_process_data can be called.
7679  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7680  * its unlocked and probably unsafe to touch the TCB.
7681  */
7682 static int
7683 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7684     struct tcpcb *tp, struct tcpopt *to,
7685     uint32_t tiwin, int32_t tlen,
7686     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7687 {
7688 	int32_t ourfinisacked = 0;
7689 	int32_t acked_amount;
7690 	uint16_t nsegs;
7691 	int32_t acked;
7692 	uint32_t lost, sack_changed = 0;
7693 	struct mbuf *mfree;
7694 	struct tcp_bbr *bbr;
7695 	uint32_t prev_acked = 0;
7696 
7697 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7698 	lost = bbr->r_ctl.rc_lost;
7699 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7700 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7701 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7702 		bbr->r_wanted_output = 1;
7703 		return (1);
7704 	}
7705 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7706 		/* Process the ack */
7707 		if (bbr->rc_in_persist)
7708 			tp->t_rxtshift = 0;
7709 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7710 			bbr_strike_dupack(bbr);
7711 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7712 	}
7713 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7714 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7715 		/*
7716 		 * Old ack, behind the last one rcv'd or a duplicate ack
7717 		 * with SACK info.
7718 		 */
7719 		if (th->th_ack == tp->snd_una) {
7720 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7721 			if (bbr->r_state == TCPS_SYN_SENT) {
7722 				/*
7723 				 * Special case on where we sent SYN. When
7724 				 * the SYN-ACK is processed in syn_sent
7725 				 * state it bumps the snd_una. This causes
7726 				 * us to hit here even though we did ack 1
7727 				 * byte.
7728 				 *
7729 				 * Go through the nothing left case so we
7730 				 * send data.
7731 				 */
7732 				goto nothing_left;
7733 			}
7734 		}
7735 		return (0);
7736 	}
7737 	/*
7738 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7739 	 * something we sent.
7740 	 */
7741 	if (tp->t_flags & TF_NEEDSYN) {
7742 		/*
7743 		 * T/TCP: Connection was half-synchronized, and our SYN has
7744 		 * been ACK'd (so connection is now fully synchronized).  Go
7745 		 * to non-starred state, increment snd_una for ACK of SYN,
7746 		 * and check if we can do window scaling.
7747 		 */
7748 		tp->t_flags &= ~TF_NEEDSYN;
7749 		tp->snd_una++;
7750 		/* Do window scaling? */
7751 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7752 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7753 			tp->rcv_scale = tp->request_r_scale;
7754 			/* Send window already scaled. */
7755 		}
7756 	}
7757 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7758 
7759 	acked = BYTES_THIS_ACK(tp, th);
7760 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7761 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7762 
7763 	/*
7764 	 * If we just performed our first retransmit, and the ACK arrives
7765 	 * within our recovery window, then it was a mistake to do the
7766 	 * retransmit in the first place.  Recover our original cwnd and
7767 	 * ssthresh, and proceed to transmit where we left off.
7768 	 */
7769 	if (tp->t_flags & TF_PREVVALID) {
7770 		tp->t_flags &= ~TF_PREVVALID;
7771 		if (tp->t_rxtshift == 1 &&
7772 		    (int)(ticks - tp->t_badrxtwin) < 0)
7773 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7774 	}
7775 	SOCKBUF_LOCK(&so->so_snd);
7776 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7777 	tp->snd_wnd -= acked_amount;
7778 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7779 	/* NB: sowwakeup_locked() does an implicit unlock. */
7780 	sowwakeup_locked(so);
7781 	m_freem(mfree);
7782 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7783 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7784 	}
7785 	tp->snd_una = th->th_ack;
7786 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7787 	if (IN_RECOVERY(tp->t_flags)) {
7788 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7789 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7790 			tcp_bbr_partialack(tp);
7791 		} else {
7792 			bbr_post_recovery(tp);
7793 		}
7794 	}
7795 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7796 		tp->snd_recover = tp->snd_una;
7797 	}
7798 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7799 		tp->snd_nxt = tp->snd_max;
7800 	}
7801 	if (tp->snd_una == tp->snd_max) {
7802 		/* Nothing left outstanding */
7803 nothing_left:
7804 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7805 		if (sbavail(&so->so_snd) == 0)
7806 			bbr->rc_tp->t_acktime = 0;
7807 		if ((sbused(&so->so_snd) == 0) &&
7808 		    (tp->t_flags & TF_SENTFIN)) {
7809 			ourfinisacked = 1;
7810 		}
7811 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7812 		if (bbr->rc_in_persist == 0) {
7813 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7814 		}
7815 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7816 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7817 		/*
7818 		 * We invalidate the last ack here since we
7819 		 * don't want to transfer forward the time
7820 		 * for our sum's calculations.
7821 		 */
7822 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7823 		    (sbavail(&so->so_snd) == 0) &&
7824 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7825 			/*
7826 			 * The socket was gone and the peer sent data, time
7827 			 * to reset him.
7828 			 */
7829 			*ret_val = 1;
7830 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7831 			/* tcp_close will kill the inp pre-log the Reset */
7832 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7833 			tp = tcp_close(tp);
7834 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7835 			BBR_STAT_INC(bbr_dropped_af_data);
7836 			return (1);
7837 		}
7838 		/* Set need output so persist might get set */
7839 		bbr->r_wanted_output = 1;
7840 	}
7841 	if (ofia)
7842 		*ofia = ourfinisacked;
7843 	return (0);
7844 }
7845 
7846 static void
7847 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7848 {
7849 	if (bbr->rc_in_persist == 0) {
7850 		bbr_timer_cancel(bbr, __LINE__, cts);
7851 		bbr->r_ctl.rc_last_delay_val = 0;
7852 		tp->t_rxtshift = 0;
7853 		bbr->rc_in_persist = 1;
7854 		bbr->r_ctl.rc_went_idle_time = cts;
7855 		/* We should be capped when rw went to 0 but just in case */
7856 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7857 		/* Time freezes for the state, so do the accounting now */
7858 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7859 			uint32_t time_in;
7860 
7861 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7862 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7863 				int32_t idx;
7864 
7865 				idx = bbr_state_val(bbr);
7866 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7867 			} else {
7868 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7869 			}
7870 		}
7871 		bbr->r_ctl.rc_bbr_state_time = cts;
7872 	}
7873 }
7874 
7875 static void
7876 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7877 {
7878 	/*
7879 	 * Note that if idle time does not exceed our
7880 	 * threshold, we do nothing continuing the state
7881 	 * transitions we were last walking through.
7882 	 */
7883 	if (idle_time >= bbr_idle_restart_threshold) {
7884 		if (bbr->rc_use_idle_restart) {
7885 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7886 			/*
7887 			 * Set our target using BBR_UNIT, so
7888 			 * we increase at a dramatic rate but
7889 			 * we stop when we get the pipe
7890 			 * full again for our current b/w estimate.
7891 			 */
7892 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7893 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7894 			bbr_set_state_target(bbr, __LINE__);
7895 			/* Now setup our gains to ramp up */
7896 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7897 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7898 			bbr_log_type_statechange(bbr, cts, __LINE__);
7899 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7900 			bbr_substate_change(bbr, cts, __LINE__, 1);
7901 		}
7902 	}
7903 }
7904 
7905 static void
7906 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7907 {
7908 	uint32_t idle_time;
7909 
7910 	if (bbr->rc_in_persist == 0)
7911 		return;
7912 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7913 	bbr->rc_in_persist = 0;
7914 	bbr->rc_hit_state_1 = 0;
7915 	bbr->r_ctl.rc_del_time = cts;
7916 	/*
7917 	 * We invalidate the last ack here since we
7918 	 * don't want to transfer forward the time
7919 	 * for our sum's calculations.
7920 	 */
7921 	if (tcp_in_hpts(bbr->rc_tp)) {
7922 		tcp_hpts_remove(bbr->rc_tp);
7923 		bbr->rc_timer_first = 0;
7924 		bbr->r_ctl.rc_hpts_flags = 0;
7925 		bbr->r_ctl.rc_last_delay_val = 0;
7926 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7927 		bbr->r_agg_early_set = 0;
7928 		bbr->r_ctl.rc_agg_early = 0;
7929 	}
7930 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7931 	if (idle_time >= bbr_rtt_probe_time) {
7932 		/*
7933 		 * This qualifies as a RTT_PROBE session since we drop the
7934 		 * data outstanding to nothing and waited more than
7935 		 * bbr_rtt_probe_time.
7936 		 */
7937 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7938 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7939 	}
7940 	tp->t_rxtshift = 0;
7941 	/*
7942 	 * If in probeBW and we have persisted more than an RTT lets do
7943 	 * special handling.
7944 	 */
7945 	/* Force a time based epoch */
7946 	bbr_set_epoch(bbr, cts, __LINE__);
7947 	/*
7948 	 * Setup the lost so we don't count anything against the guy
7949 	 * we have been stuck with during persists.
7950 	 */
7951 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7952 	/* Time un-freezes for the state */
7953 	bbr->r_ctl.rc_bbr_state_time = cts;
7954 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7955 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7956 		/*
7957 		 * If we are going back to probe-bw
7958 		 * or probe_rtt, we may need to possibly
7959 		 * do a fast restart.
7960 		 */
7961 		bbr_restart_after_idle(bbr, cts, idle_time);
7962 	}
7963 }
7964 
7965 static void
7966 bbr_collapsed_window(struct tcp_bbr *bbr)
7967 {
7968 	/*
7969 	 * Now we must walk the
7970 	 * send map and divide the
7971 	 * ones left stranded. These
7972 	 * guys can't cause us to abort
7973 	 * the connection and are really
7974 	 * "unsent". However if a buggy
7975 	 * client actually did keep some
7976 	 * of the data i.e. collapsed the win
7977 	 * and refused to ack and then opened
7978 	 * the win and acked that data. We would
7979 	 * get into an ack war, the simplier
7980 	 * method then of just pretending we
7981 	 * did not send those segments something
7982 	 * won't work.
7983 	 */
7984 	struct bbr_sendmap *rsm, *nrsm;
7985 	tcp_seq max_seq;
7986 	uint32_t maxseg;
7987 	int can_split = 0;
7988 	int fnd = 0;
7989 
7990 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
7991 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
7992 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
7993 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
7994 		/* Find the first seq past or at maxseq */
7995 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
7996 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
7997 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
7998 		    SEQ_GEQ(rsm->r_end, max_seq)) {
7999 			fnd = 1;
8000 			break;
8001 		}
8002 	}
8003 	bbr->rc_has_collapsed = 0;
8004 	if (!fnd) {
8005 		/* Nothing to do strange */
8006 		return;
8007 	}
8008 	/*
8009 	 * Now can we split?
8010 	 *
8011 	 * We don't want to split if splitting
8012 	 * would generate too many small segments
8013 	 * less we let an attacker fragment our
8014 	 * send_map and leave us out of memory.
8015 	 */
8016 	if ((max_seq != rsm->r_start) &&
8017 	    (max_seq != rsm->r_end)){
8018 		/* can we split? */
8019 		int res1, res2;
8020 
8021 		res1 = max_seq - rsm->r_start;
8022 		res2 = rsm->r_end - max_seq;
8023 		if ((res1 >= (maxseg/8)) &&
8024 		    (res2 >= (maxseg/8))) {
8025 			/* No small pieces here */
8026 			can_split = 1;
8027 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8028 			/* We are under the limit */
8029 			can_split = 1;
8030 		}
8031 	}
8032 	/* Ok do we need to split this rsm? */
8033 	if (max_seq == rsm->r_start) {
8034 		/* It's this guy no split required */
8035 		nrsm = rsm;
8036 	} else if (max_seq == rsm->r_end) {
8037 		/* It's the next one no split required. */
8038 		nrsm = TAILQ_NEXT(rsm, r_next);
8039 		if (nrsm == NULL) {
8040 			/* Huh? */
8041 			return;
8042 		}
8043 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8044 		/* yep we need to split it */
8045 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8046 		if (nrsm == NULL) {
8047 			/* failed XXXrrs what can we do mark the whole? */
8048 			nrsm = rsm;
8049 			goto no_split;
8050 		}
8051 		/* Clone it */
8052 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8053 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8054 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8055 		if (rsm->r_in_tmap) {
8056 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8057 			nrsm->r_in_tmap = 1;
8058 		}
8059 	} else {
8060 		/*
8061 		 * Split not allowed just start here just
8062 		 * use this guy.
8063 		 */
8064 		nrsm = rsm;
8065 	}
8066 no_split:
8067 	BBR_STAT_INC(bbr_collapsed_win);
8068 	/* reuse fnd as a count */
8069 	fnd = 0;
8070 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8071 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8072 		fnd++;
8073 		bbr->rc_has_collapsed = 1;
8074 	}
8075 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8076 }
8077 
8078 static void
8079 bbr_un_collapse_window(struct tcp_bbr *bbr)
8080 {
8081 	struct bbr_sendmap *rsm;
8082 	int cleared = 0;
8083 
8084 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8085 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8086 			/* Clear the flag */
8087 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8088 			cleared++;
8089 		} else
8090 			break;
8091 	}
8092 	bbr_log_type_rwnd_collapse(bbr,
8093 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8094 	bbr->rc_has_collapsed = 0;
8095 }
8096 
8097 /*
8098  * Return value of 1, the TCB is unlocked and most
8099  * likely gone, return value of 0, the TCB is still
8100  * locked.
8101  */
8102 static int
8103 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8104     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8105     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8106 {
8107 	/*
8108 	 * Update window information. Don't look at window if no ACK: TAC's
8109 	 * send garbage on first SYN.
8110 	 */
8111 	uint16_t nsegs;
8112 	int32_t tfo_syn;
8113 	struct tcp_bbr *bbr;
8114 
8115 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8116 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8117 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8118 	if ((thflags & TH_ACK) &&
8119 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8120 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8121 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8122 		/* keep track of pure window updates */
8123 		if (tlen == 0 &&
8124 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8125 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8126 		tp->snd_wnd = tiwin;
8127 		tp->snd_wl1 = th->th_seq;
8128 		tp->snd_wl2 = th->th_ack;
8129 		if (tp->snd_wnd > tp->max_sndwnd)
8130 			tp->max_sndwnd = tp->snd_wnd;
8131 		bbr->r_wanted_output = 1;
8132 	} else if (thflags & TH_ACK) {
8133 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8134 			tp->snd_wnd = tiwin;
8135 			tp->snd_wl1 = th->th_seq;
8136 			tp->snd_wl2 = th->th_ack;
8137 		}
8138 	}
8139 	if (tp->snd_wnd < ctf_outstanding(tp))
8140 		/* The peer collapsed its window on us */
8141 		bbr_collapsed_window(bbr);
8142  	else if (bbr->rc_has_collapsed)
8143 		bbr_un_collapse_window(bbr);
8144 	/* Was persist timer active and now we have window space? */
8145 	if ((bbr->rc_in_persist != 0) &&
8146 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8147 				bbr_minseg(bbr)))) {
8148 		/*
8149 		 * Make the rate persist at end of persist mode if idle long
8150 		 * enough
8151 		 */
8152 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8153 
8154 		/* Make sure we output to start the timer */
8155 		bbr->r_wanted_output = 1;
8156 	}
8157 	/* Do we need to enter persist? */
8158 	if ((bbr->rc_in_persist == 0) &&
8159 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8160 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8161 	    (tp->snd_max == tp->snd_una) &&
8162 	    sbavail(&so->so_snd) &&
8163 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8164 		/* No send window.. we must enter persist */
8165 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8166 	}
8167 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8168 		m_freem(m);
8169 		return (0);
8170 	}
8171 	/*
8172 	 * We don't support urgent data but
8173 	 * drag along the up just to make sure
8174 	 * if there is a stack switch no one
8175 	 * is surprised.
8176 	 */
8177 	tp->rcv_up = tp->rcv_nxt;
8178 
8179 	/*
8180 	 * Process the segment text, merging it into the TCP sequencing
8181 	 * queue, and arranging for acknowledgment of receipt if necessary.
8182 	 * This process logically involves adjusting tp->rcv_wnd as data is
8183 	 * presented to the user (this happens in tcp_usrreq.c, case
8184 	 * PRU_RCVD).  If a FIN has already been received on this connection
8185 	 * then we just ignore the text.
8186 	 */
8187 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8188 		   IS_FASTOPEN(tp->t_flags));
8189 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8190 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8191 		tcp_seq save_start = th->th_seq;
8192 		tcp_seq save_rnxt  = tp->rcv_nxt;
8193 		int     save_tlen  = tlen;
8194 
8195 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8196 		/*
8197 		 * Insert segment which includes th into TCP reassembly
8198 		 * queue with control block tp.  Set thflags to whether
8199 		 * reassembly now includes a segment with FIN.  This handles
8200 		 * the common case inline (segment is the next to be
8201 		 * received on an established connection, and the queue is
8202 		 * empty), avoiding linkage into and removal from the queue
8203 		 * and repetition of various conversions. Set DELACK for
8204 		 * segments received in order, but ack immediately when
8205 		 * segments are out of order (so fast retransmit can work).
8206 		 */
8207 		if (th->th_seq == tp->rcv_nxt &&
8208 		    SEGQ_EMPTY(tp) &&
8209 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8210 		    tfo_syn)) {
8211 #ifdef NETFLIX_SB_LIMITS
8212 			u_int mcnt, appended;
8213 
8214 			if (so->so_rcv.sb_shlim) {
8215 				mcnt = m_memcnt(m);
8216 				appended = 0;
8217 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8218 				    CFO_NOSLEEP, NULL) == false) {
8219 					counter_u64_add(tcp_sb_shlim_fails, 1);
8220 					m_freem(m);
8221 					return (0);
8222 				}
8223 			}
8224 
8225 #endif
8226 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8227 				bbr->bbr_segs_rcvd += max(1, nsegs);
8228 				tp->t_flags |= TF_DELACK;
8229 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8230 			} else {
8231 				bbr->r_wanted_output = 1;
8232 				tp->t_flags |= TF_ACKNOW;
8233 			}
8234 			tp->rcv_nxt += tlen;
8235 			if (tlen &&
8236 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8237 			    (tp->t_fbyte_in == 0)) {
8238 				tp->t_fbyte_in = ticks;
8239 				if (tp->t_fbyte_in == 0)
8240 					tp->t_fbyte_in = 1;
8241 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8242 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8243 			}
8244 			thflags = tcp_get_flags(th) & TH_FIN;
8245 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8246 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8247 			SOCKBUF_LOCK(&so->so_rcv);
8248 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8249 				m_freem(m);
8250 			else
8251 #ifdef NETFLIX_SB_LIMITS
8252 				appended =
8253 #endif
8254 					sbappendstream_locked(&so->so_rcv, m, 0);
8255 			/* NB: sorwakeup_locked() does an implicit unlock. */
8256 			sorwakeup_locked(so);
8257 #ifdef NETFLIX_SB_LIMITS
8258 			if (so->so_rcv.sb_shlim && appended != mcnt)
8259 				counter_fo_release(so->so_rcv.sb_shlim,
8260 				    mcnt - appended);
8261 #endif
8262 
8263 		} else {
8264 			/*
8265 			 * XXX: Due to the header drop above "th" is
8266 			 * theoretically invalid by now.  Fortunately
8267 			 * m_adj() doesn't actually frees any mbufs when
8268 			 * trimming from the head.
8269 			 */
8270 			tcp_seq temp = save_start;
8271 
8272 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8273 			tp->t_flags |= TF_ACKNOW;
8274 			if (tp->t_flags & TF_WAKESOR) {
8275 				tp->t_flags &= ~TF_WAKESOR;
8276 				/* NB: sorwakeup_locked() does an implicit unlock. */
8277 				sorwakeup_locked(so);
8278 			}
8279 		}
8280 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8281 		    (save_tlen > 0) &&
8282 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8283 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8284 				/*
8285 				 * DSACK actually handled in the fastpath
8286 				 * above.
8287 				 */
8288 				tcp_update_sack_list(tp, save_start,
8289 				    save_start + save_tlen);
8290 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8291 				if ((tp->rcv_numsacks >= 1) &&
8292 				    (tp->sackblks[0].end == save_start)) {
8293 					/*
8294 					 * Partial overlap, recorded at todrop
8295 					 * above.
8296 					 */
8297 					tcp_update_sack_list(tp,
8298 					    tp->sackblks[0].start,
8299 					    tp->sackblks[0].end);
8300 				} else {
8301 					tcp_update_dsack_list(tp, save_start,
8302 					    save_start + save_tlen);
8303 				}
8304 			} else if (tlen >= save_tlen) {
8305 				/* Update of sackblks. */
8306 				tcp_update_dsack_list(tp, save_start,
8307 				    save_start + save_tlen);
8308 			} else if (tlen > 0) {
8309 				tcp_update_dsack_list(tp, save_start,
8310 				    save_start + tlen);
8311 			}
8312 		}
8313 	} else {
8314 		m_freem(m);
8315 		thflags &= ~TH_FIN;
8316 	}
8317 
8318 	/*
8319 	 * If FIN is received ACK the FIN and let the user know that the
8320 	 * connection is closing.
8321 	 */
8322 	if (thflags & TH_FIN) {
8323 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8324 			/* The socket upcall is handled by socantrcvmore. */
8325 			socantrcvmore(so);
8326 			/*
8327 			 * If connection is half-synchronized (ie NEEDSYN
8328 			 * flag on) then delay ACK, so it may be piggybacked
8329 			 * when SYN is sent. Otherwise, since we received a
8330 			 * FIN then no more input can be expected, send ACK
8331 			 * now.
8332 			 */
8333 			if (tp->t_flags & TF_NEEDSYN) {
8334 				tp->t_flags |= TF_DELACK;
8335 				bbr_timer_cancel(bbr,
8336 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8337 			} else {
8338 				tp->t_flags |= TF_ACKNOW;
8339 			}
8340 			tp->rcv_nxt++;
8341 		}
8342 		switch (tp->t_state) {
8343 			/*
8344 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8345 			 * CLOSE_WAIT state.
8346 			 */
8347 		case TCPS_SYN_RECEIVED:
8348 			tp->t_starttime = ticks;
8349 			/* FALLTHROUGH */
8350 		case TCPS_ESTABLISHED:
8351 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8352 			break;
8353 
8354 			/*
8355 			 * If still in FIN_WAIT_1 STATE FIN has not been
8356 			 * acked so enter the CLOSING state.
8357 			 */
8358 		case TCPS_FIN_WAIT_1:
8359 			tcp_state_change(tp, TCPS_CLOSING);
8360 			break;
8361 
8362 			/*
8363 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8364 			 * starting the time-wait timer, turning off the
8365 			 * other standard timers.
8366 			 */
8367 		case TCPS_FIN_WAIT_2:
8368 			bbr->rc_timer_first = 1;
8369 			bbr_timer_cancel(bbr,
8370 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8371 			tcp_twstart(tp);
8372 			return (1);
8373 		}
8374 	}
8375 	/*
8376 	 * Return any desired output.
8377 	 */
8378 	if ((tp->t_flags & TF_ACKNOW) ||
8379 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8380 		bbr->r_wanted_output = 1;
8381 	}
8382 	return (0);
8383 }
8384 
8385 /*
8386  * Here nothing is really faster, its just that we
8387  * have broken out the fast-data path also just like
8388  * the fast-ack. Return 1 if we processed the packet
8389  * return 0 if you need to take the "slow-path".
8390  */
8391 static int
8392 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8393     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8394     uint32_t tiwin, int32_t nxt_pkt)
8395 {
8396 	uint16_t nsegs;
8397 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8398 	struct tcp_bbr *bbr;
8399 #ifdef NETFLIX_SB_LIMITS
8400 	u_int mcnt, appended;
8401 #endif
8402 
8403 	/* On the hpts and we would have called output */
8404 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8405 
8406 	/*
8407 	 * If last ACK falls within this segment's sequence numbers, record
8408 	 * the timestamp. NOTE that the test is modified according to the
8409 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8410 	 */
8411 	if (bbr->r_ctl.rc_resend != NULL) {
8412 		return (0);
8413 	}
8414 	if (tiwin && tiwin != tp->snd_wnd) {
8415 		return (0);
8416 	}
8417 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8418 		return (0);
8419 	}
8420 	if (__predict_false((to->to_flags & TOF_TS) &&
8421 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8422 		return (0);
8423 	}
8424 	if (__predict_false((th->th_ack != tp->snd_una))) {
8425 		return (0);
8426 	}
8427 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8428 		return (0);
8429 	}
8430 	if ((to->to_flags & TOF_TS) != 0 &&
8431 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8432 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8433 		tp->ts_recent = to->to_tsval;
8434 	}
8435 	/*
8436 	 * This is a pure, in-sequence data packet with nothing on the
8437 	 * reassembly queue and we have enough buffer space to take it.
8438 	 */
8439 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8440 
8441 #ifdef NETFLIX_SB_LIMITS
8442 	if (so->so_rcv.sb_shlim) {
8443 		mcnt = m_memcnt(m);
8444 		appended = 0;
8445 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8446 		    CFO_NOSLEEP, NULL) == false) {
8447 			counter_u64_add(tcp_sb_shlim_fails, 1);
8448 			m_freem(m);
8449 			return (1);
8450 		}
8451 	}
8452 #endif
8453 	/* Clean receiver SACK report if present */
8454 	if (tp->rcv_numsacks)
8455 		tcp_clean_sackreport(tp);
8456 	KMOD_TCPSTAT_INC(tcps_preddat);
8457 	tp->rcv_nxt += tlen;
8458 	if (tlen &&
8459 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8460 	    (tp->t_fbyte_in == 0)) {
8461 		tp->t_fbyte_in = ticks;
8462 		if (tp->t_fbyte_in == 0)
8463 			tp->t_fbyte_in = 1;
8464 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8465 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8466 	}
8467 	/*
8468 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8469 	 */
8470 	tp->snd_wl1 = th->th_seq;
8471 	/*
8472 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8473 	 */
8474 	tp->rcv_up = tp->rcv_nxt;
8475 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8476 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8477 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8478 
8479 	/* Add data to socket buffer. */
8480 	SOCKBUF_LOCK(&so->so_rcv);
8481 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8482 		m_freem(m);
8483 	} else {
8484 		/*
8485 		 * Set new socket buffer size. Give up when limit is
8486 		 * reached.
8487 		 */
8488 		if (newsize)
8489 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8490 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8491 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8492 
8493 #ifdef NETFLIX_SB_LIMITS
8494 		appended =
8495 #endif
8496 			sbappendstream_locked(&so->so_rcv, m, 0);
8497 		ctf_calc_rwin(so, tp);
8498 	}
8499 	/* NB: sorwakeup_locked() does an implicit unlock. */
8500 	sorwakeup_locked(so);
8501 #ifdef NETFLIX_SB_LIMITS
8502 	if (so->so_rcv.sb_shlim && mcnt != appended)
8503 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8504 #endif
8505 	if (DELAY_ACK(tp, bbr, nsegs)) {
8506 		bbr->bbr_segs_rcvd += max(1, nsegs);
8507 		tp->t_flags |= TF_DELACK;
8508 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8509 	} else {
8510 		bbr->r_wanted_output = 1;
8511 		tp->t_flags |= TF_ACKNOW;
8512 	}
8513 	return (1);
8514 }
8515 
8516 /*
8517  * This subfunction is used to try to highly optimize the
8518  * fast path. We again allow window updates that are
8519  * in sequence to remain in the fast-path. We also add
8520  * in the __predict's to attempt to help the compiler.
8521  * Note that if we return a 0, then we can *not* process
8522  * it and the caller should push the packet into the
8523  * slow-path. If we return 1, then all is well and
8524  * the packet is fully processed.
8525  */
8526 static int
8527 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8528     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8529     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8530 {
8531 	int32_t acked;
8532 	uint16_t nsegs;
8533 	uint32_t sack_changed;
8534 	uint32_t prev_acked = 0;
8535 	struct tcp_bbr *bbr;
8536 
8537 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8538 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8539 		return (0);
8540 	}
8541 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8542 		/* Above what we have sent? */
8543 		return (0);
8544 	}
8545 	if (__predict_false(tiwin == 0)) {
8546 		/* zero window */
8547 		return (0);
8548 	}
8549 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8550 		/* We need a SYN or a FIN, unlikely.. */
8551 		return (0);
8552 	}
8553 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8554 		/* Timestamp is behind .. old ack with seq wrap? */
8555 		return (0);
8556 	}
8557 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8558 		/* Still recovering */
8559 		return (0);
8560 	}
8561 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8562 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8563 		/* We are retransmitting */
8564 		return (0);
8565 	}
8566 	if (__predict_false(bbr->rc_in_persist != 0)) {
8567 		/* In persist mode */
8568 		return (0);
8569 	}
8570 	if (bbr->r_ctl.rc_sacked) {
8571 		/* We have sack holes on our scoreboard */
8572 		return (0);
8573 	}
8574 	/* Ok if we reach here, we can process a fast-ack */
8575 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8576 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8577 	/*
8578 	 * We never detect loss in fast ack [we can't
8579 	 * have a sack and can't be in recovery so
8580 	 * we always pass 0 (nothing detected)].
8581 	 */
8582 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8583 	/* Did the window get updated? */
8584 	if (tiwin != tp->snd_wnd) {
8585 		tp->snd_wnd = tiwin;
8586 		tp->snd_wl1 = th->th_seq;
8587 		if (tp->snd_wnd > tp->max_sndwnd)
8588 			tp->max_sndwnd = tp->snd_wnd;
8589 	}
8590 	/* Do we need to exit persists? */
8591 	if ((bbr->rc_in_persist != 0) &&
8592 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8593 			       bbr_minseg(bbr)))) {
8594 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8595 		bbr->r_wanted_output = 1;
8596 	}
8597 	/* Do we need to enter persists? */
8598 	if ((bbr->rc_in_persist == 0) &&
8599 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8600 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8601 	    (tp->snd_max == tp->snd_una) &&
8602 	    sbavail(&so->so_snd) &&
8603 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8604 		/* No send window.. we must enter persist */
8605 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8606 	}
8607 	/*
8608 	 * If last ACK falls within this segment's sequence numbers, record
8609 	 * the timestamp. NOTE that the test is modified according to the
8610 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8611 	 */
8612 	if ((to->to_flags & TOF_TS) != 0 &&
8613 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8614 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8615 		tp->ts_recent = to->to_tsval;
8616 	}
8617 	/*
8618 	 * This is a pure ack for outstanding data.
8619 	 */
8620 	KMOD_TCPSTAT_INC(tcps_predack);
8621 
8622 	/*
8623 	 * "bad retransmit" recovery.
8624 	 */
8625 	if (tp->t_flags & TF_PREVVALID) {
8626 		tp->t_flags &= ~TF_PREVVALID;
8627 		if (tp->t_rxtshift == 1 &&
8628 		    (int)(ticks - tp->t_badrxtwin) < 0)
8629 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8630 	}
8631 	/*
8632 	 * Recalculate the transmit timer / rtt.
8633 	 *
8634 	 * Some boxes send broken timestamp replies during the SYN+ACK
8635 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8636 	 * and blow up the retransmit timer.
8637 	 */
8638 	acked = BYTES_THIS_ACK(tp, th);
8639 
8640 #ifdef TCP_HHOOK
8641 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8642 	hhook_run_tcp_est_in(tp, th, to);
8643 #endif
8644 
8645 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8646 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8647 	sbdrop(&so->so_snd, acked);
8648 
8649 	if (SEQ_GT(th->th_ack, tp->snd_una))
8650 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8651 	tp->snd_una = th->th_ack;
8652 	if (tp->snd_wnd < ctf_outstanding(tp))
8653 		/* The peer collapsed its window on us */
8654 		bbr_collapsed_window(bbr);
8655 	else if (bbr->rc_has_collapsed)
8656 		bbr_un_collapse_window(bbr);
8657 
8658 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8659 		tp->snd_recover = tp->snd_una;
8660 	}
8661 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8662 	/*
8663 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8664 	 */
8665 	tp->snd_wl2 = th->th_ack;
8666 	m_freem(m);
8667 	/*
8668 	 * If all outstanding data are acked, stop retransmit timer,
8669 	 * otherwise restart timer using current (possibly backed-off)
8670 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8671 	 * If data are ready to send, let tcp_output decide between more
8672 	 * output or persist.
8673 	 * Wake up the socket if we have room to write more.
8674 	 */
8675 	sowwakeup(so);
8676 	if (tp->snd_una == tp->snd_max) {
8677 		/* Nothing left outstanding */
8678 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8679 		if (sbavail(&so->so_snd) == 0)
8680 			bbr->rc_tp->t_acktime = 0;
8681 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8682 		if (bbr->rc_in_persist == 0) {
8683 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8684 		}
8685 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8686 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8687 		/*
8688 		 * We invalidate the last ack here since we
8689 		 * don't want to transfer forward the time
8690 		 * for our sum's calculations.
8691 		 */
8692 		bbr->r_wanted_output = 1;
8693 	}
8694 	if (sbavail(&so->so_snd)) {
8695 		bbr->r_wanted_output = 1;
8696 	}
8697 	return (1);
8698 }
8699 
8700 /*
8701  * Return value of 1, the TCB is unlocked and most
8702  * likely gone, return value of 0, the TCB is still
8703  * locked.
8704  */
8705 static int
8706 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8707     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8708     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8709 {
8710 	int32_t todrop;
8711 	int32_t ourfinisacked = 0;
8712 	struct tcp_bbr *bbr;
8713 	int32_t ret_val = 0;
8714 
8715 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8716 
8717 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8718 	ctf_calc_rwin(so, tp);
8719 	/*
8720 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8721 	 * SYN, drop the input. if seg contains a RST, then drop the
8722 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8723 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8724 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8725 	 * not support ECN so we will not say we are capable. if SYN has
8726 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8727 	 * segment to be acked (eventually) continue processing rest of
8728 	 * data/controls, beginning with URG
8729 	 */
8730 	if ((thflags & TH_ACK) &&
8731 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8732 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8733 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8734 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8735 		return (1);
8736 	}
8737 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8738 		TCP_PROBE5(connect__refused, NULL, tp,
8739 		    mtod(m, const char *), tp, th);
8740 		tp = tcp_drop(tp, ECONNREFUSED);
8741 		ctf_do_drop(m, tp);
8742 		return (1);
8743 	}
8744 	if (thflags & TH_RST) {
8745 		ctf_do_drop(m, tp);
8746 		return (1);
8747 	}
8748 	if (!(thflags & TH_SYN)) {
8749 		ctf_do_drop(m, tp);
8750 		return (1);
8751 	}
8752 	tp->irs = th->th_seq;
8753 	tcp_rcvseqinit(tp);
8754 	if (thflags & TH_ACK) {
8755 		int tfo_partial = 0;
8756 
8757 		KMOD_TCPSTAT_INC(tcps_connects);
8758 		soisconnected(so);
8759 #ifdef MAC
8760 		mac_socketpeer_set_from_mbuf(m, so);
8761 #endif
8762 		/* Do window scaling on this connection? */
8763 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8764 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8765 			tp->rcv_scale = tp->request_r_scale;
8766 		}
8767 		tp->rcv_adv += min(tp->rcv_wnd,
8768 		    TCP_MAXWIN << tp->rcv_scale);
8769 		/*
8770 		 * If not all the data that was sent in the TFO SYN
8771 		 * has been acked, resend the remainder right away.
8772 		 */
8773 		if (IS_FASTOPEN(tp->t_flags) &&
8774 		    (tp->snd_una != tp->snd_max)) {
8775 			tp->snd_nxt = th->th_ack;
8776 			tfo_partial = 1;
8777 		}
8778 		/*
8779 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8780 		 * will be turned on later.
8781 		 */
8782 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8783 			bbr->bbr_segs_rcvd += 1;
8784 			tp->t_flags |= TF_DELACK;
8785 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8786 		} else {
8787 			bbr->r_wanted_output = 1;
8788 			tp->t_flags |= TF_ACKNOW;
8789 		}
8790 		if (SEQ_GT(th->th_ack, tp->iss)) {
8791 			/*
8792 			 * The SYN is acked
8793 			 * handle it specially.
8794 			 */
8795 			bbr_log_syn(tp, to);
8796 		}
8797 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8798 			/*
8799 			 * We advance snd_una for the
8800 			 * fast open case. If th_ack is
8801 			 * acknowledging data beyond
8802 			 * snd_una we can't just call
8803 			 * ack-processing since the
8804 			 * data stream in our send-map
8805 			 * will start at snd_una + 1 (one
8806 			 * beyond the SYN). If its just
8807 			 * equal we don't need to do that
8808 			 * and there is no send_map.
8809 			 */
8810 			tp->snd_una++;
8811 		}
8812 		/*
8813 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8814 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8815 		 */
8816 		tp->t_starttime = ticks;
8817 		if (tp->t_flags & TF_NEEDFIN) {
8818 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8819 			tp->t_flags &= ~TF_NEEDFIN;
8820 			thflags &= ~TH_SYN;
8821 		} else {
8822 			tcp_state_change(tp, TCPS_ESTABLISHED);
8823 			TCP_PROBE5(connect__established, NULL, tp,
8824 			    mtod(m, const char *), tp, th);
8825 			cc_conn_init(tp);
8826 		}
8827 	} else {
8828 		/*
8829 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8830 		 * open.  If segment contains CC option and there is a
8831 		 * cached CC, apply TAO test. If it succeeds, connection is *
8832 		 * half-synchronized. Otherwise, do 3-way handshake:
8833 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8834 		 * there was no CC option, clear cached CC value.
8835 		 */
8836 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
8837 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8838 	}
8839 	/*
8840 	 * Advance th->th_seq to correspond to first data byte. If data,
8841 	 * trim to stay within window, dropping FIN if necessary.
8842 	 */
8843 	th->th_seq++;
8844 	if (tlen > tp->rcv_wnd) {
8845 		todrop = tlen - tp->rcv_wnd;
8846 		m_adj(m, -todrop);
8847 		tlen = tp->rcv_wnd;
8848 		thflags &= ~TH_FIN;
8849 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8850 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8851 	}
8852 	tp->snd_wl1 = th->th_seq - 1;
8853 	tp->rcv_up = th->th_seq;
8854 	/*
8855 	 * Client side of transaction: already sent SYN and data. If the
8856 	 * remote host used T/TCP to validate the SYN, our data will be
8857 	 * ACK'd; if so, enter normal data segment processing in the middle
8858 	 * of step 5, ack processing. Otherwise, goto step 6.
8859 	 */
8860 	if (thflags & TH_ACK) {
8861 		if ((to->to_flags & TOF_TS) != 0) {
8862 			uint32_t t, rtt;
8863 
8864 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8865 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8866 				rtt = t - to->to_tsecr;
8867 				if (rtt == 0) {
8868 					rtt = 1;
8869 				}
8870 				rtt *= MS_IN_USEC;
8871 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8872 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8873 						       rtt, bbr->r_ctl.rc_rcvtime);
8874 			}
8875 		}
8876 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8877 			return (ret_val);
8878 		/* We may have changed to FIN_WAIT_1 above */
8879 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8880 			/*
8881 			 * In FIN_WAIT_1 STATE in addition to the processing
8882 			 * for the ESTABLISHED state if our FIN is now
8883 			 * acknowledged then enter FIN_WAIT_2.
8884 			 */
8885 			if (ourfinisacked) {
8886 				/*
8887 				 * If we can't receive any more data, then
8888 				 * closing user can proceed. Starting the
8889 				 * timer is contrary to the specification,
8890 				 * but if we don't get a FIN we'll hang
8891 				 * forever.
8892 				 *
8893 				 * XXXjl: we should release the tp also, and
8894 				 * use a compressed state.
8895 				 */
8896 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8897 					soisdisconnected(so);
8898 					tcp_timer_activate(tp, TT_2MSL,
8899 					    (tcp_fast_finwait2_recycle ?
8900 					    tcp_finwait2_timeout :
8901 					    TP_MAXIDLE(tp)));
8902 				}
8903 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8904 			}
8905 		}
8906 	}
8907 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8908 	    tiwin, thflags, nxt_pkt));
8909 }
8910 
8911 /*
8912  * Return value of 1, the TCB is unlocked and most
8913  * likely gone, return value of 0, the TCB is still
8914  * locked.
8915  */
8916 static int
8917 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8918 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8919 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8920 {
8921 	int32_t ourfinisacked = 0;
8922 	int32_t ret_val;
8923 	struct tcp_bbr *bbr;
8924 
8925 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8926 
8927 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8928 	ctf_calc_rwin(so, tp);
8929 	if ((thflags & TH_RST) ||
8930 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
8931 		return (ctf_process_rst(m, th, so, tp));
8932 	if ((thflags & TH_ACK) &&
8933 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8934 	     SEQ_GT(th->th_ack, tp->snd_max))) {
8935 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8936 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8937 		return (1);
8938 	}
8939 	if (IS_FASTOPEN(tp->t_flags)) {
8940 		/*
8941 		 * When a TFO connection is in SYN_RECEIVED, the only valid
8942 		 * packets are the initial SYN, a retransmit/copy of the
8943 		 * initial SYN (possibly with a subset of the original
8944 		 * data), a valid ACK, a FIN, or a RST.
8945 		 */
8946 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
8947 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8948 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8949 			return (1);
8950 		} else if (thflags & TH_SYN) {
8951 			/* non-initial SYN is ignored */
8952 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
8953 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
8954 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
8955 				ctf_do_drop(m, NULL);
8956 				return (0);
8957 			}
8958 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
8959 			ctf_do_drop(m, NULL);
8960 			return (0);
8961 		}
8962 	}
8963 	/*
8964 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
8965 	 * it's less than ts_recent, drop it.
8966 	 */
8967 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
8968 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
8969 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
8970 			return (ret_val);
8971 	}
8972 	/*
8973 	 * In the SYN-RECEIVED state, validate that the packet belongs to
8974 	 * this connection before trimming the data to fit the receive
8975 	 * window.  Check the sequence number versus IRS since we know the
8976 	 * sequence numbers haven't wrapped.  This is a partial fix for the
8977 	 * "LAND" DoS attack.
8978 	 */
8979 	if (SEQ_LT(th->th_seq, tp->irs)) {
8980 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8981 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8982 		return (1);
8983 	}
8984 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
8985 		return (ret_val);
8986 	}
8987 	/*
8988 	 * If last ACK falls within this segment's sequence numbers, record
8989 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
8990 	 * from the latest proposal of the tcplw@cray.com list (Braden
8991 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
8992 	 * with our earlier PAWS tests, so this check should be solely
8993 	 * predicated on the sequence space of this segment. 3) That we
8994 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
8995 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
8996 	 * SEG.Len, This modified check allows us to overcome RFC1323's
8997 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
8998 	 * p.869. In such cases, we can still calculate the RTT correctly
8999 	 * when RCV.NXT == Last.ACK.Sent.
9000 	 */
9001 	if ((to->to_flags & TOF_TS) != 0 &&
9002 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9003 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9004 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9005 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9006 		tp->ts_recent = to->to_tsval;
9007 	}
9008 	tp->snd_wnd = tiwin;
9009 	/*
9010 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9011 	 * is on (half-synchronized state), then queue data for later
9012 	 * processing; else drop segment and return.
9013 	 */
9014 	if ((thflags & TH_ACK) == 0) {
9015 		if (IS_FASTOPEN(tp->t_flags)) {
9016 			cc_conn_init(tp);
9017 		}
9018 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9019 					 tiwin, thflags, nxt_pkt));
9020 	}
9021 	KMOD_TCPSTAT_INC(tcps_connects);
9022 	if (tp->t_flags & TF_SONOTCONN) {
9023 		tp->t_flags &= ~TF_SONOTCONN;
9024 		soisconnected(so);
9025 	}
9026 	/* Do window scaling? */
9027 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9028 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9029 		tp->rcv_scale = tp->request_r_scale;
9030 	}
9031 	/*
9032 	 * ok for the first time in lets see if we can use the ts to figure
9033 	 * out what the initial RTT was.
9034 	 */
9035 	if ((to->to_flags & TOF_TS) != 0) {
9036 		uint32_t t, rtt;
9037 
9038 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9039 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9040 			rtt = t - to->to_tsecr;
9041 			if (rtt == 0) {
9042 				rtt = 1;
9043 			}
9044 			rtt *= MS_IN_USEC;
9045 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9046 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9047 		}
9048 	}
9049 	/* Drop off any SYN in the send map (probably not there)  */
9050 	if (thflags & TH_ACK)
9051 		bbr_log_syn(tp, to);
9052 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9053 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9054 		tp->t_tfo_pending = NULL;
9055 	}
9056 	/*
9057 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9058 	 * FIN-WAIT-1
9059 	 */
9060 	tp->t_starttime = ticks;
9061 	if (tp->t_flags & TF_NEEDFIN) {
9062 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9063 		tp->t_flags &= ~TF_NEEDFIN;
9064 	} else {
9065 		tcp_state_change(tp, TCPS_ESTABLISHED);
9066 		TCP_PROBE5(accept__established, NULL, tp,
9067 			   mtod(m, const char *), tp, th);
9068 		/*
9069 		 * TFO connections call cc_conn_init() during SYN
9070 		 * processing.  Calling it again here for such connections
9071 		 * is not harmless as it would undo the snd_cwnd reduction
9072 		 * that occurs when a TFO SYN|ACK is retransmitted.
9073 		 */
9074 		if (!IS_FASTOPEN(tp->t_flags))
9075 			cc_conn_init(tp);
9076 	}
9077 	/*
9078 	 * Account for the ACK of our SYN prior to
9079 	 * regular ACK processing below, except for
9080 	 * simultaneous SYN, which is handled later.
9081 	 */
9082 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9083 		tp->snd_una++;
9084 	/*
9085 	 * If segment contains data or ACK, will call tcp_reass() later; if
9086 	 * not, do so now to pass queued data to user.
9087 	 */
9088 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9089 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9090 			(struct mbuf *)0);
9091 		if (tp->t_flags & TF_WAKESOR) {
9092 			tp->t_flags &= ~TF_WAKESOR;
9093 			/* NB: sorwakeup_locked() does an implicit unlock. */
9094 			sorwakeup_locked(so);
9095 		}
9096 	}
9097 	tp->snd_wl1 = th->th_seq - 1;
9098 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9099 		return (ret_val);
9100 	}
9101 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9102 		/* We could have went to FIN_WAIT_1 (or EST) above */
9103 		/*
9104 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9105 		 * ESTABLISHED state if our FIN is now acknowledged then
9106 		 * enter FIN_WAIT_2.
9107 		 */
9108 		if (ourfinisacked) {
9109 			/*
9110 			 * If we can't receive any more data, then closing
9111 			 * user can proceed. Starting the timer is contrary
9112 			 * to the specification, but if we don't get a FIN
9113 			 * we'll hang forever.
9114 			 *
9115 			 * XXXjl: we should release the tp also, and use a
9116 			 * compressed state.
9117 			 */
9118 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9119 				soisdisconnected(so);
9120 				tcp_timer_activate(tp, TT_2MSL,
9121 						   (tcp_fast_finwait2_recycle ?
9122 						    tcp_finwait2_timeout :
9123 						    TP_MAXIDLE(tp)));
9124 			}
9125 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9126 		}
9127 	}
9128 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9129 				 tiwin, thflags, nxt_pkt));
9130 }
9131 
9132 /*
9133  * Return value of 1, the TCB is unlocked and most
9134  * likely gone, return value of 0, the TCB is still
9135  * locked.
9136  */
9137 static int
9138 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9139     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9140     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9141 {
9142 	struct tcp_bbr *bbr;
9143 	int32_t ret_val;
9144 
9145 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9146 
9147 	/*
9148 	 * Header prediction: check for the two common cases of a
9149 	 * uni-directional data xfer.  If the packet has no control flags,
9150 	 * is in-sequence, the window didn't change and we're not
9151 	 * retransmitting, it's a candidate.  If the length is zero and the
9152 	 * ack moved forward, we're the sender side of the xfer.  Just free
9153 	 * the data acked & wake any higher level process that was blocked
9154 	 * waiting for space.  If the length is non-zero and the ack didn't
9155 	 * move, we're the receiver side.  If we're getting packets in-order
9156 	 * (the reassembly queue is empty), add the data toc The socket
9157 	 * buffer and note that we need a delayed ack. Make sure that the
9158 	 * hidden state-flags are also off. Since we check for
9159 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9160 	 */
9161 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9162 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9163 		/*
9164 		 * If we have delived under 4 segments increase the initial
9165 		 * window if raised by the peer. We use this to determine
9166 		 * dynamic and static rwnd's at the end of a connection.
9167 		 */
9168 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9169 	}
9170 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9171 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9172 	    __predict_true(SEGQ_EMPTY(tp)) &&
9173 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9174 		if (tlen == 0) {
9175 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9176 			    tiwin, nxt_pkt, iptos)) {
9177 				return (0);
9178 			}
9179 		} else {
9180 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9181 			    tiwin, nxt_pkt)) {
9182 				return (0);
9183 			}
9184 		}
9185 	}
9186 	ctf_calc_rwin(so, tp);
9187 
9188 	if ((thflags & TH_RST) ||
9189 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9190 		return (ctf_process_rst(m, th, so, tp));
9191 	/*
9192 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9193 	 * synchronized state.
9194 	 */
9195 	if (thflags & TH_SYN) {
9196 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9197 		return (ret_val);
9198 	}
9199 	/*
9200 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9201 	 * it's less than ts_recent, drop it.
9202 	 */
9203 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9204 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9205 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9206 			return (ret_val);
9207 	}
9208 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9209 		return (ret_val);
9210 	}
9211 	/*
9212 	 * If last ACK falls within this segment's sequence numbers, record
9213 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9214 	 * from the latest proposal of the tcplw@cray.com list (Braden
9215 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9216 	 * with our earlier PAWS tests, so this check should be solely
9217 	 * predicated on the sequence space of this segment. 3) That we
9218 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9219 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9220 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9221 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9222 	 * p.869. In such cases, we can still calculate the RTT correctly
9223 	 * when RCV.NXT == Last.ACK.Sent.
9224 	 */
9225 	if ((to->to_flags & TOF_TS) != 0 &&
9226 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9227 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9228 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9229 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9230 		tp->ts_recent = to->to_tsval;
9231 	}
9232 	/*
9233 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9234 	 * is on (half-synchronized state), then queue data for later
9235 	 * processing; else drop segment and return.
9236 	 */
9237 	if ((thflags & TH_ACK) == 0) {
9238 		if (tp->t_flags & TF_NEEDSYN) {
9239 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9240 			    tiwin, thflags, nxt_pkt));
9241 		} else if (tp->t_flags & TF_ACKNOW) {
9242 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9243 			bbr->r_wanted_output = 1;
9244 			return (ret_val);
9245 		} else {
9246 			ctf_do_drop(m, NULL);
9247 			return (0);
9248 		}
9249 	}
9250 	/*
9251 	 * Ack processing.
9252 	 */
9253 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9254 		return (ret_val);
9255 	}
9256 	if (sbavail(&so->so_snd)) {
9257 		if (ctf_progress_timeout_check(tp, true)) {
9258 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9259 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9260 			return (1);
9261 		}
9262 	}
9263 	/* State changes only happen in bbr_process_data() */
9264 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9265 	    tiwin, thflags, nxt_pkt));
9266 }
9267 
9268 /*
9269  * Return value of 1, the TCB is unlocked and most
9270  * likely gone, return value of 0, the TCB is still
9271  * locked.
9272  */
9273 static int
9274 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9275     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9276     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9277 {
9278 	struct tcp_bbr *bbr;
9279 	int32_t ret_val;
9280 
9281 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9282 
9283 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9284 	ctf_calc_rwin(so, tp);
9285 	if ((thflags & TH_RST) ||
9286 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9287 		return (ctf_process_rst(m, th, so, tp));
9288 	/*
9289 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9290 	 * synchronized state.
9291 	 */
9292 	if (thflags & TH_SYN) {
9293 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9294 		return (ret_val);
9295 	}
9296 	/*
9297 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9298 	 * it's less than ts_recent, drop it.
9299 	 */
9300 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9301 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9302 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9303 			return (ret_val);
9304 	}
9305 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9306 		return (ret_val);
9307 	}
9308 	/*
9309 	 * If last ACK falls within this segment's sequence numbers, record
9310 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9311 	 * from the latest proposal of the tcplw@cray.com list (Braden
9312 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9313 	 * with our earlier PAWS tests, so this check should be solely
9314 	 * predicated on the sequence space of this segment. 3) That we
9315 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9316 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9317 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9318 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9319 	 * p.869. In such cases, we can still calculate the RTT correctly
9320 	 * when RCV.NXT == Last.ACK.Sent.
9321 	 */
9322 	if ((to->to_flags & TOF_TS) != 0 &&
9323 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9324 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9325 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9326 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9327 		tp->ts_recent = to->to_tsval;
9328 	}
9329 	/*
9330 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9331 	 * is on (half-synchronized state), then queue data for later
9332 	 * processing; else drop segment and return.
9333 	 */
9334 	if ((thflags & TH_ACK) == 0) {
9335 		if (tp->t_flags & TF_NEEDSYN) {
9336 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9337 			    tiwin, thflags, nxt_pkt));
9338 		} else if (tp->t_flags & TF_ACKNOW) {
9339 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9340 			bbr->r_wanted_output = 1;
9341 			return (ret_val);
9342 		} else {
9343 			ctf_do_drop(m, NULL);
9344 			return (0);
9345 		}
9346 	}
9347 	/*
9348 	 * Ack processing.
9349 	 */
9350 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9351 		return (ret_val);
9352 	}
9353 	if (sbavail(&so->so_snd)) {
9354 		if (ctf_progress_timeout_check(tp, true)) {
9355 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9356 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9357 			return (1);
9358 		}
9359 	}
9360 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9361 	    tiwin, thflags, nxt_pkt));
9362 }
9363 
9364 static int
9365 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9366     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9367 {
9368 
9369 	if (bbr->rc_allow_data_af_clo == 0) {
9370 close_now:
9371 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9372 		/* tcp_close will kill the inp pre-log the Reset */
9373 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9374 		tp = tcp_close(tp);
9375 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9376 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9377 		return (1);
9378 	}
9379 	if (sbavail(&so->so_snd) == 0)
9380 		goto close_now;
9381 	/* Ok we allow data that is ignored and a followup reset */
9382 	tp->rcv_nxt = th->th_seq + *tlen;
9383 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9384 	bbr->r_wanted_output = 1;
9385 	*tlen = 0;
9386 	return (0);
9387 }
9388 
9389 /*
9390  * Return value of 1, the TCB is unlocked and most
9391  * likely gone, return value of 0, the TCB is still
9392  * locked.
9393  */
9394 static int
9395 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9396     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9397     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9398 {
9399 	int32_t ourfinisacked = 0;
9400 	int32_t ret_val;
9401 	struct tcp_bbr *bbr;
9402 
9403 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9404 
9405 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9406 	ctf_calc_rwin(so, tp);
9407 	if ((thflags & TH_RST) ||
9408 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9409 		return (ctf_process_rst(m, th, so, tp));
9410 	/*
9411 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9412 	 * synchronized state.
9413 	 */
9414 	if (thflags & TH_SYN) {
9415 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9416 		return (ret_val);
9417 	}
9418 	/*
9419 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9420 	 * it's less than ts_recent, drop it.
9421 	 */
9422 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9423 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9424 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9425 			return (ret_val);
9426 	}
9427 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9428 		return (ret_val);
9429 	}
9430 	/*
9431 	 * If new data are received on a connection after the user processes
9432 	 * are gone, then RST the other end.
9433 	 * We call a new function now so we might continue and setup
9434 	 * to reset at all data being ack'd.
9435 	 */
9436 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9437 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9438 		return (1);
9439 	/*
9440 	 * If last ACK falls within this segment's sequence numbers, record
9441 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9442 	 * from the latest proposal of the tcplw@cray.com list (Braden
9443 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9444 	 * with our earlier PAWS tests, so this check should be solely
9445 	 * predicated on the sequence space of this segment. 3) That we
9446 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9447 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9448 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9449 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9450 	 * p.869. In such cases, we can still calculate the RTT correctly
9451 	 * when RCV.NXT == Last.ACK.Sent.
9452 	 */
9453 	if ((to->to_flags & TOF_TS) != 0 &&
9454 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9455 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9456 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9457 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9458 		tp->ts_recent = to->to_tsval;
9459 	}
9460 	/*
9461 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9462 	 * is on (half-synchronized state), then queue data for later
9463 	 * processing; else drop segment and return.
9464 	 */
9465 	if ((thflags & TH_ACK) == 0) {
9466 		if (tp->t_flags & TF_NEEDSYN) {
9467 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9468 			    tiwin, thflags, nxt_pkt));
9469 		} else if (tp->t_flags & TF_ACKNOW) {
9470 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9471 			bbr->r_wanted_output = 1;
9472 			return (ret_val);
9473 		} else {
9474 			ctf_do_drop(m, NULL);
9475 			return (0);
9476 		}
9477 	}
9478 	/*
9479 	 * Ack processing.
9480 	 */
9481 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9482 		return (ret_val);
9483 	}
9484 	if (ourfinisacked) {
9485 		/*
9486 		 * If we can't receive any more data, then closing user can
9487 		 * proceed. Starting the timer is contrary to the
9488 		 * specification, but if we don't get a FIN we'll hang
9489 		 * forever.
9490 		 *
9491 		 * XXXjl: we should release the tp also, and use a
9492 		 * compressed state.
9493 		 */
9494 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9495 			soisdisconnected(so);
9496 			tcp_timer_activate(tp, TT_2MSL,
9497 			    (tcp_fast_finwait2_recycle ?
9498 			    tcp_finwait2_timeout :
9499 			    TP_MAXIDLE(tp)));
9500 		}
9501 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9502 	}
9503 	if (sbavail(&so->so_snd)) {
9504 		if (ctf_progress_timeout_check(tp, true)) {
9505 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9506 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9507 			return (1);
9508 		}
9509 	}
9510 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9511 	    tiwin, thflags, nxt_pkt));
9512 }
9513 
9514 /*
9515  * Return value of 1, the TCB is unlocked and most
9516  * likely gone, return value of 0, the TCB is still
9517  * locked.
9518  */
9519 static int
9520 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9521     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9522     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9523 {
9524 	int32_t ourfinisacked = 0;
9525 	int32_t ret_val;
9526 	struct tcp_bbr *bbr;
9527 
9528 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9529 
9530 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9531 	ctf_calc_rwin(so, tp);
9532 	if ((thflags & TH_RST) ||
9533 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9534 		return (ctf_process_rst(m, th, so, tp));
9535 	/*
9536 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9537 	 * synchronized state.
9538 	 */
9539 	if (thflags & TH_SYN) {
9540 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9541 		return (ret_val);
9542 	}
9543 	/*
9544 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9545 	 * it's less than ts_recent, drop it.
9546 	 */
9547 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9548 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9549 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9550 			return (ret_val);
9551 	}
9552 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9553 		return (ret_val);
9554 	}
9555 	/*
9556 	 * If new data are received on a connection after the user processes
9557 	 * are gone, then RST the other end.
9558 	 * We call a new function now so we might continue and setup
9559 	 * to reset at all data being ack'd.
9560 	 */
9561 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9562 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9563 		return (1);
9564 	/*
9565 	 * If last ACK falls within this segment's sequence numbers, record
9566 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9567 	 * from the latest proposal of the tcplw@cray.com list (Braden
9568 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9569 	 * with our earlier PAWS tests, so this check should be solely
9570 	 * predicated on the sequence space of this segment. 3) That we
9571 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9572 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9573 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9574 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9575 	 * p.869. In such cases, we can still calculate the RTT correctly
9576 	 * when RCV.NXT == Last.ACK.Sent.
9577 	 */
9578 	if ((to->to_flags & TOF_TS) != 0 &&
9579 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9580 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9581 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9582 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9583 		tp->ts_recent = to->to_tsval;
9584 	}
9585 	/*
9586 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9587 	 * is on (half-synchronized state), then queue data for later
9588 	 * processing; else drop segment and return.
9589 	 */
9590 	if ((thflags & TH_ACK) == 0) {
9591 		if (tp->t_flags & TF_NEEDSYN) {
9592 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9593 			    tiwin, thflags, nxt_pkt));
9594 		} else if (tp->t_flags & TF_ACKNOW) {
9595 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9596 			bbr->r_wanted_output = 1;
9597 			return (ret_val);
9598 		} else {
9599 			ctf_do_drop(m, NULL);
9600 			return (0);
9601 		}
9602 	}
9603 	/*
9604 	 * Ack processing.
9605 	 */
9606 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9607 		return (ret_val);
9608 	}
9609 	if (ourfinisacked) {
9610 		tcp_twstart(tp);
9611 		m_freem(m);
9612 		return (1);
9613 	}
9614 	if (sbavail(&so->so_snd)) {
9615 		if (ctf_progress_timeout_check(tp, true)) {
9616 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9617 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9618 			return (1);
9619 		}
9620 	}
9621 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9622 	    tiwin, thflags, nxt_pkt));
9623 }
9624 
9625 /*
9626  * Return value of 1, the TCB is unlocked and most
9627  * likely gone, return value of 0, the TCB is still
9628  * locked.
9629  */
9630 static int
9631 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9632     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9633     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9634 {
9635 	int32_t ourfinisacked = 0;
9636 	int32_t ret_val;
9637 	struct tcp_bbr *bbr;
9638 
9639 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9640 
9641 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9642 	ctf_calc_rwin(so, tp);
9643 	if ((thflags & TH_RST) ||
9644 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9645 		return (ctf_process_rst(m, th, so, tp));
9646 	/*
9647 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9648 	 * synchronized state.
9649 	 */
9650 	if (thflags & TH_SYN) {
9651 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9652 		return (ret_val);
9653 	}
9654 	/*
9655 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9656 	 * it's less than ts_recent, drop it.
9657 	 */
9658 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9659 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9660 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9661 			return (ret_val);
9662 	}
9663 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9664 		return (ret_val);
9665 	}
9666 	/*
9667 	 * If new data are received on a connection after the user processes
9668 	 * are gone, then RST the other end.
9669 	 * We call a new function now so we might continue and setup
9670 	 * to reset at all data being ack'd.
9671 	 */
9672 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9673 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9674 		return (1);
9675 	/*
9676 	 * If last ACK falls within this segment's sequence numbers, record
9677 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9678 	 * from the latest proposal of the tcplw@cray.com list (Braden
9679 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9680 	 * with our earlier PAWS tests, so this check should be solely
9681 	 * predicated on the sequence space of this segment. 3) That we
9682 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9683 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9684 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9685 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9686 	 * p.869. In such cases, we can still calculate the RTT correctly
9687 	 * when RCV.NXT == Last.ACK.Sent.
9688 	 */
9689 	if ((to->to_flags & TOF_TS) != 0 &&
9690 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9691 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9692 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9693 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9694 		tp->ts_recent = to->to_tsval;
9695 	}
9696 	/*
9697 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9698 	 * is on (half-synchronized state), then queue data for later
9699 	 * processing; else drop segment and return.
9700 	 */
9701 	if ((thflags & TH_ACK) == 0) {
9702 		if (tp->t_flags & TF_NEEDSYN) {
9703 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9704 			    tiwin, thflags, nxt_pkt));
9705 		} else if (tp->t_flags & TF_ACKNOW) {
9706 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9707 			bbr->r_wanted_output = 1;
9708 			return (ret_val);
9709 		} else {
9710 			ctf_do_drop(m, NULL);
9711 			return (0);
9712 		}
9713 	}
9714 	/*
9715 	 * case TCPS_LAST_ACK: Ack processing.
9716 	 */
9717 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9718 		return (ret_val);
9719 	}
9720 	if (ourfinisacked) {
9721 		tp = tcp_close(tp);
9722 		ctf_do_drop(m, tp);
9723 		return (1);
9724 	}
9725 	if (sbavail(&so->so_snd)) {
9726 		if (ctf_progress_timeout_check(tp, true)) {
9727 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9728 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9729 			return (1);
9730 		}
9731 	}
9732 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9733 	    tiwin, thflags, nxt_pkt));
9734 }
9735 
9736 /*
9737  * Return value of 1, the TCB is unlocked and most
9738  * likely gone, return value of 0, the TCB is still
9739  * locked.
9740  */
9741 static int
9742 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9743     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9744     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9745 {
9746 	int32_t ourfinisacked = 0;
9747 	int32_t ret_val;
9748 	struct tcp_bbr *bbr;
9749 
9750 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9751 
9752 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9753 	ctf_calc_rwin(so, tp);
9754 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9755 	if ((thflags & TH_RST) ||
9756 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9757 		return (ctf_process_rst(m, th, so, tp));
9758 
9759 	/*
9760 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9761 	 * synchronized state.
9762 	 */
9763 	if (thflags & TH_SYN) {
9764 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9765 		return (ret_val);
9766 	}
9767 	/*
9768 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9769 	 * it's less than ts_recent, drop it.
9770 	 */
9771 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9772 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9773 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9774 			return (ret_val);
9775 	}
9776 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9777 		return (ret_val);
9778 	}
9779 	/*
9780 	 * If new data are received on a connection after the user processes
9781 	 * are gone, then we may RST the other end depending on the outcome
9782 	 * of bbr_check_data_after_close.
9783 	 * We call a new function now so we might continue and setup
9784 	 * to reset at all data being ack'd.
9785 	 */
9786 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9787 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9788 		return (1);
9789 	/*
9790 	 * If last ACK falls within this segment's sequence numbers, record
9791 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9792 	 * from the latest proposal of the tcplw@cray.com list (Braden
9793 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9794 	 * with our earlier PAWS tests, so this check should be solely
9795 	 * predicated on the sequence space of this segment. 3) That we
9796 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9797 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9798 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9799 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9800 	 * p.869. In such cases, we can still calculate the RTT correctly
9801 	 * when RCV.NXT == Last.ACK.Sent.
9802 	 */
9803 	if ((to->to_flags & TOF_TS) != 0 &&
9804 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9805 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9806 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9807 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9808 		tp->ts_recent = to->to_tsval;
9809 	}
9810 	/*
9811 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9812 	 * is on (half-synchronized state), then queue data for later
9813 	 * processing; else drop segment and return.
9814 	 */
9815 	if ((thflags & TH_ACK) == 0) {
9816 		if (tp->t_flags & TF_NEEDSYN) {
9817 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9818 			    tiwin, thflags, nxt_pkt));
9819 		} else if (tp->t_flags & TF_ACKNOW) {
9820 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9821 			bbr->r_wanted_output = 1;
9822 			return (ret_val);
9823 		} else {
9824 			ctf_do_drop(m, NULL);
9825 			return (0);
9826 		}
9827 	}
9828 	/*
9829 	 * Ack processing.
9830 	 */
9831 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9832 		return (ret_val);
9833 	}
9834 	if (sbavail(&so->so_snd)) {
9835 		if (ctf_progress_timeout_check(tp, true)) {
9836 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9837 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9838 			return (1);
9839 		}
9840 	}
9841 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9842 	    tiwin, thflags, nxt_pkt));
9843 }
9844 
9845 static void
9846 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr)
9847 {
9848 	/*
9849 	 * Assure no timers are running.
9850 	 */
9851 	if (tcp_timer_active(tp, TT_PERSIST)) {
9852 		/* We enter in persists, set the flag appropriately */
9853 		bbr->rc_in_persist = 1;
9854 	}
9855 	if (tcp_in_hpts(bbr->rc_tp)) {
9856 		tcp_hpts_remove(bbr->rc_tp);
9857 	}
9858 }
9859 
9860 static void
9861 bbr_google_mode_on(struct tcp_bbr *bbr)
9862 {
9863 	bbr->rc_use_google = 1;
9864 	bbr->rc_no_pacing = 0;
9865 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9866 	bbr->r_use_policer = bbr_policer_detection_enabled;
9867 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9868 	bbr->bbr_use_rack_cheat = 0;
9869 	bbr->r_ctl.rc_incr_tmrs = 0;
9870 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9871 	bbr->r_ctl.rc_inc_ip_oh = 0;
9872 	bbr->r_ctl.rc_inc_enet_oh = 0;
9873 	reset_time(&bbr->r_ctl.rc_delrate,
9874 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9875 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9876 			 (11 * USECS_IN_SECOND));
9877 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9878 }
9879 
9880 static void
9881 bbr_google_mode_off(struct tcp_bbr *bbr)
9882 {
9883 	bbr->rc_use_google = 0;
9884 	bbr->r_ctl.bbr_google_discount = 0;
9885 	bbr->no_pacing_until = bbr_no_pacing_until;
9886 	bbr->r_use_policer = 0;
9887 	if (bbr->no_pacing_until)
9888 		bbr->rc_no_pacing = 1;
9889 	else
9890 		bbr->rc_no_pacing = 0;
9891 	if (bbr_use_rack_resend_cheat)
9892 		bbr->bbr_use_rack_cheat = 1;
9893 	else
9894 		bbr->bbr_use_rack_cheat = 0;
9895 	if (bbr_incr_timers)
9896 		bbr->r_ctl.rc_incr_tmrs = 1;
9897 	else
9898 		bbr->r_ctl.rc_incr_tmrs = 0;
9899 	if (bbr_include_tcp_oh)
9900 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9901 	else
9902 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9903 	if (bbr_include_ip_oh)
9904 		bbr->r_ctl.rc_inc_ip_oh = 1;
9905 	else
9906 		bbr->r_ctl.rc_inc_ip_oh = 0;
9907 	if (bbr_include_enet_oh)
9908 		bbr->r_ctl.rc_inc_enet_oh = 1;
9909 	else
9910 		bbr->r_ctl.rc_inc_enet_oh = 0;
9911 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9912 	reset_time(&bbr->r_ctl.rc_delrate,
9913 		   bbr_num_pktepo_for_del_limit);
9914 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9915 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9916 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9917 }
9918 /*
9919  * Return 0 on success, non-zero on failure
9920  * which indicates the error (usually no memory).
9921  */
9922 static int
9923 bbr_init(struct tcpcb *tp, void **ptr)
9924 {
9925 	struct inpcb *inp = tptoinpcb(tp);
9926 	struct tcp_bbr *bbr = NULL;
9927 	uint32_t cts;
9928 
9929 	*ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
9930 	if (*ptr == NULL) {
9931 		/*
9932 		 * We need to allocate memory but cant. The INP and INP_INFO
9933 		 * locks and they are recursive (happens during setup. So a
9934 		 * scheme to drop the locks fails :(
9935 		 *
9936 		 */
9937 		return (ENOMEM);
9938 	}
9939 	bbr = (struct tcp_bbr *)*ptr;
9940 	bbr->rtt_valid = 0;
9941 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
9942 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
9943 	/* Take off any undesired flags */
9944 	tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
9945 	tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
9946 	tp->t_flags2 &= ~TF2_MBUF_ACKCMP;
9947 	tp->t_flags2 &= ~TF2_MBUF_L_ACKS;
9948 
9949 	TAILQ_INIT(&bbr->r_ctl.rc_map);
9950 	TAILQ_INIT(&bbr->r_ctl.rc_free);
9951 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
9952 	bbr->rc_tp = tp;
9953 	bbr->rc_inp = inp;
9954 	cts = tcp_get_usecs(&bbr->rc_tv);
9955 	tp->t_acktime = 0;
9956 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
9957 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
9958 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
9959 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
9960 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
9961 	bbr->r_ctl.rc_min_to = bbr_min_to;
9962 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
9963 	bbr->r_ctl.bbr_lost_at_state = 0;
9964 	bbr->r_ctl.rc_lost_at_startup = 0;
9965 	bbr->rc_all_timers_stopped = 0;
9966 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
9967 	bbr->r_ctl.rc_pkt_epoch_del = 0;
9968 	bbr->r_ctl.rc_pkt_epoch = 0;
9969 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
9970 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
9971 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
9972 	bbr->r_ctl.rc_went_idle_time = cts;
9973 	bbr->rc_pacer_started = cts;
9974 	bbr->r_ctl.rc_pkt_epoch_time = cts;
9975 	bbr->r_ctl.rc_rcvtime = cts;
9976 	bbr->r_ctl.rc_bbr_state_time = cts;
9977 	bbr->r_ctl.rc_del_time = cts;
9978 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
9979 	bbr->r_ctl.last_in_probertt = cts;
9980 	bbr->skip_gain = 0;
9981 	bbr->gain_is_limited = 0;
9982 	bbr->no_pacing_until = bbr_no_pacing_until;
9983 	if (bbr->no_pacing_until)
9984 		bbr->rc_no_pacing = 1;
9985 	if (bbr_use_google_algo) {
9986 		bbr->rc_no_pacing = 0;
9987 		bbr->rc_use_google = 1;
9988 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9989 		bbr->r_use_policer = bbr_policer_detection_enabled;
9990 	} else {
9991 		bbr->rc_use_google = 0;
9992 		bbr->r_ctl.bbr_google_discount = 0;
9993 		bbr->r_use_policer = 0;
9994 	}
9995 	if (bbr_ts_limiting)
9996 		bbr->rc_use_ts_limit = 1;
9997 	else
9998 		bbr->rc_use_ts_limit = 0;
9999 	if (bbr_ts_can_raise)
10000 		bbr->ts_can_raise = 1;
10001 	else
10002 		bbr->ts_can_raise = 0;
10003 	if (V_tcp_delack_enabled == 1)
10004 		tp->t_delayed_ack = 2;
10005 	else if (V_tcp_delack_enabled == 0)
10006 		tp->t_delayed_ack = 0;
10007 	else if (V_tcp_delack_enabled < 100)
10008 		tp->t_delayed_ack = V_tcp_delack_enabled;
10009 	else
10010 		tp->t_delayed_ack = 2;
10011 	if (bbr->rc_use_google == 0)
10012 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10013 	else
10014 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10015 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10016 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10017 	bbr->rc_init_win = bbr_def_init_win;
10018 	if (tp->t_flags & TF_REQ_TSTMP)
10019 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10020 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10021 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10022 	bbr->r_init_rtt = 1;
10023 
10024 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10025 	if (bbr_allow_hdwr_pacing)
10026 		bbr->bbr_hdw_pace_ena = 1;
10027 	else
10028 		bbr->bbr_hdw_pace_ena = 0;
10029 	if (bbr_sends_full_iwnd)
10030 		bbr->bbr_init_win_cheat = 1;
10031 	else
10032 		bbr->bbr_init_win_cheat = 0;
10033 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10034 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10035 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10036 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10037 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10038 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10039 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10040 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10041 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10042 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10043 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10044 	bbr->r_ctl.rc_rtt_shrinks = cts;
10045 	if (bbr->rc_use_google) {
10046 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10047 				  FILTER_TYPE_MAX,
10048 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10049 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10050 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10051 	} else {
10052 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10053 				  FILTER_TYPE_MAX,
10054 				  bbr_num_pktepo_for_del_limit);
10055 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10056 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10057 	}
10058 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10059 	if (bbr_uses_idle_restart)
10060 		bbr->rc_use_idle_restart = 1;
10061 	else
10062 		bbr->rc_use_idle_restart = 0;
10063 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10064 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10065 	if (bbr_resends_use_tso)
10066 		bbr->rc_resends_use_tso = 1;
10067 	if (tp->snd_una != tp->snd_max) {
10068 		/* Create a send map for the current outstanding data */
10069 		struct bbr_sendmap *rsm;
10070 
10071 		rsm = bbr_alloc(bbr);
10072 		if (rsm == NULL) {
10073 			uma_zfree(bbr_pcb_zone, *ptr);
10074 			*ptr = NULL;
10075 			return (ENOMEM);
10076 		}
10077 		rsm->r_rtt_not_allowed = 1;
10078 		rsm->r_tim_lastsent[0] = cts;
10079 		rsm->r_rtr_cnt = 1;
10080 		rsm->r_rtr_bytes = 0;
10081 		rsm->r_start = tp->snd_una;
10082 		rsm->r_end = tp->snd_max;
10083 		rsm->r_dupack = 0;
10084 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10085 		rsm->r_ts_valid = 0;
10086 		rsm->r_del_ack_ts = tp->ts_recent;
10087 		rsm->r_del_time = cts;
10088 		if (bbr->r_ctl.r_app_limited_until)
10089 			rsm->r_app_limited = 1;
10090 		else
10091 			rsm->r_app_limited = 0;
10092 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10093 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10094 		rsm->r_in_tmap = 1;
10095 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10096 			rsm->r_bbr_state = bbr_state_val(bbr);
10097 		else
10098 			rsm->r_bbr_state = 8;
10099 	}
10100 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10101 		bbr->bbr_use_rack_cheat = 1;
10102 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10103 		bbr->r_ctl.rc_incr_tmrs = 1;
10104 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10105 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10106 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10107 		bbr->r_ctl.rc_inc_ip_oh = 1;
10108 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10109 		bbr->r_ctl.rc_inc_enet_oh = 1;
10110 
10111 	bbr_log_type_statechange(bbr, cts, __LINE__);
10112 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10113 	    (tp->t_srtt)) {
10114 		uint32_t rtt;
10115 
10116 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10117 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10118 	}
10119 	/* announce the settings and state */
10120 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10121 	tcp_bbr_tso_size_check(bbr, cts);
10122 	/*
10123 	 * Now call the generic function to start a timer. This will place
10124 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10125 	 * flags.
10126 	 */
10127 	bbr_stop_all_timers(tp, bbr);
10128 	/*
10129 	 * Validate the timers are not in usec, if they are convert.
10130 	 * BBR should in theory move to USEC and get rid of a
10131 	 * lot of the TICKS_2 calls.. but for now we stay
10132 	 * with tick timers.
10133 	 */
10134 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
10135 	TCPT_RANGESET(tp->t_rxtcur,
10136 	    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
10137 	    tp->t_rttmin, TCPTV_REXMTMAX);
10138 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10139 	return (0);
10140 }
10141 
10142 /*
10143  * Return 0 if we can accept the connection. Return
10144  * non-zero if we can't handle the connection. A EAGAIN
10145  * means you need to wait until the connection is up.
10146  * a EADDRNOTAVAIL means we can never handle the connection
10147  * (no SACK).
10148  */
10149 static int
10150 bbr_handoff_ok(struct tcpcb *tp)
10151 {
10152 	if ((tp->t_state == TCPS_CLOSED) ||
10153 	    (tp->t_state == TCPS_LISTEN)) {
10154 		/* Sure no problem though it may not stick */
10155 		return (0);
10156 	}
10157 	if ((tp->t_state == TCPS_SYN_SENT) ||
10158 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10159 		/*
10160 		 * We really don't know you have to get to ESTAB or beyond
10161 		 * to tell.
10162 		 */
10163 		return (EAGAIN);
10164 	}
10165 	if (tp->t_flags & TF_SENTFIN)
10166 		return (EINVAL);
10167 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10168 		return (0);
10169 	}
10170 	/*
10171 	 * If we reach here we don't do SACK on this connection so we can
10172 	 * never do rack.
10173 	 */
10174 	return (EINVAL);
10175 }
10176 
10177 static void
10178 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10179 {
10180 	if (tp->t_fb_ptr) {
10181 		uint32_t calc;
10182 		struct tcp_bbr *bbr;
10183 		struct bbr_sendmap *rsm;
10184 
10185 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10186 		if (bbr->r_ctl.crte)
10187 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10188 		bbr_log_flowend(bbr);
10189 		bbr->rc_tp = NULL;
10190 		if (bbr->bbr_hdrw_pacing)
10191 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10192 		else
10193 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10194 		if (bbr->r_ctl.crte != NULL) {
10195 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10196 			bbr->r_ctl.crte = NULL;
10197 		}
10198 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10199 		while (rsm) {
10200 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10201 			uma_zfree(bbr_zone, rsm);
10202 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10203 		}
10204 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10205 		while (rsm) {
10206 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10207 			uma_zfree(bbr_zone, rsm);
10208 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10209 		}
10210 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10211 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10212 			BBR_STAT_INC(bbr_dynamic_rwnd);
10213 		else
10214 			BBR_STAT_INC(bbr_static_rwnd);
10215 		bbr->r_ctl.rc_free_cnt = 0;
10216 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10217 		tp->t_fb_ptr = NULL;
10218 	}
10219 	/* Make sure snd_nxt is correctly set */
10220 	tp->snd_nxt = tp->snd_max;
10221 }
10222 
10223 static void
10224 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10225 {
10226 	switch (tp->t_state) {
10227 	case TCPS_SYN_SENT:
10228 		bbr->r_state = TCPS_SYN_SENT;
10229 		bbr->r_substate = bbr_do_syn_sent;
10230 		break;
10231 	case TCPS_SYN_RECEIVED:
10232 		bbr->r_state = TCPS_SYN_RECEIVED;
10233 		bbr->r_substate = bbr_do_syn_recv;
10234 		break;
10235 	case TCPS_ESTABLISHED:
10236 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10237 		bbr->r_state = TCPS_ESTABLISHED;
10238 		bbr->r_substate = bbr_do_established;
10239 		break;
10240 	case TCPS_CLOSE_WAIT:
10241 		bbr->r_state = TCPS_CLOSE_WAIT;
10242 		bbr->r_substate = bbr_do_close_wait;
10243 		break;
10244 	case TCPS_FIN_WAIT_1:
10245 		bbr->r_state = TCPS_FIN_WAIT_1;
10246 		bbr->r_substate = bbr_do_fin_wait_1;
10247 		break;
10248 	case TCPS_CLOSING:
10249 		bbr->r_state = TCPS_CLOSING;
10250 		bbr->r_substate = bbr_do_closing;
10251 		break;
10252 	case TCPS_LAST_ACK:
10253 		bbr->r_state = TCPS_LAST_ACK;
10254 		bbr->r_substate = bbr_do_lastack;
10255 		break;
10256 	case TCPS_FIN_WAIT_2:
10257 		bbr->r_state = TCPS_FIN_WAIT_2;
10258 		bbr->r_substate = bbr_do_fin_wait_2;
10259 		break;
10260 	case TCPS_LISTEN:
10261 	case TCPS_CLOSED:
10262 	case TCPS_TIME_WAIT:
10263 	default:
10264 		break;
10265 	};
10266 }
10267 
10268 static void
10269 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10270 {
10271 	/*
10272 	 * Now what state are we going into now? Is there adjustments
10273 	 * needed?
10274 	 */
10275 	int32_t old_state;
10276 
10277 	old_state = bbr_state_val(bbr);
10278 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10279 		/* Save the lowest srtt we saw in our end of the sub-state */
10280 		bbr->rc_hit_state_1 = 0;
10281 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10282 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10283 	}
10284 	bbr->rc_bbr_substate++;
10285 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10286 		/* Cycle back to first state-> gain */
10287 		bbr->rc_bbr_substate = 0;
10288 	}
10289 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10290 		/*
10291 		 * We enter the gain(5/4) cycle (possibly less if
10292 		 * shallow buffer detection is enabled)
10293 		 */
10294 		if (bbr->skip_gain) {
10295 			/*
10296 			 * Hardware pacing has set our rate to
10297 			 * the max and limited our b/w just
10298 			 * do level i.e. no gain.
10299 			 */
10300 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10301 		} else if (bbr->gain_is_limited &&
10302 			   bbr->bbr_hdrw_pacing &&
10303 			   bbr->r_ctl.crte) {
10304 			/*
10305 			 * We can't gain above the hardware pacing
10306 			 * rate which is less than our rate + the gain
10307 			 * calculate the gain needed to reach the hardware
10308 			 * pacing rate..
10309 			 */
10310 			uint64_t bw, rate, gain_calc;
10311 
10312 			bw = bbr_get_bw(bbr);
10313 			rate = bbr->r_ctl.crte->rate;
10314 			if ((rate > bw) &&
10315 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10316 				gain_calc = (rate * BBR_UNIT) / bw;
10317 				if (gain_calc < BBR_UNIT)
10318 					gain_calc = BBR_UNIT;
10319 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10320 			} else {
10321 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10322 			}
10323 		} else
10324 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10325 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10326 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10327 		} else
10328 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10329 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10330 		bbr->rc_hit_state_1 = 1;
10331 		bbr->r_ctl.rc_exta_time_gd = 0;
10332 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10333 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10334 		if (bbr_state_drain_2_tar) {
10335 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10336 		} else
10337 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10338 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10339 	} else {
10340 		/* All other cycles hit here 2-7 */
10341 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10342 			if (bbr_sub_drain_slam_cwnd &&
10343 			    (bbr->rc_use_google == 0) &&
10344 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10345 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10346 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10347 			}
10348 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10349 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10350 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10351 			else
10352 				bbr->r_ctl.rc_exta_time_gd = 0;
10353 			if (bbr->r_ctl.rc_exta_time_gd) {
10354 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10355 				/* Now chop up the time for each state (div by 7) */
10356 				bbr->r_ctl.rc_level_state_extra /= 7;
10357 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10358 					/* Add a randomization */
10359 					bbr_randomize_extra_state_time(bbr);
10360 				}
10361 			}
10362 		}
10363 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10364 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10365 	}
10366 	if (bbr->rc_use_google) {
10367 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10368 	}
10369 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10370 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10371 	if (dolog)
10372 		bbr_log_type_statechange(bbr, cts, line);
10373 
10374 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10375 		uint32_t time_in;
10376 
10377 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10378 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10379 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10380 		} else {
10381 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10382 		}
10383 	}
10384 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10385 	bbr_set_state_target(bbr, __LINE__);
10386 	if (bbr_sub_drain_slam_cwnd &&
10387 	    (bbr->rc_use_google == 0) &&
10388 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10389 		/* Slam down the cwnd */
10390 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10391 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10392 		if (bbr_sub_drain_app_limit) {
10393 			/* Go app limited if we are on a long drain */
10394 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10395 							  ctf_flight_size(bbr->rc_tp,
10396 							      (bbr->r_ctl.rc_sacked +
10397 							       bbr->r_ctl.rc_lost_bytes)));
10398 		}
10399 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10400 	}
10401 	if (bbr->rc_lt_use_bw) {
10402 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10403 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10404 	}
10405 	/* Google changes TSO size every cycle */
10406 	if (bbr->rc_use_google)
10407 		tcp_bbr_tso_size_check(bbr, cts);
10408 	bbr->r_ctl.gain_epoch = cts;
10409 	bbr->r_ctl.rc_bbr_state_time = cts;
10410 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10411 }
10412 
10413 static void
10414 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10415 {
10416 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10417 	    (google_allow_early_out == 1) &&
10418 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10419 		/* We have reached out target flight size possibly early */
10420 		goto change_state;
10421 	}
10422 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10423 		return;
10424 	}
10425 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10426 		/*
10427 		 * Must be a rttProp movement forward before
10428 		 * we can change states.
10429 		 */
10430 		return;
10431 	}
10432 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10433 		/*
10434 		 * The needed time has passed but for
10435 		 * the gain cycle extra rules apply:
10436 		 * 1) If we have seen loss, we exit
10437 		 * 2) If we have not reached the target
10438 		 *    we stay in GAIN (gain-to-target).
10439 		 */
10440 		if (google_consider_lost && losses)
10441 			goto change_state;
10442 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10443 			return;
10444 		}
10445 	}
10446 change_state:
10447 	/* For gain we must reach our target, all others last 1 rttProp */
10448 	bbr_substate_change(bbr, cts, __LINE__, 1);
10449 }
10450 
10451 static void
10452 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10453 {
10454 	uint32_t flight, bbr_cur_cycle_time;
10455 
10456 	if (bbr->rc_use_google) {
10457 		bbr_set_probebw_google_gains(bbr, cts, losses);
10458 		return;
10459 	}
10460 	if (cts == 0) {
10461 		/*
10462 		 * Never alow cts to be 0 we
10463 		 * do this so we can judge if
10464 		 * we have set a timestamp.
10465 		 */
10466 		cts = 1;
10467 	}
10468 	if (bbr_state_is_pkt_epoch)
10469 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10470 	else
10471 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10472 
10473 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10474 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10475 			flight = ctf_flight_size(bbr->rc_tp,
10476 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10477 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10478 				/* Keep it slam down */
10479 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10480 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10481 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10482 				}
10483 				if (bbr_sub_drain_app_limit) {
10484 					/* Go app limited if we are on a long drain */
10485 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10486 				}
10487 			}
10488 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10489 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10490 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10491 				/*
10492 				 * Still here after the same time as
10493 				 * the gain. We need to drain harder
10494 				 * for the next srtt. Reduce by a set amount
10495 				 * the gain drop is capped at DRAIN states
10496 				 * value (88).
10497 				 */
10498 				bbr->r_ctl.flightsize_at_drain = flight;
10499 				if (bbr_drain_drop_mul &&
10500 				    bbr_drain_drop_div &&
10501 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10502 					/* Use your specific drop value (def 4/5 = 20%) */
10503 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10504 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10505 				} else {
10506 					/* You get drop of 20% */
10507 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10508 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10509 				}
10510 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10511 					/* Reduce our gain again to the bottom  */
10512 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10513 				}
10514 				bbr_log_exit_gain(bbr, cts, 4);
10515 				/*
10516 				 * Extend out so we wait another
10517 				 * epoch before dropping again.
10518 				 */
10519 				bbr->r_ctl.gain_epoch = cts;
10520 			}
10521 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10522 				if (bbr_sub_drain_slam_cwnd &&
10523 				    (bbr->rc_use_google == 0) &&
10524 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10525 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10526 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10527 				}
10528 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10529 				bbr_log_exit_gain(bbr, cts, 3);
10530 			}
10531 		} else {
10532 			/* Its a gain  */
10533 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10534 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10535 				goto change_state;
10536 			}
10537 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10538 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10539 			     bbr->rc_tp->snd_wnd)) {
10540 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10541 				bbr_log_exit_gain(bbr, cts, 2);
10542 			}
10543 		}
10544 		/**
10545 		 * We fall through and return always one of two things has
10546 		 * occurred.
10547 		 * 1) We are still not at target
10548 		 *    <or>
10549 		 * 2) We reached the target and set rc_bbr_state_atflight
10550 		 *    which means we no longer hit this block
10551 		 *    next time we are called.
10552 		 */
10553 		return;
10554 	}
10555 change_state:
10556 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10557 		return;
10558 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10559 		/* Less than a full time-period has passed */
10560 		return;
10561 	}
10562 	if (bbr->r_ctl.rc_level_state_extra &&
10563 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10564 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10565 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10566 		/* Less than a full time-period + extra has passed */
10567 		return;
10568 	}
10569 	if (bbr_gain_gets_extra_too &&
10570 	    bbr->r_ctl.rc_level_state_extra &&
10571 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10572 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10573 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10574 		/* Less than a full time-period + extra has passed */
10575 		return;
10576 	}
10577 	bbr_substate_change(bbr, cts, __LINE__, 1);
10578 }
10579 
10580 static uint32_t
10581 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10582 {
10583 	uint32_t mss, tar;
10584 
10585 	if (bbr->rc_use_google) {
10586 		/* Google just uses the cwnd target */
10587 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10588 	} else {
10589 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10590 			  bbr->r_ctl.rc_pace_max_segs);
10591 		/* Get the base cwnd with gain rounded to a mss */
10592 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10593 						      gain), mss);
10594 		/* Make sure it is within our min */
10595 		if (tar < get_min_cwnd(bbr))
10596 			return (get_min_cwnd(bbr));
10597 	}
10598 	return (tar);
10599 }
10600 
10601 static void
10602 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10603 {
10604 	uint32_t tar, meth;
10605 
10606 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10607 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10608 		/* Special case using old probe-rtt method */
10609 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10610 		meth = 1;
10611 	} else {
10612 		/* Non-probe-rtt case and reduced probe-rtt  */
10613 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10614 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10615 			/* For gain cycle we use the hptsi gain */
10616 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10617 			meth = 2;
10618 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10619 			/*
10620 			 * If configured, or for google all other states
10621 			 * get BBR_UNIT.
10622 			 */
10623 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10624 			meth = 3;
10625 		} else {
10626 			/*
10627 			 * Or we set a target based on the pacing gain
10628 			 * for non-google mode and default (non-configured).
10629 			 * Note we don't set a target goal below drain (192).
10630 			 */
10631 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10632 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10633 				meth = 4;
10634 			} else {
10635 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10636 				meth = 5;
10637 			}
10638 		}
10639 	}
10640 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10641 	bbr->r_ctl.rc_target_at_state = tar;
10642 }
10643 
10644 static void
10645 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10646 {
10647 	/* Change to probe_rtt */
10648 	uint32_t time_in;
10649 
10650 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10651 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10652 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10653 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10654 					  + bbr->r_ctl.rc_delivered);
10655 	/* Setup so we force feed the filter */
10656 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10657 		bbr->rc_prtt_set_ts = 1;
10658 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10659 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10660 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10661 	}
10662 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10663 	bbr->r_ctl.rc_rtt_shrinks = cts;
10664 	bbr->r_ctl.last_in_probertt = cts;
10665 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10666 	bbr->r_ctl.rc_bbr_state_time = cts;
10667 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10668 	/* We need to force the filter to update */
10669 
10670 	if ((bbr_sub_drain_slam_cwnd) &&
10671 	    bbr->rc_hit_state_1 &&
10672 	    (bbr->rc_use_google == 0) &&
10673 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10674 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10675 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10676 	} else
10677 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10678 	/* Update the lost */
10679 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10680 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10681 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10682 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10683 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10684 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10685 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10686 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10687 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10688 	} else {
10689 		/*
10690 		 * We bring it down slowly by using a hptsi gain that is
10691 		 * probably 75%. This will slowly float down our outstanding
10692 		 * without tampering with the cwnd.
10693 		 */
10694 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10695 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10696 		bbr_set_state_target(bbr, __LINE__);
10697 		if (bbr_prtt_slam_cwnd &&
10698 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10699 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10700 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10701 		}
10702 	}
10703 	if (ctf_flight_size(bbr->rc_tp,
10704 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10705 	    bbr->r_ctl.rc_target_at_state) {
10706 		/* We are at target */
10707 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10708 	} else {
10709 		/* We need to come down to reach target before our time begins */
10710 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10711 	}
10712 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10713 	BBR_STAT_INC(bbr_enter_probertt);
10714 	bbr_log_exit_gain(bbr, cts, 0);
10715 	bbr_log_type_statechange(bbr, cts, line);
10716 }
10717 
10718 static void
10719 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10720 {
10721 	/*
10722 	 * Sanity check on probe-rtt intervals.
10723 	 * In crazy situations where we are competing
10724 	 * against new-reno flows with huge buffers
10725 	 * our rtt-prop interval could come to dominate
10726 	 * things if we can't get through a full set
10727 	 * of cycles, we need to adjust it.
10728 	 */
10729 	if (bbr_can_adjust_probertt &&
10730 	    (bbr->rc_use_google == 0)) {
10731 		uint16_t val = 0;
10732 		uint32_t cur_rttp, fval, newval, baseval;
10733 
10734 		/* Are we to small and go into probe-rtt to often? */
10735 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10736 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10737 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10738 		if (bbr_is_ratio == 0) {
10739 			if (fval > bbr_rtt_probe_limit)
10740 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10741 			else
10742 				newval = cur_rttp;
10743 		} else {
10744 			int mul;
10745 
10746 			mul = fval / bbr_rtt_probe_limit;
10747 			newval = cur_rttp * mul;
10748 		}
10749 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10750 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10751 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10752 			val = 1;
10753 		} else {
10754 			/*
10755 			 * No adjustments were made
10756 			 * do we need to shrink it?
10757 			 */
10758 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10759 				if (cur_rttp <= bbr_rtt_probe_limit) {
10760 					/*
10761 					 * Things have calmed down lets
10762 					 * shrink all the way to default
10763 					 */
10764 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10765 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10766 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10767 					cur_rttp = bbr_rtt_probe_limit;
10768 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10769 					val = 2;
10770 				} else {
10771 					/*
10772 					 * Well does some adjustment make sense?
10773 					 */
10774 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10775 						/* We can reduce interval time some */
10776 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10777 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10778 						val = 3;
10779 					}
10780 				}
10781 			}
10782 		}
10783 		if (val)
10784 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10785 	}
10786 }
10787 
10788 static void
10789 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10790 {
10791 	/* Exit probe-rtt */
10792 
10793 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10794 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10795 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10796 	}
10797 	bbr_log_exit_gain(bbr, cts, 1);
10798 	bbr->rc_hit_state_1 = 0;
10799 	bbr->r_ctl.rc_rtt_shrinks = cts;
10800 	bbr->r_ctl.last_in_probertt = cts;
10801 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10802 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10803 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10804 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10805 					  bbr->r_ctl.rc_delivered);
10806 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10807 		uint32_t time_in;
10808 
10809 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10810 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10811 	}
10812 	if (bbr->rc_filled_pipe) {
10813 		/* Switch to probe_bw */
10814 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10815 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10816 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10817 		bbr_substate_change(bbr, cts, __LINE__, 0);
10818 		bbr_log_type_statechange(bbr, cts, __LINE__);
10819 	} else {
10820 		/* Back to startup */
10821 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10822 		bbr->r_ctl.rc_bbr_state_time = cts;
10823 		/*
10824 		 * We don't want to give a complete free 3
10825 		 * measurements until we exit, so we use
10826 		 * the number of pe's we were in probe-rtt
10827 		 * to add to the startup_epoch. That way
10828 		 * we will still retain the old state.
10829 		 */
10830 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10831 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10832 		/* Make sure to use the lower pg when shifting back in */
10833 		if (bbr->r_ctl.rc_lost &&
10834 		    bbr_use_lower_gain_in_startup &&
10835 		    (bbr->rc_use_google == 0))
10836 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10837 		else
10838 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10839 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10840 		/* Probably not needed but set it anyway */
10841 		bbr_set_state_target(bbr, __LINE__);
10842 		bbr_log_type_statechange(bbr, cts, __LINE__);
10843 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10844 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10845 	}
10846 	bbr_check_probe_rtt_limits(bbr, cts);
10847 }
10848 
10849 static int32_t inline
10850 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10851 {
10852 	if ((bbr->rc_past_init_win == 1) &&
10853 	    (bbr->rc_in_persist == 0) &&
10854 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10855 		return (1);
10856 	}
10857 	if (bbr_can_force_probertt &&
10858 	    (bbr->rc_in_persist == 0) &&
10859 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10860 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10861 		return (1);
10862 	}
10863 	return (0);
10864 }
10865 
10866 static int32_t
10867 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10868 {
10869 	uint64_t btlbw, gain;
10870 	if (pkt_epoch == 0) {
10871 		/*
10872 		 * Need to be on a pkt-epoch to continue.
10873 		 */
10874 		return (0);
10875 	}
10876 	btlbw = bbr_get_full_bw(bbr);
10877 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10878 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10879 	if (btlbw >= gain) {
10880 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10881 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10882 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10883 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10884 	}
10885 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10886 		return (1);
10887 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10888 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10889 	return(0);
10890 }
10891 
10892 static int32_t inline
10893 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10894 {
10895 	/* Have we gained 25% in the last 3 packet based epoch's? */
10896 	uint64_t btlbw, gain;
10897 	int do_exit;
10898 	int delta, rtt_gain;
10899 
10900 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10901 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10902 		/*
10903 		 * This qualifies as a RTT_PROBE session since we drop the
10904 		 * data outstanding to nothing and waited more than
10905 		 * bbr_rtt_probe_time.
10906 		 */
10907 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10908 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10909 	}
10910 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10911 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10912 		return (0);
10913 	}
10914 	if (bbr->rc_use_google)
10915 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10916 
10917 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10918 	    (bbr_use_lower_gain_in_startup)) {
10919 		/* Drop to a lower gain 1.5 x since we saw loss */
10920 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10921 	}
10922 	if (pkt_epoch == 0) {
10923 		/*
10924 		 * Need to be on a pkt-epoch to continue.
10925 		 */
10926 		return (0);
10927 	}
10928 	if (bbr_rtt_gain_thresh) {
10929 		/*
10930 		 * Do we allow a flow to stay
10931 		 * in startup with no loss and no
10932 		 * gain in rtt over a set threshold?
10933 		 */
10934 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
10935 		    bbr->r_ctl.startup_last_srtt &&
10936 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
10937 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
10938 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
10939 		} else
10940 			rtt_gain = 0;
10941 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
10942 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
10943 			/* First time or new lower value */
10944 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
10945 
10946 		if ((bbr->r_ctl.rc_lost == 0) &&
10947 		    (rtt_gain < bbr_rtt_gain_thresh)) {
10948 			/*
10949 			 * No loss, and we are under
10950 			 * our gain threhold for
10951 			 * increasing RTT.
10952 			 */
10953 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10954 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
10955 			bbr_log_startup_event(bbr, cts, rtt_gain,
10956 					      delta, bbr->r_ctl.startup_last_srtt, 10);
10957 			return (0);
10958 		}
10959 	}
10960 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
10961 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
10962 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
10963 		/*
10964 		 * We only assess if we have a new measurement when
10965 		 * we have no loss and are not in recovery.
10966 		 * Drag up by one our last_startup epoch so we will hold
10967 		 * the number of non-gain we have already accumulated.
10968 		 */
10969 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10970 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
10971 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10972 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
10973 		return (0);
10974 	}
10975 	/* Case where we reduced the lost (bad retransmit) */
10976 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
10977 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10978 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
10979 	btlbw = bbr_get_full_bw(bbr);
10980 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
10981 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10982 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10983 	else
10984 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10985 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10986 	do_exit = 0;
10987 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
10988 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10989 	if (btlbw >= gain) {
10990 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10991 		/* Update the lost so we won't exit in next set of tests */
10992 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10993 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10994 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10995 	}
10996 	if ((bbr->rc_loss_exit &&
10997 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10998 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
10999 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11000 		/*
11001 		 * If we had no gain,  we had loss and that loss was above
11002 		 * our threshould, the rwnd is not constrained, and we have
11003 		 * had at least 3 packet epochs exit. Note that this is
11004 		 * switched off by sysctl. Google does not do this by the
11005 		 * way.
11006 		 */
11007 		if ((ctf_flight_size(bbr->rc_tp,
11008 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11009 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11010 			do_exit = 1;
11011 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11012 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11013 		} else {
11014 			/* Just record an updated loss value */
11015 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11016 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11017 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11018 		}
11019 	} else
11020 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11021 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11022 	    do_exit) {
11023 		/* Return 1 to exit the startup state. */
11024 		return (1);
11025 	}
11026 	/* Stay in startup */
11027 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11028 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11029 	return (0);
11030 }
11031 
11032 static void
11033 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11034 {
11035 	/*
11036 	 * A tick occurred in the rtt epoch do we need to do anything?
11037 	 */
11038 #ifdef BBR_INVARIANTS
11039 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11040 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11041 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11042 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11043 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11044 		/* Debug code? */
11045 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11046 	}
11047 #endif
11048 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11049 		/* Do we exit the startup state? */
11050 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11051 			uint32_t time_in;
11052 
11053 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11054 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11055 			bbr->rc_filled_pipe = 1;
11056 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11057 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11058 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11059 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11060 			} else
11061 				time_in = 0;
11062 			if (bbr->rc_no_pacing)
11063 				bbr->rc_no_pacing = 0;
11064 			bbr->r_ctl.rc_bbr_state_time = cts;
11065 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11066 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11067 			bbr_set_state_target(bbr, __LINE__);
11068 			if ((bbr->rc_use_google == 0) &&
11069 			    bbr_slam_cwnd_in_main_drain) {
11070 				/* Here we don't have to worry about probe-rtt */
11071 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11072 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11073 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11074 			}
11075 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11076 			bbr_log_type_statechange(bbr, cts, __LINE__);
11077 			if (ctf_flight_size(bbr->rc_tp,
11078 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11079 			    bbr->r_ctl.rc_target_at_state) {
11080 				/*
11081 				 * Switch to probe_bw if we are already
11082 				 * there
11083 				 */
11084 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11085 				bbr_substate_change(bbr, cts, __LINE__, 0);
11086 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11087 				bbr_log_type_statechange(bbr, cts, __LINE__);
11088 			}
11089 		}
11090 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11091 		uint32_t inflight;
11092 		struct tcpcb *tp;
11093 
11094 		tp = bbr->rc_tp;
11095 		inflight = ctf_flight_size(tp,
11096 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11097 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11098 			/* We have reached a flight of the cwnd target */
11099 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11100 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11101 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11102 			bbr_set_state_target(bbr, __LINE__);
11103 			/*
11104 			 * Rig it so we don't do anything crazy and
11105 			 * start fresh with a new randomization.
11106 			 */
11107 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11108 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11109 			bbr_substate_change(bbr, cts, __LINE__, 1);
11110 		}
11111 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11112 		/* Has in-flight reached the bdp (or less)? */
11113 		uint32_t inflight;
11114 		struct tcpcb *tp;
11115 
11116 		tp = bbr->rc_tp;
11117 		inflight = ctf_flight_size(tp,
11118 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11119 		if ((bbr->rc_use_google == 0) &&
11120 		    bbr_slam_cwnd_in_main_drain &&
11121 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11122 			/*
11123 			 * Here we don't have to worry about probe-rtt
11124 			 * re-slam it, but keep it slammed down.
11125 			 */
11126 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11127 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11128 		}
11129 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11130 			/* We have drained */
11131 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11132 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11133 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11134 				uint32_t time_in;
11135 
11136 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11137 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11138 			}
11139 			if ((bbr->rc_use_google == 0) &&
11140 			    bbr_slam_cwnd_in_main_drain &&
11141 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11142 				/* Restore the cwnd */
11143 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11144 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11145 			}
11146 			/* Setup probe-rtt has being done now RRS-HERE */
11147 			bbr->r_ctl.rc_rtt_shrinks = cts;
11148 			bbr->r_ctl.last_in_probertt = cts;
11149 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11150 			/* Randomly pick a sub-state */
11151 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11152 			bbr_substate_change(bbr, cts, __LINE__, 0);
11153 			bbr_log_type_statechange(bbr, cts, __LINE__);
11154 		}
11155 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11156 		uint32_t flight;
11157 
11158 		flight = ctf_flight_size(bbr->rc_tp,
11159 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11160 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11161 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11162 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11163 			/*
11164 			 * We must keep cwnd at the desired MSS.
11165 			 */
11166 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11167 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11168 		} else if ((bbr_prtt_slam_cwnd) &&
11169 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11170 			/* Re-slam it */
11171 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11172 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11173 		}
11174 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11175 			/* Has outstanding reached our target? */
11176 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11177 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11178 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11179 				/* If time is exactly 0, be 1usec off */
11180 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11181 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11182 				if (bbr->rc_use_google == 0) {
11183 					/*
11184 					 * Restore any lowering that as occurred to
11185 					 * reach here
11186 					 */
11187 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11188 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11189 					else
11190 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11191 				}
11192 			}
11193 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11194 			    (bbr->rc_use_google == 0) &&
11195 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11196 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11197 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11198 				/*
11199 				 * We have doddled with our current hptsi
11200 				 * gain an srtt and have still not made it
11201 				 * to target, or we have increased our flight.
11202 				 * Lets reduce the gain by xx%
11203 				 * flooring the reduce at DRAIN (based on
11204 				 * mul/div)
11205 				 */
11206 				int red;
11207 
11208 				bbr->r_ctl.flightsize_at_drain = flight;
11209 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11210 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11211 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11212 					/* Reduce our gain again */
11213 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11214 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11215 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11216 					/* one more chance before we give up */
11217 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11218 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11219 				} else {
11220 					/* At the very bottom */
11221 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11222 				}
11223 			}
11224 		}
11225 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11226 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11227 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11228 			/* Time to exit probe RTT normally */
11229 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11230 		}
11231 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11232 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11233 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11234 			/*
11235 			 * This qualifies as a RTT_PROBE session since we
11236 			 * drop the data outstanding to nothing and waited
11237 			 * more than bbr_rtt_probe_time.
11238 			 */
11239 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11240 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11241 		}
11242 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11243 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11244 		} else {
11245 			bbr_set_probebw_gains(bbr, cts, losses);
11246 		}
11247 	}
11248 }
11249 
11250 static void
11251 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11252 {
11253 	int32_t epoch = 0;
11254 
11255 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11256 		bbr_set_epoch(bbr, cts, line);
11257 		/* At each epoch doe lt bw sampling */
11258 		epoch = 1;
11259 	}
11260 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11261 }
11262 
11263 static int
11264 bbr_do_segment_nounlock(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11265     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos, int32_t nxt_pkt,
11266     struct timeval *tv)
11267 {
11268 	struct inpcb *inp = tptoinpcb(tp);
11269 	struct socket *so = tptosocket(tp);
11270 	int32_t thflags, retval;
11271 	uint32_t cts, lcts;
11272 	uint32_t tiwin;
11273 	struct tcpopt to;
11274 	struct tcp_bbr *bbr;
11275 	struct bbr_sendmap *rsm;
11276 	struct timeval ltv;
11277 	int32_t did_out = 0;
11278 	uint16_t nsegs;
11279 	int32_t prev_state;
11280 	uint32_t lost;
11281 
11282 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11283 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11284 	/* add in our stats */
11285 	kern_prefetch(bbr, &prev_state);
11286 	prev_state = 0;
11287 	thflags = tcp_get_flags(th);
11288 	/*
11289 	 * If this is either a state-changing packet or current state isn't
11290 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11291 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11292 	 * caller may have unnecessarily acquired a write lock due to a
11293 	 * race.
11294 	 */
11295 	INP_WLOCK_ASSERT(tptoinpcb(tp));
11296 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11297 	    __func__));
11298 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11299 	    __func__));
11300 
11301 	tp->t_rcvtime = ticks;
11302 	/*
11303 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11304 	 * the scale is zero.
11305 	 */
11306 	tiwin = th->th_win << tp->snd_scale;
11307 #ifdef STATS
11308 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11309 #endif
11310 
11311 	if (m->m_flags & M_TSTMP) {
11312 		/* Prefer the hardware timestamp if present */
11313 		struct timespec ts;
11314 
11315 		mbuf_tstmp2timespec(m, &ts);
11316 		bbr->rc_tv.tv_sec = ts.tv_sec;
11317 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11318 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11319 	} else if (m->m_flags & M_TSTMP_LRO) {
11320 		/* Next the arrival timestamp */
11321 		struct timespec ts;
11322 
11323 		mbuf_tstmp2timespec(m, &ts);
11324 		bbr->rc_tv.tv_sec = ts.tv_sec;
11325 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11326 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11327 	} else {
11328 		/*
11329 		 * Ok just get the current time.
11330 		 */
11331 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11332 	}
11333 	/*
11334 	 * Parse options on any incoming segment.
11335 	 */
11336 	tcp_dooptions(&to, (u_char *)(th + 1),
11337 	    (th->th_off << 2) - sizeof(struct tcphdr),
11338 	    (thflags & TH_SYN) ? TO_SYN : 0);
11339 
11340 	/*
11341 	 * If timestamps were negotiated during SYN/ACK and a
11342 	 * segment without a timestamp is received, silently drop
11343 	 * the segment, unless it is a RST segment or missing timestamps are
11344 	 * tolerated.
11345 	 * See section 3.2 of RFC 7323.
11346 	 */
11347 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11348 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11349 		retval = 0;
11350 		m_freem(m);
11351 		goto done_with_input;
11352 	}
11353 	/*
11354 	 * If echoed timestamp is later than the current time, fall back to
11355 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11356 	 * were used when this connection was established.
11357 	 */
11358 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11359 		to.to_tsecr -= tp->ts_offset;
11360 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11361 			to.to_tsecr = 0;
11362 	}
11363 	/*
11364 	 * If its the first time in we need to take care of options and
11365 	 * verify we can do SACK for rack!
11366 	 */
11367 	if (bbr->r_state == 0) {
11368 		/*
11369 		 * Process options only when we get SYN/ACK back. The SYN
11370 		 * case for incoming connections is handled in tcp_syncache.
11371 		 * According to RFC1323 the window field in a SYN (i.e., a
11372 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11373 		 * this is traditional behavior, may need to be cleaned up.
11374 		 */
11375 		if (bbr->rc_inp == NULL) {
11376 			bbr->rc_inp = inp;
11377 		}
11378 		/*
11379 		 * We need to init rc_inp here since its not init'd when
11380 		 * bbr_init is called
11381 		 */
11382 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11383 			if ((to.to_flags & TOF_SCALE) &&
11384 			    (tp->t_flags & TF_REQ_SCALE)) {
11385 				tp->t_flags |= TF_RCVD_SCALE;
11386 				tp->snd_scale = to.to_wscale;
11387 			} else
11388 				tp->t_flags &= ~TF_REQ_SCALE;
11389 			/*
11390 			 * Initial send window.  It will be updated with the
11391 			 * next incoming segment to the scaled value.
11392 			 */
11393 			tp->snd_wnd = th->th_win;
11394 			if ((to.to_flags & TOF_TS) &&
11395 			    (tp->t_flags & TF_REQ_TSTMP)) {
11396 				tp->t_flags |= TF_RCVD_TSTMP;
11397 				tp->ts_recent = to.to_tsval;
11398 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11399 			} else
11400 			    tp->t_flags &= ~TF_REQ_TSTMP;
11401 			if (to.to_flags & TOF_MSS)
11402 				tcp_mss(tp, to.to_mss);
11403 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11404 			    (to.to_flags & TOF_SACKPERM) == 0)
11405 				tp->t_flags &= ~TF_SACK_PERMIT;
11406 			if (IS_FASTOPEN(tp->t_flags)) {
11407 				if (to.to_flags & TOF_FASTOPEN) {
11408 					uint16_t mss;
11409 
11410 					if (to.to_flags & TOF_MSS)
11411 						mss = to.to_mss;
11412 					else
11413 						if ((inp->inp_vflag & INP_IPV6) != 0)
11414 							mss = TCP6_MSS;
11415 						else
11416 							mss = TCP_MSS;
11417 					tcp_fastopen_update_cache(tp, mss,
11418 					    to.to_tfo_len, to.to_tfo_cookie);
11419 				} else
11420 					tcp_fastopen_disable_path(tp);
11421 			}
11422 		}
11423 		/*
11424 		 * At this point we are at the initial call. Here we decide
11425 		 * if we are doing RACK or not. We do this by seeing if
11426 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11427 		 * we switch to the default code.
11428 		 */
11429 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11430 			/* Bail */
11431 			tcp_switch_back_to_default(tp);
11432 			(*tp->t_fb->tfb_tcp_do_segment)(tp, m, th, drop_hdrlen,
11433 			    tlen, iptos);
11434 			return (1);
11435 		}
11436 		/* Set the flag */
11437 		bbr->r_is_v6 = (inp->inp_vflag & INP_IPV6) != 0;
11438 		tcp_set_hpts(tp);
11439 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11440 	}
11441 	if (thflags & TH_ACK) {
11442 		/* Track ack types */
11443 		if (to.to_flags & TOF_SACK)
11444 			BBR_STAT_INC(bbr_acks_with_sacks);
11445 		else
11446 			BBR_STAT_INC(bbr_plain_acks);
11447 	}
11448 	/*
11449 	 * This is the one exception case where we set the rack state
11450 	 * always. All other times (timers etc) we must have a rack-state
11451 	 * set (so we assure we have done the checks above for SACK).
11452 	 */
11453 	if (thflags & TH_FIN)
11454 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11455 	if (bbr->r_state != tp->t_state)
11456 		bbr_set_state(tp, bbr, tiwin);
11457 
11458 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11459 		kern_prefetch(rsm, &prev_state);
11460 	prev_state = bbr->r_state;
11461 	bbr->rc_ack_was_delayed = 0;
11462 	lost = bbr->r_ctl.rc_lost;
11463 	bbr->rc_is_pkt_epoch_now = 0;
11464 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11465 		/* Get the real time into lcts and figure the real delay */
11466 		lcts = tcp_get_usecs(&ltv);
11467 		if (TSTMP_GT(lcts, cts)) {
11468 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11469 			bbr->rc_ack_was_delayed = 1;
11470 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11471 				     bbr->r_ctl.highest_hdwr_delay))
11472 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11473 		} else {
11474 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11475 			bbr->rc_ack_was_delayed = 0;
11476 		}
11477 	} else {
11478 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11479 		bbr->rc_ack_was_delayed = 0;
11480 	}
11481 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11482 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11483 		retval = 0;
11484 		m_freem(m);
11485 		goto done_with_input;
11486 	}
11487 	/*
11488 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11489 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11490 	 */
11491 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11492 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11493 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11494 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11495 		return (1);
11496 	}
11497 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11498 		bbr->r_ctl.rc_high_rwnd = tiwin;
11499 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11500 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11501 	bbr->rtt_valid = 0;
11502 	if (to.to_flags & TOF_TS) {
11503 		bbr->rc_ts_valid = 1;
11504 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11505 	} else {
11506 		bbr->rc_ts_valid = 0;
11507 		bbr->r_ctl.last_inbound_ts = 0;
11508 	}
11509 	retval = (*bbr->r_substate) (m, th, so,
11510 	    tp, &to, drop_hdrlen,
11511 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11512 	if (nxt_pkt == 0)
11513 		BBR_STAT_INC(bbr_rlock_left_ret0);
11514 	else
11515 		BBR_STAT_INC(bbr_rlock_left_ret1);
11516 	if (retval == 0) {
11517 		/*
11518 		 * If retval is 1 the tcb is unlocked and most likely the tp
11519 		 * is gone.
11520 		 */
11521 		INP_WLOCK_ASSERT(inp);
11522 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11523 		if (bbr->rc_is_pkt_epoch_now)
11524 			bbr_set_pktepoch(bbr, cts, __LINE__);
11525 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11526 		if (nxt_pkt == 0) {
11527 			if (bbr->r_wanted_output != 0) {
11528 				bbr->rc_output_starts_timer = 0;
11529 				did_out = 1;
11530 				if (tcp_output(tp) < 0)
11531 					return (1);
11532 			} else
11533 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11534 		}
11535 		if ((nxt_pkt == 0) &&
11536 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11537 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11538 		     (tp->t_flags & TF_DELACK) ||
11539 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11540 		      (tp->t_state <= TCPS_CLOSING)))) {
11541 			/*
11542 			 * We could not send (probably in the hpts but
11543 			 * stopped the timer)?
11544 			 */
11545 			if ((tp->snd_max == tp->snd_una) &&
11546 			    ((tp->t_flags & TF_DELACK) == 0) &&
11547 			    (tcp_in_hpts(tp)) &&
11548 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11549 				/*
11550 				 * keep alive not needed if we are hptsi
11551 				 * output yet
11552 				 */
11553 				;
11554 			} else {
11555 				if (tcp_in_hpts(tp)) {
11556 					tcp_hpts_remove(tp);
11557 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11558 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11559 						uint32_t del;
11560 
11561 						del = lcts - bbr->rc_pacer_started;
11562 						if (bbr->r_ctl.rc_last_delay_val > del) {
11563 							BBR_STAT_INC(bbr_force_timer_start);
11564 							bbr->r_ctl.rc_last_delay_val -= del;
11565 							bbr->rc_pacer_started = lcts;
11566 						} else {
11567 							/* We are late */
11568 							bbr->r_ctl.rc_last_delay_val = 0;
11569 							BBR_STAT_INC(bbr_force_output);
11570 							if (tcp_output(tp) < 0)
11571 								return (1);
11572 						}
11573 					}
11574 				}
11575 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11576 				    0);
11577 			}
11578 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11579 			/* Do we have the correct timer running? */
11580 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11581 		}
11582 		/* Clear the flag, it may have been cleared by output but we may not have  */
11583 		if ((nxt_pkt == 0) && (tp->t_flags2 & TF2_HPTS_CALLS))
11584 			tp->t_flags2 &= ~TF2_HPTS_CALLS;
11585 		/* Do we have a new state */
11586 		if (bbr->r_state != tp->t_state)
11587 			bbr_set_state(tp, bbr, tiwin);
11588 done_with_input:
11589 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11590 		if (did_out)
11591 			bbr->r_wanted_output = 0;
11592 	}
11593 	return (retval);
11594 }
11595 
11596 static void
11597 bbr_do_segment(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11598     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11599 {
11600 	struct timeval tv;
11601 	int retval;
11602 
11603 	/* First lets see if we have old packets */
11604 	if (!STAILQ_EMPTY(&tp->t_inqueue)) {
11605 		if (ctf_do_queued_segments(tp, 1)) {
11606 			m_freem(m);
11607 			return;
11608 		}
11609 	}
11610 	if (m->m_flags & M_TSTMP_LRO) {
11611 		mbuf_tstmp2timeval(m, &tv);
11612 	} else {
11613 		/* Should not be should we kassert instead? */
11614 		tcp_get_usecs(&tv);
11615 	}
11616 	retval = bbr_do_segment_nounlock(tp, m, th, drop_hdrlen, tlen, iptos,
11617 	    0, &tv);
11618 	if (retval == 0) {
11619 		INP_WUNLOCK(tptoinpcb(tp));
11620 	}
11621 }
11622 
11623 /*
11624  * Return how much data can be sent without violating the
11625  * cwnd or rwnd.
11626  */
11627 
11628 static inline uint32_t
11629 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11630     uint32_t avail, int32_t sb_offset, uint32_t cts)
11631 {
11632 	uint32_t len;
11633 
11634 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11635 		/* We never want to go over our peers rcv-window */
11636 		len = 0;
11637 	} else {
11638 		uint32_t flight;
11639 
11640 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11641 		if (flight >= sendwin) {
11642 			/*
11643 			 * We have in flight what we are allowed by cwnd (if
11644 			 * it was rwnd blocking it would have hit above out
11645 			 * >= tp->snd_wnd).
11646 			 */
11647 			return (0);
11648 		}
11649 		len = sendwin - flight;
11650 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11651 			/* We would send too much (beyond the rwnd) */
11652 			len = tp->snd_wnd - ctf_outstanding(tp);
11653 		}
11654 		if ((len + sb_offset) > avail) {
11655 			/*
11656 			 * We don't have that much in the SB, how much is
11657 			 * there?
11658 			 */
11659 			len = avail - sb_offset;
11660 		}
11661 	}
11662 	return (len);
11663 }
11664 
11665 static inline void
11666 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11667 {
11668 	if (error) {
11669 		return;
11670 	}
11671 	if (rsm) {
11672 		if (rsm->r_flags & BBR_TLP) {
11673 			/*
11674 			 * TLP should not count in retran count, but in its
11675 			 * own bin
11676 			 */
11677 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11678 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11679 		} else {
11680 			/* Retransmit */
11681 			tp->t_sndrexmitpack++;
11682 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11683 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11684 #ifdef STATS
11685 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11686 			    len);
11687 #endif
11688 		}
11689 		/*
11690 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11691 		 * sub-state
11692 		 */
11693 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11694 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11695 			/* Non probe_bw log in 1, 2, or 4. */
11696 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11697 		} else {
11698 			/*
11699 			 * Log our probe state 3, and log also 5-13 to show
11700 			 * us the recovery sub-state for the send. This
11701 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11702 			 */
11703 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11704 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11705 		}
11706 		/* Place in both 16's the totals of retransmitted */
11707 		counter_u64_add(bbr_state_lost[16], len);
11708 		counter_u64_add(bbr_state_resend[16], len);
11709 		/* Place in 17's the total sent */
11710 		counter_u64_add(bbr_state_resend[17], len);
11711 		counter_u64_add(bbr_state_lost[17], len);
11712 
11713 	} else {
11714 		/* New sends */
11715 		KMOD_TCPSTAT_INC(tcps_sndpack);
11716 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11717 		/* Place in 17's the total sent */
11718 		counter_u64_add(bbr_state_resend[17], len);
11719 		counter_u64_add(bbr_state_lost[17], len);
11720 #ifdef STATS
11721 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11722 		    len);
11723 #endif
11724 	}
11725 }
11726 
11727 static void
11728 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11729 {
11730 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11731 		/*
11732 		 * Limit the cwnd to not be above N x the target plus whats
11733 		 * is outstanding. The target is based on the current b/w
11734 		 * estimate.
11735 		 */
11736 		uint32_t target;
11737 
11738 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11739 		target += ctf_outstanding(tp);
11740 		target *= bbr_target_cwnd_mult_limit;
11741 		if (tp->snd_cwnd > target)
11742 			tp->snd_cwnd = target;
11743 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11744 	}
11745 }
11746 
11747 static int
11748 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11749 {
11750 	/*
11751 	 * "adv" is the amount we could increase the window, taking into
11752 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11753 	 */
11754 	int32_t adv;
11755 	int32_t oldwin;
11756 
11757 	adv = recwin;
11758 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11759 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11760 		if (adv > oldwin)
11761 			adv -= oldwin;
11762 		else {
11763 			/* We can't increase the window */
11764 			adv = 0;
11765 		}
11766 	} else
11767 		oldwin = 0;
11768 
11769 	/*
11770 	 * If the new window size ends up being the same as or less
11771 	 * than the old size when it is scaled, then don't force
11772 	 * a window update.
11773 	 */
11774 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11775 		return (0);
11776 
11777 	if (adv >= (2 * maxseg) &&
11778 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11779 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11780 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11781 		return (1);
11782 	}
11783 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11784 		return (1);
11785 	return (0);
11786 }
11787 
11788 /*
11789  * Return 0 on success and a errno on failure to send.
11790  * Note that a 0 return may not mean we sent anything
11791  * if the TCB was on the hpts. A non-zero return
11792  * does indicate the error we got from ip[6]_output.
11793  */
11794 static int
11795 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11796 {
11797 	struct socket *so;
11798 	int32_t len;
11799 	uint32_t cts;
11800 	uint32_t recwin, sendwin;
11801 	int32_t sb_offset;
11802 	int32_t flags, abandon, error = 0;
11803 	struct tcp_log_buffer *lgb = NULL;
11804 	struct mbuf *m;
11805 	struct mbuf *mb;
11806 	uint32_t if_hw_tsomaxsegcount = 0;
11807 	uint32_t if_hw_tsomaxsegsize = 0;
11808 	uint32_t if_hw_tsomax = 0;
11809 	struct ip *ip = NULL;
11810 	struct tcp_bbr *bbr;
11811 	struct tcphdr *th;
11812 	struct udphdr *udp = NULL;
11813 	u_char opt[TCP_MAXOLEN];
11814 	unsigned ipoptlen, optlen, hdrlen;
11815 	unsigned ulen;
11816 	uint32_t bbr_seq;
11817 	uint32_t delay_calc=0;
11818 	uint8_t doing_tlp = 0;
11819 	uint8_t local_options;
11820 #ifdef BBR_INVARIANTS
11821 	uint8_t doing_retran_from = 0;
11822 	uint8_t picked_up_retran = 0;
11823 #endif
11824 	uint8_t wanted_cookie = 0;
11825 	uint8_t more_to_rxt=0;
11826 	int32_t prefetch_so_done = 0;
11827 	int32_t prefetch_rsm = 0;
11828 	uint32_t tot_len = 0;
11829 	uint32_t maxseg, pace_max_segs, p_maxseg;
11830 	int32_t csum_flags = 0;
11831  	int32_t hw_tls;
11832 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11833 	unsigned ipsec_optlen = 0;
11834 
11835 #endif
11836 	volatile int32_t sack_rxmit;
11837 	struct bbr_sendmap *rsm = NULL;
11838 	int32_t tso, mtu;
11839 	struct tcpopt to;
11840 	int32_t slot = 0;
11841 	struct inpcb *inp;
11842 	struct sockbuf *sb;
11843 	bool hpts_calling;
11844 #ifdef INET6
11845 	struct ip6_hdr *ip6 = NULL;
11846 	int32_t isipv6;
11847 #endif
11848 	uint8_t app_limited = BBR_JR_SENT_DATA;
11849 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11850 	/* We take a cache hit here */
11851 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11852 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11853 	inp = bbr->rc_inp;
11854 	hpts_calling = !!(tp->t_flags2 & TF2_HPTS_CALLS);
11855 	tp->t_flags2 &= ~TF2_HPTS_CALLS;
11856 	so = inp->inp_socket;
11857 	sb = &so->so_snd;
11858 	if (tp->t_nic_ktls_xmit)
11859  		hw_tls = 1;
11860  	else
11861  		hw_tls = 0;
11862 	kern_prefetch(sb, &maxseg);
11863 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11864 	if (bbr_minseg(bbr) < maxseg) {
11865 		tcp_bbr_tso_size_check(bbr, cts);
11866 	}
11867 	/* Remove any flags that indicate we are pacing on the inp  */
11868 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11869 	p_maxseg = min(maxseg, pace_max_segs);
11870 	INP_WLOCK_ASSERT(inp);
11871 #ifdef TCP_OFFLOAD
11872 	if (tp->t_flags & TF_TOE)
11873 		return (tcp_offload_output(tp));
11874 #endif
11875 
11876 #ifdef INET6
11877 	if (bbr->r_state) {
11878 		/* Use the cache line loaded if possible */
11879 		isipv6 = bbr->r_is_v6;
11880 	} else {
11881 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11882 	}
11883 #endif
11884 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11885 	    tcp_in_hpts(tp)) {
11886 		/*
11887 		 * We are on the hpts for some timer but not hptsi output.
11888 		 * Possibly remove from the hpts so we can send/recv etc.
11889 		 */
11890 		if ((tp->t_flags & TF_ACKNOW) == 0) {
11891 			/*
11892 			 * No immediate demand right now to send an ack, but
11893 			 * the user may have read, making room for new data
11894 			 * (a window update). If so we may want to cancel
11895 			 * whatever timer is running (KEEP/DEL-ACK?) and
11896 			 * continue to send out a window update. Or we may
11897 			 * have gotten more data into the socket buffer to
11898 			 * send.
11899 			 */
11900 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
11901 				      (long)TCP_MAXWIN << tp->rcv_scale);
11902 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
11903 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
11904 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
11905 			    (tp->snd_max - tp->snd_una))) {
11906 				/*
11907 				 * Nothing new to send and no window update
11908 				 * is needed to send. Lets just return and
11909 				 * let the timer-run off.
11910 				 */
11911 				return (0);
11912 			}
11913 		}
11914 		tcp_hpts_remove(tp);
11915 		bbr_timer_cancel(bbr, __LINE__, cts);
11916 	}
11917 	if (bbr->r_ctl.rc_last_delay_val) {
11918 		/* Calculate a rough delay for early escape to sending  */
11919 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11920 			delay_calc = cts - bbr->rc_pacer_started;
11921 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11922 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11923 		else
11924 			delay_calc = 0;
11925 	}
11926 	/* Mark that we have called bbr_output(). */
11927 	if ((bbr->r_timer_override) ||
11928 	    (tp->t_state < TCPS_ESTABLISHED)) {
11929 		/* Timeouts or early states are exempt */
11930 		if (tcp_in_hpts(tp))
11931 			tcp_hpts_remove(tp);
11932 	} else if (tcp_in_hpts(tp)) {
11933 		if ((bbr->r_ctl.rc_last_delay_val) &&
11934 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11935 		    delay_calc) {
11936 			/*
11937 			 * We were being paced for output and the delay has
11938 			 * already exceeded when we were supposed to be
11939 			 * called, lets go ahead and pull out of the hpts
11940 			 * and call output.
11941 			 */
11942 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
11943 			bbr->r_ctl.rc_last_delay_val = 0;
11944 			tcp_hpts_remove(tp);
11945 		} else if (tp->t_state == TCPS_CLOSED) {
11946 			bbr->r_ctl.rc_last_delay_val = 0;
11947 			tcp_hpts_remove(tp);
11948 		} else {
11949 			/*
11950 			 * On the hpts, you shall not pass! even if ACKNOW
11951 			 * is on, we will when the hpts fires, unless of
11952 			 * course we are overdue.
11953 			 */
11954 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
11955 			return (0);
11956 		}
11957 	}
11958 	bbr->rc_cwnd_limited = 0;
11959 	if (bbr->r_ctl.rc_last_delay_val) {
11960 		/* recalculate the real delay and deal with over/under  */
11961 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11962 			delay_calc = cts - bbr->rc_pacer_started;
11963 		else
11964 			delay_calc = 0;
11965 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11966 			/* Setup the delay which will be added in */
11967 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11968 		else {
11969 			/*
11970 			 * We are early setup to adjust
11971 			 * our slot time.
11972 			 */
11973 			uint64_t merged_val;
11974 
11975 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
11976 			bbr->r_agg_early_set = 1;
11977 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
11978 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
11979 					/* Nope our previous late cancels out the early */
11980 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
11981 					bbr->r_agg_early_set = 0;
11982 					bbr->r_ctl.rc_agg_early = 0;
11983 				} else {
11984 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
11985 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
11986 				}
11987 			}
11988 			merged_val = bbr->rc_pacer_started;
11989 			merged_val <<= 32;
11990 			merged_val |= bbr->r_ctl.rc_last_delay_val;
11991 			bbr_log_pacing_delay_calc(bbr, hpts_calling,
11992 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
11993 						 bbr->r_agg_early_set, 3);
11994 			bbr->r_ctl.rc_last_delay_val = 0;
11995 			BBR_STAT_INC(bbr_early);
11996 			delay_calc = 0;
11997 		}
11998 	} else {
11999 		/* We were not delayed due to hptsi */
12000 		if (bbr->r_agg_early_set)
12001 			bbr->r_ctl.rc_agg_early = 0;
12002 		bbr->r_agg_early_set = 0;
12003 		delay_calc = 0;
12004 	}
12005 	if (delay_calc) {
12006 		/*
12007 		 * We had a hptsi delay which means we are falling behind on
12008 		 * sending at the expected rate. Calculate an extra amount
12009 		 * of data we can send, if any, to put us back on track.
12010 		 */
12011 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12012 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12013 		else
12014 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12015 	}
12016 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12017 	if ((tp->snd_una == tp->snd_max) &&
12018 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12019 	    (sbavail(sb))) {
12020 		/*
12021 		 * Ok we have been idle with nothing outstanding
12022 		 * we possibly need to start fresh with either a new
12023 		 * suite of states or a fast-ramp up.
12024 		 */
12025 		bbr_restart_after_idle(bbr,
12026 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12027 	}
12028 	/*
12029 	 * Now was there a hptsi delay where we are behind? We only count
12030 	 * being behind if: a) We are not in recovery. b) There was a delay.
12031 	 * <and> c) We had room to send something.
12032 	 *
12033 	 */
12034 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12035 		int retval;
12036 
12037 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12038 		if (retval != 0) {
12039 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12040 			/*
12041 			 * If timers want tcp_drop(), then pass error out,
12042 			 * otherwise suppress it.
12043 			 */
12044 			return (retval < 0 ? retval : 0);
12045 		}
12046 	}
12047 	bbr->rc_tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
12048 	if (hpts_calling &&
12049 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12050 		bbr->r_ctl.rc_last_delay_val = 0;
12051 	}
12052 	bbr->r_timer_override = 0;
12053 	bbr->r_wanted_output = 0;
12054 	/*
12055 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12056 	 * SYN|ACK and those sent by the retransmit timer.
12057 	 */
12058 	if (IS_FASTOPEN(tp->t_flags) &&
12059 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12060 	     (tp->t_state == TCPS_SYN_SENT)) &&
12061 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12062 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12063 		len = 0;
12064 		goto just_return_nolock;
12065 	}
12066 	/*
12067 	 * Before sending anything check for a state update. For hpts
12068 	 * calling without input this is important. If its input calling
12069 	 * then this was already done.
12070 	 */
12071 	if (bbr->rc_use_google == 0)
12072 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12073 again:
12074 	/*
12075 	 * If we've recently taken a timeout, snd_max will be greater than
12076 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12077 	 * for historic reasons the persist timer still uses it. This means
12078 	 * we have to look at it. All retransmissions that are not persits
12079 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12080 	 * end of this routine we pull snd_nxt always up to snd_max.
12081 	 */
12082 	doing_tlp = 0;
12083 #ifdef BBR_INVARIANTS
12084 	doing_retran_from = picked_up_retran = 0;
12085 #endif
12086 	error = 0;
12087 	tso = 0;
12088 	slot = 0;
12089 	mtu = 0;
12090 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12091 	sb_offset = tp->snd_max - tp->snd_una;
12092 	flags = tcp_outflags[tp->t_state];
12093 	sack_rxmit = 0;
12094 	len = 0;
12095 	rsm = NULL;
12096 	if (flags & TH_RST) {
12097 		SOCKBUF_LOCK(sb);
12098 		goto send;
12099 	}
12100 recheck_resend:
12101 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12102 		/* We need to always have one in reserve */
12103 		rsm = bbr_alloc(bbr);
12104 		if (rsm == NULL) {
12105 			error = ENOMEM;
12106 			/* Lie to get on the hpts */
12107 			tot_len = tp->t_maxseg;
12108 			if (hpts_calling)
12109 				/* Retry in a ms */
12110 				slot = 1001;
12111 			goto just_return_nolock;
12112 		}
12113 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12114 		bbr->r_ctl.rc_free_cnt++;
12115 		rsm = NULL;
12116 	}
12117 	/* What do we send, a resend? */
12118 	if (bbr->r_ctl.rc_resend == NULL) {
12119 		/* Check for rack timeout */
12120 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12121 		if (bbr->r_ctl.rc_resend) {
12122 #ifdef BBR_INVARIANTS
12123 			picked_up_retran = 1;
12124 #endif
12125 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12126 		}
12127 	}
12128 	if (bbr->r_ctl.rc_resend) {
12129 		rsm = bbr->r_ctl.rc_resend;
12130 #ifdef BBR_INVARIANTS
12131 		doing_retran_from = 1;
12132 #endif
12133 		/* Remove any TLP flags its a RACK or T-O */
12134 		rsm->r_flags &= ~BBR_TLP;
12135 		bbr->r_ctl.rc_resend = NULL;
12136 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12137 #ifdef BBR_INVARIANTS
12138 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12139 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12140 			goto recheck_resend;
12141 #else
12142 			/* TSNH */
12143 			rsm = NULL;
12144 			goto recheck_resend;
12145 #endif
12146 		}
12147 		if (rsm->r_flags & BBR_HAS_SYN) {
12148 			/* Only retransmit a SYN by itself */
12149 			len = 0;
12150 			if ((flags & TH_SYN) == 0) {
12151 				/* Huh something is wrong */
12152 				rsm->r_start++;
12153 				if (rsm->r_start == rsm->r_end) {
12154 					/* Clean it up, somehow we missed the ack? */
12155 					bbr_log_syn(tp, NULL);
12156 				} else {
12157 					/* TFO with data? */
12158 					rsm->r_flags &= ~BBR_HAS_SYN;
12159 					len = rsm->r_end - rsm->r_start;
12160 				}
12161 			} else {
12162 				/* Retransmitting SYN */
12163 				rsm = NULL;
12164 				SOCKBUF_LOCK(sb);
12165 				goto send;
12166 			}
12167 		} else
12168 			len = rsm->r_end - rsm->r_start;
12169 		if ((bbr->rc_resends_use_tso == 0) &&
12170 		    (len > maxseg)) {
12171 			len = maxseg;
12172 			more_to_rxt = 1;
12173 		}
12174 		sb_offset = rsm->r_start - tp->snd_una;
12175 		if (len > 0) {
12176 			sack_rxmit = 1;
12177 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12178 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12179 			    min(len, maxseg));
12180 		} else {
12181 			/* I dont think this can happen */
12182 			rsm = NULL;
12183 			goto recheck_resend;
12184 		}
12185 		BBR_STAT_INC(bbr_resends_set);
12186 	} else if (bbr->r_ctl.rc_tlp_send) {
12187 		/*
12188 		 * Tail loss probe
12189 		 */
12190 		doing_tlp = 1;
12191 		rsm = bbr->r_ctl.rc_tlp_send;
12192 		bbr->r_ctl.rc_tlp_send = NULL;
12193 		sack_rxmit = 1;
12194 		len = rsm->r_end - rsm->r_start;
12195 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12196 			len = maxseg;
12197 
12198 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12199 #ifdef BBR_INVARIANTS
12200 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12201 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12202 #else
12203 			/* TSNH */
12204 			rsm = NULL;
12205 			goto recheck_resend;
12206 #endif
12207 		}
12208 		sb_offset = rsm->r_start - tp->snd_una;
12209 		BBR_STAT_INC(bbr_tlp_set);
12210 	}
12211 	/*
12212 	 * Enforce a connection sendmap count limit if set
12213 	 * as long as we are not retransmiting.
12214 	 */
12215 	if ((rsm == NULL) &&
12216 	    (V_tcp_map_entries_limit > 0) &&
12217 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12218 		BBR_STAT_INC(bbr_alloc_limited);
12219 		if (!bbr->alloc_limit_reported) {
12220 			bbr->alloc_limit_reported = 1;
12221 			BBR_STAT_INC(bbr_alloc_limited_conns);
12222 		}
12223 		goto just_return_nolock;
12224 	}
12225 #ifdef BBR_INVARIANTS
12226 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12227 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12228 		    tp, bbr, rsm, sb_offset, len);
12229 	}
12230 #endif
12231 	/*
12232 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12233 	 * state flags.
12234 	 */
12235 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12236 		flags |= TH_FIN;
12237 	if (tp->t_flags & TF_NEEDSYN)
12238 		flags |= TH_SYN;
12239 
12240 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12241 		/* we are retransmitting the fin */
12242 		len--;
12243 		if (len) {
12244 			/*
12245 			 * When retransmitting data do *not* include the
12246 			 * FIN. This could happen from a TLP probe if we
12247 			 * allowed data with a FIN.
12248 			 */
12249 			flags &= ~TH_FIN;
12250 		}
12251 	} else if (rsm) {
12252 		if (flags & TH_FIN)
12253 			flags &= ~TH_FIN;
12254 	}
12255 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12256 		void *end_rsm;
12257 
12258 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12259 		if (end_rsm)
12260 			kern_prefetch(end_rsm, &prefetch_rsm);
12261 		prefetch_rsm = 1;
12262 	}
12263 	SOCKBUF_LOCK(sb);
12264 	/*
12265 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12266 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12267 	 * negative length.  This can also occur when TCP opens up its
12268 	 * congestion window while receiving additional duplicate acks after
12269 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12270 	 * the fast-retransmit.
12271 	 *
12272 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12273 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12274 	 * up 0.
12275 	 *
12276 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12277 	 * in which case len is already set.
12278 	 */
12279 	if (sack_rxmit == 0) {
12280 		uint32_t avail;
12281 
12282 		avail = sbavail(sb);
12283 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12284 			sb_offset = tp->snd_max - tp->snd_una;
12285 		else
12286 			sb_offset = 0;
12287 		if (bbr->rc_tlp_new_data) {
12288 			/* TLP is forcing out new data */
12289 			uint32_t tlplen;
12290 
12291 			doing_tlp = 1;
12292 			tlplen = maxseg;
12293 
12294 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12295 				tlplen = (uint32_t)(avail - sb_offset);
12296 			}
12297 			if (tlplen > tp->snd_wnd) {
12298 				len = tp->snd_wnd;
12299 			} else {
12300 				len = tlplen;
12301 			}
12302 			bbr->rc_tlp_new_data = 0;
12303 		} else {
12304 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12305 			if ((len < p_maxseg) &&
12306 			    (bbr->rc_in_persist == 0) &&
12307 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12308 			    ((avail - sb_offset) >= p_maxseg)) {
12309 				/*
12310 				 * We are not completing whats in the socket
12311 				 * buffer (i.e. there is at least a segment
12312 				 * waiting to send) and we have 2 or more
12313 				 * segments outstanding. There is no sense
12314 				 * of sending a little piece. Lets defer and
12315 				 * and wait until we can send a whole
12316 				 * segment.
12317 				 */
12318 				len = 0;
12319 			}
12320 			if (bbr->rc_in_persist) {
12321 				/*
12322 				 * We are in persists, figure out if
12323 				 * a retransmit is available (maybe the previous
12324 				 * persists we sent) or if we have to send new
12325 				 * data.
12326 				 */
12327 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12328 				if (rsm) {
12329 					len = rsm->r_end - rsm->r_start;
12330 					if (rsm->r_flags & BBR_HAS_FIN)
12331 						len--;
12332 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12333 						len = maxseg;
12334 					if (len > 1)
12335 						BBR_STAT_INC(bbr_persist_reneg);
12336 					/*
12337 					 * XXXrrs we could force the len to
12338 					 * 1 byte here to cause the chunk to
12339 					 * split apart.. but that would then
12340 					 * mean we always retransmit it as
12341 					 * one byte even after the window
12342 					 * opens.
12343 					 */
12344 					sack_rxmit = 1;
12345 					sb_offset = rsm->r_start - tp->snd_una;
12346 				} else {
12347 					/*
12348 					 * First time through in persists or peer
12349 					 * acked our one byte. Though we do have
12350 					 * to have something in the sb.
12351 					 */
12352 					len = 1;
12353 					sb_offset = 0;
12354 					if (avail == 0)
12355 					    len = 0;
12356 				}
12357 			}
12358 		}
12359 	}
12360 	if (prefetch_so_done == 0) {
12361 		kern_prefetch(so, &prefetch_so_done);
12362 		prefetch_so_done = 1;
12363 	}
12364 	/*
12365 	 * Lop off SYN bit if it has already been sent.  However, if this is
12366 	 * SYN-SENT state and if segment contains data and if we don't know
12367 	 * that foreign host supports TAO, suppress sending segment.
12368 	 */
12369 	if ((flags & TH_SYN) && (rsm == NULL) &&
12370 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12371 		if (tp->t_state != TCPS_SYN_RECEIVED)
12372 			flags &= ~TH_SYN;
12373 		/*
12374 		 * When sending additional segments following a TFO SYN|ACK,
12375 		 * do not include the SYN bit.
12376 		 */
12377 		if (IS_FASTOPEN(tp->t_flags) &&
12378 		    (tp->t_state == TCPS_SYN_RECEIVED))
12379 			flags &= ~TH_SYN;
12380 		sb_offset--, len++;
12381 		if (sbavail(sb) == 0)
12382 			len = 0;
12383 	} else if ((flags & TH_SYN) && rsm) {
12384 		/*
12385 		 * Subtract one from the len for the SYN being
12386 		 * retransmitted.
12387 		 */
12388 		len--;
12389 	}
12390 	/*
12391 	 * Be careful not to send data and/or FIN on SYN segments. This
12392 	 * measure is needed to prevent interoperability problems with not
12393 	 * fully conformant TCP implementations.
12394 	 */
12395 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12396 		len = 0;
12397 		flags &= ~TH_FIN;
12398 	}
12399 	/*
12400 	 * On TFO sockets, ensure no data is sent in the following cases:
12401 	 *
12402 	 *  - When retransmitting SYN|ACK on a passively-created socket
12403 	 *  - When retransmitting SYN on an actively created socket
12404 	 *  - When sending a zero-length cookie (cookie request) on an
12405 	 *    actively created socket
12406 	 *  - When the socket is in the CLOSED state (RST is being sent)
12407 	 */
12408 	if (IS_FASTOPEN(tp->t_flags) &&
12409 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12410 	     ((tp->t_state == TCPS_SYN_SENT) &&
12411 	      (tp->t_tfo_client_cookie_len == 0)) ||
12412 	     (flags & TH_RST))) {
12413 		len = 0;
12414 		sack_rxmit = 0;
12415 		rsm = NULL;
12416 	}
12417 	/* Without fast-open there should never be data sent on a SYN */
12418 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12419 		len = 0;
12420 	if (len <= 0) {
12421 		/*
12422 		 * If FIN has been sent but not acked, but we haven't been
12423 		 * called to retransmit, len will be < 0.  Otherwise, window
12424 		 * shrank after we sent into it.  If window shrank to 0,
12425 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12426 		 * window, and set the persist timer if it isn't already
12427 		 * going.  If the window didn't close completely, just wait
12428 		 * for an ACK.
12429 		 *
12430 		 * We also do a general check here to ensure that we will
12431 		 * set the persist timer when we have data to send, but a
12432 		 * 0-byte window. This makes sure the persist timer is set
12433 		 * even if the packet hits one of the "goto send" lines
12434 		 * below.
12435 		 */
12436 		len = 0;
12437 		if ((tp->snd_wnd == 0) &&
12438 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12439 		    (tp->snd_una == tp->snd_max) &&
12440 		    (sb_offset < (int)sbavail(sb))) {
12441 			/*
12442 			 * Not enough room in the rwnd to send
12443 			 * a paced segment out.
12444 			 */
12445 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12446 		}
12447 	} else if ((rsm == NULL) &&
12448 		   (doing_tlp == 0) &&
12449 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12450 		/*
12451 		 * We are not sending a full segment for
12452 		 * some reason. Should we not send anything (think
12453 		 * sws or persists)?
12454 		 */
12455 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12456 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12457 		    (len < (int)(sbavail(sb) - sb_offset))) {
12458 			/*
12459 			 * Here the rwnd is less than
12460 			 * the pacing size, this is not a retransmit,
12461 			 * we are established and
12462 			 * the send is not the last in the socket buffer
12463 			 * lets not send, and possibly enter persists.
12464 			 */
12465 			len = 0;
12466 			if (tp->snd_max == tp->snd_una)
12467 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12468 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12469 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12470 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12471 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12472 			   (len < bbr_minseg(bbr))) {
12473 			/*
12474 			 * Here we are not retransmitting, and
12475 			 * the cwnd is not so small that we could
12476 			 * not send at least a min size (rxt timer
12477 			 * not having gone off), We have 2 segments or
12478 			 * more already in flight, its not the tail end
12479 			 * of the socket buffer  and the cwnd is blocking
12480 			 * us from sending out minimum pacing segment size.
12481 			 * Lets not send anything.
12482 			 */
12483 			bbr->rc_cwnd_limited = 1;
12484 			len = 0;
12485 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12486 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12487 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12488 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12489 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12490 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12491 			/*
12492 			 * Here we have a send window but we have
12493 			 * filled it up and we can't send another pacing segment.
12494 			 * We also have in flight more than 2 segments
12495 			 * and we are not completing the sb i.e. we allow
12496 			 * the last bytes of the sb to go out even if
12497 			 * its not a full pacing segment.
12498 			 */
12499 			len = 0;
12500 		}
12501 	}
12502 	/* len will be >= 0 after this point. */
12503 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12504 	tcp_sndbuf_autoscale(tp, so, sendwin);
12505 	/*
12506 	 *
12507 	 */
12508 	if (bbr->rc_in_persist &&
12509 	    len &&
12510 	    (rsm == NULL) &&
12511 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12512 		/*
12513 		 * We are in persist, not doing a retransmit and don't have enough space
12514 		 * yet to send a full TSO. So is it at the end of the sb
12515 		 * if so we need to send else nuke to 0 and don't send.
12516 		 */
12517 		int sbleft;
12518 		if (sbavail(sb) > sb_offset)
12519 			sbleft = sbavail(sb) - sb_offset;
12520 		else
12521 			sbleft = 0;
12522 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12523 			/* not at end of sb lets not send */
12524 			len = 0;
12525 		}
12526 	}
12527 	/*
12528 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12529 	 * hardware).
12530 	 *
12531 	 * TSO may only be used if we are in a pure bulk sending state.  The
12532 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12533 	 * options prevent using TSO.  With TSO the TCP header is the same
12534 	 * (except for the sequence number) for all generated packets.  This
12535 	 * makes it impossible to transmit any options which vary per
12536 	 * generated segment or packet.
12537 	 *
12538 	 * IPv4 handling has a clear separation of ip options and ip header
12539 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12540 	 * does the right thing below to provide length of just ip options
12541 	 * and thus checking for ipoptlen is enough to decide if ip options
12542 	 * are present.
12543 	 */
12544 #ifdef INET6
12545 	if (isipv6)
12546 		ipoptlen = ip6_optlen(inp);
12547 	else
12548 #endif
12549 	if (inp->inp_options)
12550 		ipoptlen = inp->inp_options->m_len -
12551 		    offsetof(struct ipoption, ipopt_list);
12552 	else
12553 		ipoptlen = 0;
12554 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12555 	/*
12556 	 * Pre-calculate here as we save another lookup into the darknesses
12557 	 * of IPsec that way and can actually decide if TSO is ok.
12558 	 */
12559 #ifdef INET6
12560 	if (isipv6 && IPSEC_ENABLED(ipv6))
12561 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12562 #ifdef INET
12563 	else
12564 #endif
12565 #endif				/* INET6 */
12566 #ifdef INET
12567 	if (IPSEC_ENABLED(ipv4))
12568 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12569 #endif				/* INET */
12570 #endif				/* IPSEC */
12571 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12572 	ipoptlen += ipsec_optlen;
12573 #endif
12574 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12575 	    (len > maxseg) &&
12576 	    (tp->t_port == 0) &&
12577 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12578 	    tp->rcv_numsacks == 0 &&
12579 	    ipoptlen == 0)
12580 		tso = 1;
12581 
12582 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12583 	    (long)TCP_MAXWIN << tp->rcv_scale);
12584 	/*
12585 	 * Sender silly window avoidance.   We transmit under the following
12586 	 * conditions when len is non-zero:
12587 	 *
12588 	 * - We have a full segment (or more with TSO) - This is the last
12589 	 * buffer in a write()/send() and we are either idle or running
12590 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12591 	 * then 1/2 the maximum send window's worth of data (receiver may be
12592 	 * limited the window size) - we need to retransmit
12593 	 */
12594 	if (rsm)
12595 		goto send;
12596 	if (len) {
12597 		if (sack_rxmit)
12598 			goto send;
12599 		if (len >= p_maxseg)
12600 			goto send;
12601 		/*
12602 		 * NOTE! on localhost connections an 'ack' from the remote
12603 		 * end may occur synchronously with the output and cause us
12604 		 * to flush a buffer queued with moretocome.  XXX
12605 		 *
12606 		 */
12607 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12608 		    ((tp->t_flags & TF_NODELAY) ||
12609 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12610 		    (tp->t_flags & TF_NOPUSH) == 0) {
12611 			goto send;
12612 		}
12613 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12614 			goto send;
12615 		}
12616 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12617 			goto send;
12618 		}
12619 	}
12620 	/*
12621 	 * Sending of standalone window updates.
12622 	 *
12623 	 * Window updates are important when we close our window due to a
12624 	 * full socket buffer and are opening it again after the application
12625 	 * reads data from it.  Once the window has opened again and the
12626 	 * remote end starts to send again the ACK clock takes over and
12627 	 * provides the most current window information.
12628 	 *
12629 	 * We must avoid the silly window syndrome whereas every read from
12630 	 * the receive buffer, no matter how small, causes a window update
12631 	 * to be sent.  We also should avoid sending a flurry of window
12632 	 * updates when the socket buffer had queued a lot of data and the
12633 	 * application is doing small reads.
12634 	 *
12635 	 * Prevent a flurry of pointless window updates by only sending an
12636 	 * update when we can increase the advertized window by more than
12637 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12638 	 * full or is very small be more aggressive and send an update
12639 	 * whenever we can increase by two mss sized segments. In all other
12640 	 * situations the ACK's to new incoming data will carry further
12641 	 * window increases.
12642 	 *
12643 	 * Don't send an independent window update if a delayed ACK is
12644 	 * pending (it will get piggy-backed on it) or the remote side
12645 	 * already has done a half-close and won't send more data.  Skip
12646 	 * this if the connection is in T/TCP half-open state.
12647 	 */
12648 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12649 	    !(tp->t_flags & TF_DELACK) &&
12650 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12651 		/* Check to see if we should do a window update */
12652 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12653 			goto send;
12654 	}
12655 	/*
12656 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12657 	 * is also a catch-all for the retransmit timer timeout case.
12658 	 */
12659 	if (tp->t_flags & TF_ACKNOW) {
12660 		goto send;
12661 	}
12662 	if (flags & TH_RST) {
12663 		/* Always send a RST if one is due */
12664 		goto send;
12665 	}
12666 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12667 		goto send;
12668 	}
12669 	/*
12670 	 * If our state indicates that FIN should be sent and we have not
12671 	 * yet done so, then we need to send.
12672 	 */
12673 	if (flags & TH_FIN &&
12674 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12675 		goto send;
12676 	}
12677 	/*
12678 	 * No reason to send a segment, just return.
12679 	 */
12680 just_return:
12681 	SOCKBUF_UNLOCK(sb);
12682 just_return_nolock:
12683 	if (tot_len)
12684 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12685 	if (bbr->rc_no_pacing)
12686 		slot = 0;
12687 	if (tot_len == 0) {
12688 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12689 		    tp->snd_wnd) {
12690 			BBR_STAT_INC(bbr_rwnd_limited);
12691 			app_limited = BBR_JR_RWND_LIMITED;
12692 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12693 			if ((bbr->rc_in_persist == 0) &&
12694 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12695 			    (tp->snd_max == tp->snd_una) &&
12696 			    sbavail(&so->so_snd)) {
12697 				/* No send window.. we must enter persist */
12698 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12699 			}
12700 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12701 			BBR_STAT_INC(bbr_app_limited);
12702 			app_limited = BBR_JR_APP_LIMITED;
12703 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12704 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12705 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12706 			BBR_STAT_INC(bbr_cwnd_limited);
12707  			app_limited = BBR_JR_CWND_LIMITED;
12708 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12709 									bbr->r_ctl.rc_lost_bytes)));
12710 			bbr->rc_cwnd_limited = 1;
12711 		} else {
12712 			BBR_STAT_INC(bbr_app_limited);
12713 			app_limited = BBR_JR_APP_LIMITED;
12714 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12715 		}
12716 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12717 		bbr->r_agg_early_set = 0;
12718 		bbr->r_ctl.rc_agg_early = 0;
12719 		bbr->r_ctl.rc_last_delay_val = 0;
12720 	} else if (bbr->rc_use_google == 0)
12721 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12722 	/* Are we app limited? */
12723 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12724 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12725 		/**
12726 		 * We are application limited.
12727 		 */
12728 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12729 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12730 	}
12731 	if (tot_len == 0)
12732 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12733 	/* Dont update the time if we did not send */
12734 	bbr->r_ctl.rc_last_delay_val = 0;
12735 	bbr->rc_output_starts_timer = 1;
12736 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12737 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12738 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12739 		/* Make sure snd_nxt is drug up */
12740 		tp->snd_nxt = tp->snd_max;
12741 	}
12742 	return (error);
12743 
12744 send:
12745 	if (doing_tlp == 0) {
12746 		/*
12747 		 * Data not a TLP, and its not the rxt firing. If it is the
12748 		 * rxt firing, we want to leave the tlp_in_progress flag on
12749 		 * so we don't send another TLP. It has to be a rack timer
12750 		 * or normal send (response to acked data) to clear the tlp
12751 		 * in progress flag.
12752 		 */
12753 		bbr->rc_tlp_in_progress = 0;
12754 		bbr->rc_tlp_rtx_out = 0;
12755 	} else {
12756 		/*
12757 		 * Its a TLP.
12758 		 */
12759 		bbr->rc_tlp_in_progress = 1;
12760 	}
12761 	bbr_timer_cancel(bbr, __LINE__, cts);
12762 	if (rsm == NULL) {
12763 		if (sbused(sb) > 0) {
12764 			/*
12765 			 * This is sub-optimal. We only send a stand alone
12766 			 * FIN on its own segment.
12767 			 */
12768 			if (flags & TH_FIN) {
12769 				flags &= ~TH_FIN;
12770 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12771 					/* Lets not send this */
12772 					slot = 0;
12773 					goto just_return;
12774 				}
12775 			}
12776 		}
12777 	} else {
12778 		/*
12779 		 * We do *not* send a FIN on a retransmit if it has data.
12780 		 * The if clause here where len > 1 should never come true.
12781 		 */
12782 		if ((len > 0) &&
12783 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12784 		    (flags & TH_FIN))) {
12785 			flags &= ~TH_FIN;
12786 			len--;
12787 		}
12788 	}
12789 	SOCKBUF_LOCK_ASSERT(sb);
12790 	if (len > 0) {
12791 		if ((tp->snd_una == tp->snd_max) &&
12792 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12793 			/*
12794 			 * This qualifies as a RTT_PROBE session since we
12795 			 * drop the data outstanding to nothing and waited
12796 			 * more than bbr_rtt_probe_time.
12797 			 */
12798 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12799 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12800 		}
12801 		if (len >= maxseg)
12802 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12803 		else
12804 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12805 	}
12806 	/*
12807 	 * Before ESTABLISHED, force sending of initial options unless TCP
12808 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12809 	 * plus TCP options always fit in a single mbuf, leaving room for a
12810 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12811 	 * + optlen <= MCLBYTES
12812 	 */
12813 	optlen = 0;
12814 #ifdef INET6
12815 	if (isipv6)
12816 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12817 	else
12818 #endif
12819 		hdrlen = sizeof(struct tcpiphdr);
12820 
12821 	/*
12822 	 * Compute options for segment. We only have to care about SYN and
12823 	 * established connection segments.  Options for SYN-ACK segments
12824 	 * are handled in TCP syncache.
12825 	 */
12826 	to.to_flags = 0;
12827 	local_options = 0;
12828 	if ((tp->t_flags & TF_NOOPT) == 0) {
12829 		/* Maximum segment size. */
12830 		if (flags & TH_SYN) {
12831 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12832 			if (tp->t_port)
12833 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12834 			to.to_flags |= TOF_MSS;
12835 			/*
12836 			 * On SYN or SYN|ACK transmits on TFO connections,
12837 			 * only include the TFO option if it is not a
12838 			 * retransmit, as the presence of the TFO option may
12839 			 * have caused the original SYN or SYN|ACK to have
12840 			 * been dropped by a middlebox.
12841 			 */
12842 			if (IS_FASTOPEN(tp->t_flags) &&
12843 			    (tp->t_rxtshift == 0)) {
12844 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12845 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12846 					to.to_tfo_cookie =
12847 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12848 					to.to_flags |= TOF_FASTOPEN;
12849 					wanted_cookie = 1;
12850 				} else if (tp->t_state == TCPS_SYN_SENT) {
12851 					to.to_tfo_len =
12852 					    tp->t_tfo_client_cookie_len;
12853 					to.to_tfo_cookie =
12854 					    tp->t_tfo_cookie.client;
12855 					to.to_flags |= TOF_FASTOPEN;
12856 					wanted_cookie = 1;
12857 				}
12858 			}
12859 		}
12860 		/* Window scaling. */
12861 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12862 			to.to_wscale = tp->request_r_scale;
12863 			to.to_flags |= TOF_SCALE;
12864 		}
12865 		/* Timestamps. */
12866 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12867 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12868 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12869 			to.to_tsecr = tp->ts_recent;
12870 			to.to_flags |= TOF_TS;
12871 			local_options += TCPOLEN_TIMESTAMP + 2;
12872 		}
12873 		/* Set receive buffer autosizing timestamp. */
12874 		if (tp->rfbuf_ts == 0 &&
12875 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12876 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12877 		/* Selective ACK's. */
12878 		if (flags & TH_SYN)
12879 			to.to_flags |= TOF_SACKPERM;
12880 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12881 		    tp->rcv_numsacks > 0) {
12882 			to.to_flags |= TOF_SACK;
12883 			to.to_nsacks = tp->rcv_numsacks;
12884 			to.to_sacks = (u_char *)tp->sackblks;
12885 		}
12886 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
12887 		/* TCP-MD5 (RFC2385). */
12888 		if (tp->t_flags & TF_SIGNATURE)
12889 			to.to_flags |= TOF_SIGNATURE;
12890 #endif				/* TCP_SIGNATURE */
12891 
12892 		/* Processing the options. */
12893 		hdrlen += (optlen = tcp_addoptions(&to, opt));
12894 		/*
12895 		 * If we wanted a TFO option to be added, but it was unable
12896 		 * to fit, ensure no data is sent.
12897 		 */
12898 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
12899 		    !(to.to_flags & TOF_FASTOPEN))
12900 			len = 0;
12901 	}
12902 	if (tp->t_port) {
12903 		if (V_tcp_udp_tunneling_port == 0) {
12904 			/* The port was removed?? */
12905 			SOCKBUF_UNLOCK(&so->so_snd);
12906 			return (EHOSTUNREACH);
12907 		}
12908 		hdrlen += sizeof(struct udphdr);
12909 	}
12910 #ifdef INET6
12911 	if (isipv6)
12912 		ipoptlen = ip6_optlen(inp);
12913 	else
12914 #endif
12915 	if (inp->inp_options)
12916 		ipoptlen = inp->inp_options->m_len -
12917 		    offsetof(struct ipoption, ipopt_list);
12918 	else
12919 		ipoptlen = 0;
12920 	ipoptlen = 0;
12921 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12922 	ipoptlen += ipsec_optlen;
12923 #endif
12924 	if (bbr->rc_last_options != local_options) {
12925 		/*
12926 		 * Cache the options length this generally does not change
12927 		 * on a connection. We use this to calculate TSO.
12928 		 */
12929 		bbr->rc_last_options = local_options;
12930 	}
12931 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
12932 	p_maxseg = min(maxseg, pace_max_segs);
12933 	/*
12934 	 * Adjust data length if insertion of options will bump the packet
12935 	 * length beyond the t_maxseg length. Clear the FIN bit because we
12936 	 * cut off the tail of the segment.
12937 	 */
12938 	if (len > maxseg) {
12939 		if (len != 0 && (flags & TH_FIN)) {
12940 			flags &= ~TH_FIN;
12941 		}
12942 		if (tso) {
12943 			uint32_t moff;
12944 			int32_t max_len;
12945 
12946 			/* extract TSO information */
12947 			if_hw_tsomax = tp->t_tsomax;
12948 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
12949 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
12950 			KASSERT(ipoptlen == 0,
12951 			    ("%s: TSO can't do IP options", __func__));
12952 
12953 			/*
12954 			 * Check if we should limit by maximum payload
12955 			 * length:
12956 			 */
12957 			if (if_hw_tsomax != 0) {
12958 				/* compute maximum TSO length */
12959 				max_len = (if_hw_tsomax - hdrlen -
12960 				    max_linkhdr);
12961 				if (max_len <= 0) {
12962 					len = 0;
12963 				} else if (len > max_len) {
12964 					len = max_len;
12965 				}
12966 			}
12967 			/*
12968 			 * Prevent the last segment from being fractional
12969 			 * unless the send sockbuf can be emptied:
12970 			 */
12971 			if ((sb_offset + len) < sbavail(sb)) {
12972 				moff = len % (uint32_t)maxseg;
12973 				if (moff != 0) {
12974 					len -= moff;
12975 				}
12976 			}
12977 			/*
12978 			 * In case there are too many small fragments don't
12979 			 * use TSO:
12980 			 */
12981 			if (len <= maxseg) {
12982 				len = maxseg;
12983 				tso = 0;
12984 			}
12985 		} else {
12986 			/* Not doing TSO */
12987 			if (optlen + ipoptlen >= tp->t_maxseg) {
12988 				/*
12989 				 * Since we don't have enough space to put
12990 				 * the IP header chain and the TCP header in
12991 				 * one packet as required by RFC 7112, don't
12992 				 * send it. Also ensure that at least one
12993 				 * byte of the payload can be put into the
12994 				 * TCP segment.
12995 				 */
12996 				SOCKBUF_UNLOCK(&so->so_snd);
12997 				error = EMSGSIZE;
12998 				sack_rxmit = 0;
12999 				goto out;
13000 			}
13001 			len = maxseg;
13002 		}
13003 	} else {
13004 		/* Not doing TSO */
13005 		if_hw_tsomaxsegcount = 0;
13006 		tso = 0;
13007 	}
13008 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13009 	    ("%s: len > IP_MAXPACKET", __func__));
13010 #ifdef DIAGNOSTIC
13011 #ifdef INET6
13012 	if (max_linkhdr + hdrlen > MCLBYTES)
13013 #else
13014 	if (max_linkhdr + hdrlen > MHLEN)
13015 #endif
13016 		panic("tcphdr too big");
13017 #endif
13018 	/*
13019 	 * This KASSERT is here to catch edge cases at a well defined place.
13020 	 * Before, those had triggered (random) panic conditions further
13021 	 * down.
13022 	 */
13023 #ifdef BBR_INVARIANTS
13024 	if (sack_rxmit) {
13025 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13026 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13027 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13028 		}
13029 	}
13030 #endif
13031 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13032 	if ((len == 0) &&
13033 	    (flags & TH_FIN) &&
13034 	    (sbused(sb))) {
13035 		/*
13036 		 * We have outstanding data, don't send a fin by itself!.
13037 		 */
13038 		slot = 0;
13039 		goto just_return;
13040 	}
13041 	/*
13042 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13043 	 * and initialize the header from the template for sends on this
13044 	 * connection.
13045 	 */
13046 	if (len) {
13047 		uint32_t moff;
13048 
13049 		/*
13050 		 * We place a limit on sending with hptsi.
13051 		 */
13052 		if ((rsm == NULL) && len > pace_max_segs)
13053 			len = pace_max_segs;
13054 		if (len <= maxseg)
13055 			tso = 0;
13056 #ifdef INET6
13057 		if (MHLEN < hdrlen + max_linkhdr)
13058 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13059 		else
13060 #endif
13061 			m = m_gethdr(M_NOWAIT, MT_DATA);
13062 
13063 		if (m == NULL) {
13064 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13065 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13066 			SOCKBUF_UNLOCK(sb);
13067 			error = ENOBUFS;
13068 			sack_rxmit = 0;
13069 			goto out;
13070 		}
13071 		m->m_data += max_linkhdr;
13072 		m->m_len = hdrlen;
13073 		/*
13074 		 * Start the m_copy functions from the closest mbuf to the
13075 		 * sb_offset in the socket buffer chain.
13076 		 */
13077 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13078 #ifdef BBR_INVARIANTS
13079 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13080 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13081 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13082 				    doing_retran_from,
13083 				    picked_up_retran,
13084 				    doing_tlp);
13085 
13086 #endif
13087 			/*
13088 			 * In this messed up situation we have two choices,
13089 			 * a) pretend the send worked, and just start timers
13090 			 * and what not (not good since that may lead us
13091 			 * back here a lot). <or> b) Send the lowest segment
13092 			 * in the map. <or> c) Drop the connection. Lets do
13093 			 * <b> which if it continues to happen will lead to
13094 			 * <c> via timeouts.
13095 			 */
13096 			BBR_STAT_INC(bbr_offset_recovery);
13097 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13098 			sb_offset = 0;
13099 			if (rsm == NULL) {
13100 				sack_rxmit = 0;
13101 				len = sbavail(sb);
13102 			} else {
13103 				sack_rxmit = 1;
13104 				if (rsm->r_start != tp->snd_una) {
13105 					/*
13106 					 * Things are really messed up, <c>
13107 					 * is the only thing to do.
13108 					 */
13109 					BBR_STAT_INC(bbr_offset_drop);
13110 					SOCKBUF_UNLOCK(sb);
13111 					(void)m_free(m);
13112 					return (-EFAULT); /* tcp_drop() */
13113 				}
13114 				len = rsm->r_end - rsm->r_start;
13115 			}
13116 			if (len > sbavail(sb))
13117 				len = sbavail(sb);
13118 			if (len > maxseg)
13119 				len = maxseg;
13120 		}
13121 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13122 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13123 			m_copydata(mb, moff, (int)len,
13124 			    mtod(m, caddr_t)+hdrlen);
13125 			if (rsm == NULL)
13126 				sbsndptr_adv(sb, mb, len);
13127 			m->m_len += len;
13128 		} else {
13129 			struct sockbuf *msb;
13130 
13131 			if (rsm)
13132 				msb = NULL;
13133 			else
13134 				msb = sb;
13135 #ifdef BBR_INVARIANTS
13136 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13137 				if (rsm) {
13138 					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 ",
13139 					    tp, bbr, len, moff,
13140 					    sbavail(sb), rsm,
13141 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13142 					    doing_retran_from,
13143 					    picked_up_retran,
13144 					    doing_tlp, sack_rxmit);
13145 				} else {
13146 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13147 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13148 				}
13149 			}
13150 #endif
13151 			m->m_next = tcp_m_copym(
13152 				mb, moff, &len,
13153 				if_hw_tsomaxsegcount,
13154 				if_hw_tsomaxsegsize, msb,
13155 				((rsm == NULL) ? hw_tls : 0)
13156 #ifdef NETFLIX_COPY_ARGS
13157 				, NULL, NULL
13158 #endif
13159 				);
13160 			if (len <= maxseg) {
13161 				/*
13162 				 * Must have ran out of mbufs for the copy
13163 				 * shorten it to no longer need tso. Lets
13164 				 * not put on sendalot since we are low on
13165 				 * mbufs.
13166 				 */
13167 				tso = 0;
13168 			}
13169 			if (m->m_next == NULL) {
13170 				SOCKBUF_UNLOCK(sb);
13171 				(void)m_free(m);
13172 				error = ENOBUFS;
13173 				sack_rxmit = 0;
13174 				goto out;
13175 			}
13176 		}
13177 #ifdef BBR_INVARIANTS
13178 		if (tso && len < maxseg) {
13179 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13180 			    tp, len, maxseg);
13181 		}
13182 		if (tso && if_hw_tsomaxsegcount) {
13183 			int32_t seg_cnt = 0;
13184 			struct mbuf *foo;
13185 
13186 			foo = m;
13187 			while (foo) {
13188 				seg_cnt++;
13189 				foo = foo->m_next;
13190 			}
13191 			if (seg_cnt > if_hw_tsomaxsegcount) {
13192 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13193 			}
13194 		}
13195 #endif
13196 		/*
13197 		 * If we're sending everything we've got, set PUSH. (This
13198 		 * will keep happy those implementations which only give
13199 		 * data to the user when a buffer fills or a PUSH comes in.)
13200 		 */
13201 		if (sb_offset + len == sbused(sb) &&
13202 		    sbused(sb) &&
13203 		    !(flags & TH_SYN)) {
13204 			flags |= TH_PUSH;
13205 		}
13206 		SOCKBUF_UNLOCK(sb);
13207 	} else {
13208 		SOCKBUF_UNLOCK(sb);
13209 		if (tp->t_flags & TF_ACKNOW)
13210 			KMOD_TCPSTAT_INC(tcps_sndacks);
13211 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13212 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13213 		else
13214 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13215 
13216 		m = m_gethdr(M_NOWAIT, MT_DATA);
13217 		if (m == NULL) {
13218 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13219 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13220 			error = ENOBUFS;
13221 			/* Fudge the send time since we could not send */
13222 			sack_rxmit = 0;
13223 			goto out;
13224 		}
13225 #ifdef INET6
13226 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13227 		    MHLEN >= hdrlen) {
13228 			M_ALIGN(m, hdrlen);
13229 		} else
13230 #endif
13231 			m->m_data += max_linkhdr;
13232 		m->m_len = hdrlen;
13233 	}
13234 	SOCKBUF_UNLOCK_ASSERT(sb);
13235 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13236 #ifdef MAC
13237 	mac_inpcb_create_mbuf(inp, m);
13238 #endif
13239 #ifdef INET6
13240 	if (isipv6) {
13241 		ip6 = mtod(m, struct ip6_hdr *);
13242 		if (tp->t_port) {
13243 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13244 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13245 			udp->uh_dport = tp->t_port;
13246 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13247 			udp->uh_ulen = htons(ulen);
13248 			th = (struct tcphdr *)(udp + 1);
13249 		} else {
13250 			th = (struct tcphdr *)(ip6 + 1);
13251 		}
13252 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13253 	} else
13254 #endif				/* INET6 */
13255 	{
13256 		ip = mtod(m, struct ip *);
13257 		if (tp->t_port) {
13258 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13259 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13260 			udp->uh_dport = tp->t_port;
13261 			ulen = hdrlen + len - sizeof(struct ip);
13262 			udp->uh_ulen = htons(ulen);
13263 			th = (struct tcphdr *)(udp + 1);
13264 		} else {
13265 			th = (struct tcphdr *)(ip + 1);
13266 		}
13267 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13268 	}
13269 	/*
13270 	 * If we are doing retransmissions, then snd_nxt will not reflect
13271 	 * the first unsent octet.  For ACK only packets, we do not want the
13272 	 * sequence number of the retransmitted packet, we want the sequence
13273 	 * number of the next unsent octet.  So, if there is no data (and no
13274 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13275 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13276 	 * one byte beyond the right edge of the window, so use snd_nxt in
13277 	 * that case, since we know we aren't doing a retransmission.
13278 	 * (retransmit and persist are mutually exclusive...)
13279 	 */
13280 	if (sack_rxmit == 0) {
13281 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13282 			/* New data (including new persists) */
13283 			th->th_seq = htonl(tp->snd_max);
13284 			bbr_seq = tp->snd_max;
13285 		} else if (flags & TH_SYN) {
13286 			/* Syn's always send from iss */
13287 			th->th_seq = htonl(tp->iss);
13288 			bbr_seq = tp->iss;
13289 		} else if (flags & TH_FIN) {
13290 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13291 				/*
13292 				 * If we sent the fin already its 1 minus
13293 				 * snd_max
13294 				 */
13295 				th->th_seq = (htonl(tp->snd_max - 1));
13296 				bbr_seq = (tp->snd_max - 1);
13297 			} else {
13298 				/* First time FIN use snd_max */
13299 				th->th_seq = htonl(tp->snd_max);
13300 				bbr_seq = tp->snd_max;
13301 			}
13302 		} else {
13303 			/*
13304 			 * len == 0 and not persist we use snd_max, sending
13305 			 * an ack unless we have sent the fin then its 1
13306 			 * minus.
13307 			 */
13308 			/*
13309 			 * XXXRRS Question if we are in persists and we have
13310 			 * nothing outstanding to send and we have not sent
13311 			 * a FIN, we will send an ACK. In such a case it
13312 			 * might be better to send (tp->snd_una - 1) which
13313 			 * would force the peer to ack.
13314 			 */
13315 			if (tp->t_flags & TF_SENTFIN) {
13316 				th->th_seq = htonl(tp->snd_max - 1);
13317 				bbr_seq = (tp->snd_max - 1);
13318 			} else {
13319 				th->th_seq = htonl(tp->snd_max);
13320 				bbr_seq = tp->snd_max;
13321 			}
13322 		}
13323 	} else {
13324 		/* All retransmits use the rsm to guide the send */
13325 		th->th_seq = htonl(rsm->r_start);
13326 		bbr_seq = rsm->r_start;
13327 	}
13328 	th->th_ack = htonl(tp->rcv_nxt);
13329 	if (optlen) {
13330 		bcopy(opt, th + 1, optlen);
13331 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13332 	}
13333 	tcp_set_flags(th, flags);
13334 	/*
13335 	 * Calculate receive window.  Don't shrink window, but avoid silly
13336 	 * window syndrome.
13337 	 */
13338 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13339 				  recwin < maxseg)))
13340 		recwin = 0;
13341 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13342 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13343 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13344 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13345 		recwin = TCP_MAXWIN << tp->rcv_scale;
13346 
13347 	/*
13348 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13349 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13350 	 * handled in syncache.
13351 	 */
13352 	if (flags & TH_SYN)
13353 		th->th_win = htons((u_short)
13354 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13355 	else {
13356 		/* Avoid shrinking window with window scaling. */
13357 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13358 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13359 	}
13360 	/*
13361 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13362 	 * window.  This may cause the remote transmitter to stall.  This
13363 	 * flag tells soreceive() to disable delayed acknowledgements when
13364 	 * draining the buffer.  This can occur if the receiver is
13365 	 * attempting to read more data than can be buffered prior to
13366 	 * transmitting on the connection.
13367 	 */
13368 	if (th->th_win == 0) {
13369 		tp->t_sndzerowin++;
13370 		tp->t_flags |= TF_RXWIN0SENT;
13371 	} else
13372 		tp->t_flags &= ~TF_RXWIN0SENT;
13373 	/*
13374 	 * We don't support urgent data, but drag along
13375 	 * the pointer in case of a stack switch.
13376 	 */
13377 	tp->snd_up = tp->snd_una;
13378 	/*
13379 	 * Put TCP length in extended header, and then checksum extended
13380 	 * header and data.
13381 	 */
13382 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13383 
13384 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13385 	if (to.to_flags & TOF_SIGNATURE) {
13386 		/*
13387 		 * Calculate MD5 signature and put it into the place
13388 		 * determined before. NOTE: since TCP options buffer doesn't
13389 		 * point into mbuf's data, calculate offset and use it.
13390 		 */
13391 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13392 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13393 			/*
13394 			 * Do not send segment if the calculation of MD5
13395 			 * digest has failed.
13396 			 */
13397 			goto out;
13398 		}
13399 	}
13400 #endif
13401 
13402 #ifdef INET6
13403 	if (isipv6) {
13404 		/*
13405 		 * ip6_plen is not need to be filled now, and will be filled
13406 		 * in ip6_output.
13407 		 */
13408 		if (tp->t_port) {
13409 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13410 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13411 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13412 			th->th_sum = htons(0);
13413 			UDPSTAT_INC(udps_opackets);
13414 		} else {
13415 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13416 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13417 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13418 			    optlen + len, IPPROTO_TCP, 0);
13419 		}
13420 	}
13421 #endif
13422 #if defined(INET6) && defined(INET)
13423 	else
13424 #endif
13425 #ifdef INET
13426 	{
13427 		if (tp->t_port) {
13428 			m->m_pkthdr.csum_flags = CSUM_UDP;
13429 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13430 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13431 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13432 			th->th_sum = htons(0);
13433 			UDPSTAT_INC(udps_opackets);
13434 		} else {
13435 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13436 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13437 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13438 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13439 			    IPPROTO_TCP + len + optlen));
13440 		}
13441 		/* IP version must be set here for ipv4/ipv6 checking later */
13442 		KASSERT(ip->ip_v == IPVERSION,
13443 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13444 	}
13445 #endif
13446 
13447 	/*
13448 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13449 	 * header checksum is always provided. XXX: Fixme: This is currently
13450 	 * not the case for IPv6.
13451 	 */
13452 	if (tso) {
13453 		KASSERT(len > maxseg,
13454 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13455 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13456 		csum_flags |= CSUM_TSO;
13457 		m->m_pkthdr.tso_segsz = maxseg;
13458 	}
13459 	KASSERT(len + hdrlen == m_length(m, NULL),
13460 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13461 	    __func__, len, hdrlen, m_length(m, NULL)));
13462 
13463 #ifdef TCP_HHOOK
13464 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13465 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13466 #endif
13467 
13468 	/* Log to the black box */
13469 	if (tcp_bblogging_on(tp)) {
13470 		union tcp_log_stackspecific log;
13471 
13472 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13473 		/* Record info on type of transmission */
13474 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13475 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13476 		log.u_bbr.flex3 = maxseg;
13477 		log.u_bbr.flex4 = delay_calc;
13478 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13479 		log.u_bbr.flex5 <<= 1;
13480 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13481 		log.u_bbr.flex5 <<= 29;
13482 		log.u_bbr.flex5 |= tp->t_maxseg;
13483 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13484 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13485 		/* lets poke in the low and the high here for debugging */
13486 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13487 		if (rsm || sack_rxmit) {
13488 			if (doing_tlp)
13489 				log.u_bbr.flex8 = 2;
13490 			else
13491 				log.u_bbr.flex8 = 1;
13492 		} else {
13493 			log.u_bbr.flex8 = 0;
13494 		}
13495 		lgb = tcp_log_event(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13496 		    len, &log, false, NULL, NULL, 0, tv);
13497 	} else {
13498 		lgb = NULL;
13499 	}
13500 	/*
13501 	 * Fill in IP length and desired time to live and send to IP level.
13502 	 * There should be a better way to handle ttl and tos; we could keep
13503 	 * them in the template, but need a way to checksum without them.
13504 	 */
13505 	/*
13506 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13507 	 * because in6_cksum() need it.
13508 	 */
13509 #ifdef INET6
13510 	if (isipv6) {
13511 		/*
13512 		 * we separately set hoplimit for every segment, since the
13513 		 * user might want to change the value via setsockopt. Also,
13514 		 * desired default hop limit might be changed via Neighbor
13515 		 * Discovery.
13516 		 */
13517 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13518 
13519 		/*
13520 		 * Set the packet size here for the benefit of DTrace
13521 		 * probes. ip6_output() will set it properly; it's supposed
13522 		 * to include the option header lengths as well.
13523 		 */
13524 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13525 
13526 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13527 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13528 		else
13529 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13530 
13531 		if (tp->t_state == TCPS_SYN_SENT)
13532 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13533 
13534 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13535 		/* TODO: IPv6 IP6TOS_ECT bit on */
13536 		error = ip6_output(m, inp->in6p_outputopts,
13537 		    &inp->inp_route6,
13538 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13539 		    NULL, NULL, inp);
13540 
13541 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13542 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13543 	}
13544 #endif				/* INET6 */
13545 #if defined(INET) && defined(INET6)
13546 	else
13547 #endif
13548 #ifdef INET
13549 	{
13550 		ip->ip_len = htons(m->m_pkthdr.len);
13551 #ifdef INET6
13552 		if (isipv6)
13553 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13554 #endif				/* INET6 */
13555 		/*
13556 		 * If we do path MTU discovery, then we set DF on every
13557 		 * packet. This might not be the best thing to do according
13558 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13559 		 * the problem so it affects only the first tcp connection
13560 		 * with a host.
13561 		 *
13562 		 * NB: Don't set DF on small MTU/MSS to have a safe
13563 		 * fallback.
13564 		 */
13565 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13566 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13567 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13568 				ip->ip_off |= htons(IP_DF);
13569 			}
13570 		} else {
13571 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13572 		}
13573 
13574 		if (tp->t_state == TCPS_SYN_SENT)
13575 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13576 
13577 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13578 
13579 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13580 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13581 		    inp);
13582 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13583 			mtu = inp->inp_route.ro_nh->nh_mtu;
13584 	}
13585 #endif				/* INET */
13586 out:
13587 
13588 	if (lgb) {
13589 		lgb->tlb_errno = error;
13590 		lgb = NULL;
13591 	}
13592 	/*
13593 	 * In transmit state, time the transmission and arrange for the
13594 	 * retransmit.  In persist state, just set snd_max.
13595 	 */
13596 	if (error == 0) {
13597 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13598 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13599 		    (tp->t_flags & TF_SACK_PERMIT) &&
13600 		    tp->rcv_numsacks > 0)
13601 			tcp_clean_dsack_blocks(tp);
13602 		/* We sent an ack clear the bbr_segs_rcvd count */
13603 		bbr->output_error_seen = 0;
13604 		bbr->oerror_cnt = 0;
13605 		bbr->bbr_segs_rcvd = 0;
13606 		if (len == 0)
13607 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13608 		/* Do accounting for new sends */
13609 		if ((len > 0) && (rsm == NULL)) {
13610 			int idx;
13611 			if (tp->snd_una == tp->snd_max) {
13612 				/*
13613 				 * Special case to match google, when
13614 				 * nothing is in flight the delivered
13615 				 * time does get updated to the current
13616 				 * time (see tcp_rate_bsd.c).
13617 				 */
13618 				bbr->r_ctl.rc_del_time = cts;
13619 			}
13620 			if (len >= maxseg) {
13621 				idx = (len / maxseg) + 3;
13622 				if (idx >= TCP_MSS_ACCT_ATIMER)
13623 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13624 				else
13625 					counter_u64_add(bbr_out_size[idx], 1);
13626 			} else {
13627 				/* smaller than a MSS */
13628 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13629 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13630 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13631 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13632 			}
13633 		}
13634 	}
13635 	abandon = 0;
13636 	/*
13637 	 * We must do the send accounting before we log the output,
13638 	 * otherwise the state of the rsm could change and we account to the
13639 	 * wrong bucket.
13640 	 */
13641 	if (len > 0) {
13642 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13643 		if (error == 0) {
13644 			if (tp->snd_una == tp->snd_max)
13645 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13646 		}
13647 	}
13648 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13649 	    cts, mb, &abandon, rsm, 0, sb);
13650 	if (abandon) {
13651 		/*
13652 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13653 		 * sent we should hit this condition.
13654 		 */
13655 		return (0);
13656 	}
13657 	if (bbr->rc_in_persist == 0) {
13658 		/*
13659 		 * Advance snd_nxt over sequence space of this segment.
13660 		 */
13661 		if (error)
13662 			/* We don't log or do anything with errors */
13663 			goto skip_upd;
13664 
13665 		if (tp->snd_una == tp->snd_max &&
13666 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13667 			/*
13668 			 * Update the time we just added data since none was
13669 			 * outstanding.
13670 			 */
13671 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13672 			bbr->rc_tp->t_acktime  = ticks;
13673 		}
13674 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13675 			if (flags & TH_SYN) {
13676 				/*
13677 				 * Smack the snd_max to iss + 1
13678 				 * if its a FO we will add len below.
13679 				 */
13680 				tp->snd_max = tp->iss + 1;
13681 			}
13682 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13683 				tp->snd_max++;
13684 				tp->t_flags |= TF_SENTFIN;
13685 			}
13686 		}
13687 		if (sack_rxmit == 0)
13688 			tp->snd_max += len;
13689 skip_upd:
13690 		if ((error == 0) && len)
13691 			tot_len += len;
13692 	} else {
13693 		/* Persists case */
13694 		int32_t xlen = len;
13695 
13696 		if (error)
13697 			goto nomore;
13698 
13699 		if (flags & TH_SYN)
13700 			++xlen;
13701 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13702 			++xlen;
13703 			tp->t_flags |= TF_SENTFIN;
13704 		}
13705 		if (xlen && (tp->snd_una == tp->snd_max)) {
13706 			/*
13707 			 * Update the time we just added data since none was
13708 			 * outstanding.
13709 			 */
13710 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13711 			bbr->rc_tp->t_acktime = ticks;
13712 		}
13713 		if (sack_rxmit == 0)
13714 			tp->snd_max += xlen;
13715 		tot_len += (len + optlen + ipoptlen);
13716 	}
13717 nomore:
13718 	if (error) {
13719 		/*
13720 		 * Failures do not advance the seq counter above. For the
13721 		 * case of ENOBUFS we will fall out and become ack-clocked.
13722 		 * capping the cwnd at the current flight.
13723 		 * Everything else will just have to retransmit with the timer
13724 		 * (no pacer).
13725 		 */
13726 		SOCKBUF_UNLOCK_ASSERT(sb);
13727 		BBR_STAT_INC(bbr_saw_oerr);
13728 		/* Clear all delay/early tracks */
13729 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13730 		bbr->r_ctl.rc_agg_early = 0;
13731 		bbr->r_agg_early_set = 0;
13732 		bbr->output_error_seen = 1;
13733 		if (bbr->oerror_cnt < 0xf)
13734 			bbr->oerror_cnt++;
13735 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13736 			/* drop the session */
13737 			return (-ENETDOWN);
13738 		}
13739 		switch (error) {
13740 		case ENOBUFS:
13741 			/*
13742 			 * Make this guy have to get ack's to send
13743 			 * more but lets make sure we don't
13744 			 * slam him below a T-O (1MSS).
13745 			 */
13746 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13747 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13748 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13749 				if (tp->snd_cwnd < maxseg)
13750 					tp->snd_cwnd = maxseg;
13751 			}
13752 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13753 			BBR_STAT_INC(bbr_saw_enobuf);
13754 			if (bbr->bbr_hdrw_pacing)
13755 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13756 			else
13757 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13758 			/*
13759 			 * Here even in the enobuf's case we want to do our
13760 			 * state update. The reason being we may have been
13761 			 * called by the input function. If so we have had
13762 			 * things change.
13763 			 */
13764 			error = 0;
13765 			goto enobufs;
13766 		case EMSGSIZE:
13767 			/*
13768 			 * For some reason the interface we used initially
13769 			 * to send segments changed to another or lowered
13770 			 * its MTU. If TSO was active we either got an
13771 			 * interface without TSO capabilits or TSO was
13772 			 * turned off. If we obtained mtu from ip_output()
13773 			 * then update it and try again.
13774 			 */
13775 			/* Turn on tracing (or try to) */
13776 			{
13777 				int old_maxseg;
13778 
13779 				old_maxseg = tp->t_maxseg;
13780 				BBR_STAT_INC(bbr_saw_emsgsiz);
13781 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13782 				if (mtu != 0)
13783 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13784 				if (old_maxseg <= tp->t_maxseg) {
13785 					/* Huh it did not shrink? */
13786 					tp->t_maxseg = old_maxseg - 40;
13787 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13788 				}
13789 				/*
13790 				 * Nuke all other things that can interfere
13791 				 * with slot
13792 				 */
13793 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13794 					slot = bbr_get_pacing_delay(bbr,
13795 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13796 					    (tot_len + len), cts, 0);
13797 					if (slot < bbr_error_base_paceout)
13798 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13799 				} else
13800 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13801 				bbr->rc_output_starts_timer = 1;
13802 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13803 				    tot_len);
13804 				return (error);
13805 			}
13806 		case EPERM:
13807 			tp->t_softerror = error;
13808 			/* FALLTHROUGH */
13809 		case EHOSTDOWN:
13810 		case EHOSTUNREACH:
13811 		case ENETDOWN:
13812 		case ENETUNREACH:
13813 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13814 				tp->t_softerror = error;
13815 			}
13816 			/* FALLTHROUGH */
13817 		default:
13818 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13819 			bbr->rc_output_starts_timer = 1;
13820 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13821 			return (error);
13822 		}
13823 #ifdef STATS
13824 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13825 		    len &&
13826 		    (rsm == NULL) &&
13827 	    (bbr->rc_in_persist == 0)) {
13828 		tp->gput_seq = bbr_seq;
13829 		tp->gput_ack = bbr_seq +
13830 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13831 		tp->gput_ts = cts;
13832 		tp->t_flags |= TF_GPUTINPROG;
13833 #endif
13834 	}
13835 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13836 	if ((bbr->bbr_hdw_pace_ena) &&
13837 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13838 	    (bbr->rc_past_init_win) &&
13839 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13840 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13841 	    (inp->inp_route.ro_nh &&
13842 	     inp->inp_route.ro_nh->nh_ifp)) {
13843 		/*
13844 		 * We are past the initial window and
13845 		 * have at least one measurement so we
13846 		 * could use hardware pacing if its available.
13847 		 * We have an interface and we have not attempted
13848 		 * to setup hardware pacing, lets try to now.
13849 		 */
13850 		uint64_t rate_wanted;
13851 		int err = 0;
13852 
13853 		rate_wanted = bbr_get_hardware_rate(bbr);
13854 		bbr->bbr_attempt_hdwr_pace = 1;
13855 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13856 						      inp->inp_route.ro_nh->nh_ifp,
13857 						      rate_wanted,
13858 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
13859 						      &err, NULL);
13860 		if (bbr->r_ctl.crte) {
13861 			bbr_type_log_hdwr_pacing(bbr,
13862 						 bbr->r_ctl.crte->ptbl->rs_ifp,
13863 						 rate_wanted,
13864 						 bbr->r_ctl.crte->rate,
13865 						 __LINE__, cts, err);
13866 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
13867 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
13868 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
13869 			bbr->bbr_hdrw_pacing = 1;
13870 			/* Now what is our gain status? */
13871 			if (bbr->r_ctl.crte->rate < rate_wanted) {
13872 				/* We have a problem */
13873 				bbr_setup_less_of_rate(bbr, cts,
13874 						       bbr->r_ctl.crte->rate, rate_wanted);
13875 			} else {
13876 				/* We are good */
13877 				bbr->gain_is_limited = 0;
13878 				bbr->skip_gain = 0;
13879 			}
13880 			tcp_bbr_tso_size_check(bbr, cts);
13881 		} else {
13882 			bbr_type_log_hdwr_pacing(bbr,
13883 						 inp->inp_route.ro_nh->nh_ifp,
13884 						 rate_wanted,
13885 						 0,
13886 						 __LINE__, cts, err);
13887 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
13888 		}
13889 	}
13890 	if (bbr->bbr_hdrw_pacing) {
13891 		/*
13892 		 * Worry about cases where the route
13893 		 * changes or something happened that we
13894 		 * lost our hardware pacing possibly during
13895 		 * the last ip_output call.
13896 		 */
13897 		if (inp->inp_snd_tag == NULL) {
13898 			/* A change during ip output disabled hw pacing? */
13899 			bbr->bbr_hdrw_pacing = 0;
13900 		} else if ((inp->inp_route.ro_nh == NULL) ||
13901 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
13902 			/*
13903 			 * We had an interface or route change,
13904 			 * detach from the current hdwr pacing
13905 			 * and setup to re-attempt next go
13906 			 * round.
13907 			 */
13908 			bbr->bbr_hdrw_pacing = 0;
13909 			bbr->bbr_attempt_hdwr_pace = 0;
13910 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
13911 			tcp_bbr_tso_size_check(bbr, cts);
13912 		}
13913 	}
13914 	/*
13915 	 * Data sent (as far as we can tell). If this advertises a larger
13916 	 * window than any other segment, then remember the size of the
13917 	 * advertised window. Any pending ACK has now been sent.
13918 	 */
13919 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
13920 		tp->rcv_adv = tp->rcv_nxt + recwin;
13921 
13922 	tp->last_ack_sent = tp->rcv_nxt;
13923 	if ((error == 0) &&
13924 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
13925 	    (doing_tlp == 0) &&
13926 	    (tso == 0) &&
13927 	    (len > 0) &&
13928 	    ((flags & TH_RST) == 0) &&
13929 	    ((flags & TH_SYN) == 0) &&
13930 	    (IN_RECOVERY(tp->t_flags) == 0) &&
13931 	    (bbr->rc_in_persist == 0) &&
13932 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
13933 		/*
13934 		 * For non-tso we need to goto again until we have sent out
13935 		 * enough data to match what we are hptsi out every hptsi
13936 		 * interval.
13937 		 */
13938 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13939 			/* Make sure snd_nxt is drug up */
13940 			tp->snd_nxt = tp->snd_max;
13941 		}
13942 		if (rsm != NULL) {
13943 			rsm = NULL;
13944 			goto skip_again;
13945 		}
13946 		rsm = NULL;
13947 		sack_rxmit = 0;
13948 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13949 		goto again;
13950 	}
13951 skip_again:
13952 	if ((error == 0) && (flags & TH_FIN))
13953 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
13954 	if ((error == 0) && (flags & TH_RST))
13955 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13956 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
13957 		/*
13958 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
13959 		 * what we have sent so far
13960 		 */
13961 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
13962 		if (bbr->rc_no_pacing)
13963 			slot = 0;
13964 	}
13965 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13966 enobufs:
13967 	if (bbr->rc_use_google == 0)
13968 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
13969 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13970 							bbr->r_ctl.rc_lost_bytes)));
13971 	bbr->rc_output_starts_timer = 1;
13972 	if (bbr->bbr_use_rack_cheat &&
13973 	    (more_to_rxt ||
13974 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
13975 		/* Rack cheats and shotguns out all rxt's 1ms apart */
13976 		if (slot > 1000)
13977 			slot = 1000;
13978 	}
13979 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
13980 		/*
13981 		 * We don't change the tso size until some number of sends
13982 		 * to give the hardware commands time to get down
13983 		 * to the interface.
13984 		 */
13985 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
13986 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
13987 			bbr->hw_pacing_set = 1;
13988 			tcp_bbr_tso_size_check(bbr, cts);
13989 		}
13990 	}
13991 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
13992 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13993 		/* Make sure snd_nxt is drug up */
13994 		tp->snd_nxt = tp->snd_max;
13995 	}
13996 	return (error);
13997 
13998 }
13999 
14000 /*
14001  * See bbr_output_wtime() for return values.
14002  */
14003 static int
14004 bbr_output(struct tcpcb *tp)
14005 {
14006 	int32_t ret;
14007 	struct timeval tv;
14008 
14009 	NET_EPOCH_ASSERT();
14010 
14011 	INP_WLOCK_ASSERT(tptoinpcb(tp));
14012 	(void)tcp_get_usecs(&tv);
14013 	ret = bbr_output_wtime(tp, &tv);
14014 	return (ret);
14015 }
14016 
14017 static void
14018 bbr_mtu_chg(struct tcpcb *tp)
14019 {
14020 	struct tcp_bbr *bbr;
14021 	struct bbr_sendmap *rsm, *frsm = NULL;
14022 	uint32_t maxseg;
14023 
14024 	/*
14025 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14026 	 * over the current size as SACK_PASS so a retransmit will occur.
14027 	 */
14028 
14029 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14030 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14031 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14032 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14033 		/* Don't mess with ones acked (by sack?) */
14034 		if (rsm->r_flags & BBR_ACKED)
14035 			continue;
14036 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14037 			/*
14038 			 * We mark sack-passed on all the previous large
14039 			 * sends we did. This will force them to retransmit.
14040 			 */
14041 			rsm->r_flags |= BBR_SACK_PASSED;
14042 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14043 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14044 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14045 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14046 				rsm->r_flags |= BBR_MARKED_LOST;
14047 			}
14048 			if (frsm == NULL)
14049 				frsm = rsm;
14050 		}
14051 	}
14052 	if (frsm) {
14053 		bbr->r_ctl.rc_resend = frsm;
14054 	}
14055 }
14056 
14057 static int
14058 bbr_pru_options(struct tcpcb *tp, int flags)
14059 {
14060 	if (flags & PRUS_OOB)
14061 		return (EOPNOTSUPP);
14062 	return (0);
14063 }
14064 
14065 static void
14066 bbr_switch_failed(struct tcpcb *tp)
14067 {
14068 	/*
14069 	 * If a switch fails we only need to
14070 	 * make sure mbuf_queuing is still in place.
14071 	 * We also need to make sure we are still in
14072 	 * ticks granularity (though we should probably
14073 	 * change bbr to go to USECs).
14074 	 *
14075 	 * For timers we need to see if we are still in the
14076 	 * pacer (if our flags are up) if so we are good, if
14077 	 * not we need to get back into the pacer.
14078 	 */
14079 	struct timeval tv;
14080 	uint32_t cts;
14081 	uint32_t toval;
14082 	struct tcp_bbr *bbr;
14083 	struct hpts_diag diag;
14084 
14085 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
14086 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
14087 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
14088 	if (tp->t_in_hpts > IHPTS_NONE) {
14089 		return;
14090 	}
14091 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14092 	cts = tcp_get_usecs(&tv);
14093 	if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
14094 		if (TSTMP_GT(bbr->rc_pacer_started, cts)) {
14095 			toval = bbr->rc_pacer_started - cts;
14096 		} else {
14097 			/* one slot please */
14098 			toval = HPTS_TICKS_PER_SLOT;
14099 		}
14100 	} else if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
14101 		if (TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
14102 			toval = bbr->r_ctl.rc_timer_exp - cts;
14103 		} else {
14104 			/* one slot please */
14105 			toval = HPTS_TICKS_PER_SLOT;
14106 		}
14107 	} else
14108 		toval = HPTS_TICKS_PER_SLOT;
14109 	(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(toval),
14110 				   __LINE__, &diag);
14111 	bbr_log_hpts_diag(bbr, cts, &diag);
14112 }
14113 
14114 struct tcp_function_block __tcp_bbr = {
14115 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14116 	.tfb_tcp_output = bbr_output,
14117 	.tfb_do_queued_segments = ctf_do_queued_segments,
14118 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14119 	.tfb_tcp_do_segment = bbr_do_segment,
14120 	.tfb_tcp_ctloutput = bbr_ctloutput,
14121 	.tfb_tcp_fb_init = bbr_init,
14122 	.tfb_tcp_fb_fini = bbr_fini,
14123 	.tfb_tcp_timer_stop_all = bbr_stopall,
14124 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14125 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14126 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14127 	.tfb_pru_options = bbr_pru_options,
14128 	.tfb_switch_failed = bbr_switch_failed,
14129 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14130 };
14131 
14132 /*
14133  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14134  * socket option arguments.  When it re-acquires the lock after the copy, it
14135  * has to revalidate that the connection is still valid for the socket
14136  * option.
14137  */
14138 static int
14139 bbr_set_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14140 {
14141 	struct epoch_tracker et;
14142 	struct inpcb *inp = tptoinpcb(tp);
14143 	struct tcp_bbr *bbr;
14144 	int32_t error = 0, optval;
14145 
14146 	switch (sopt->sopt_level) {
14147 	case IPPROTO_IPV6:
14148 	case IPPROTO_IP:
14149 		return (tcp_default_ctloutput(tp, sopt));
14150 	}
14151 
14152 	switch (sopt->sopt_name) {
14153 	case TCP_RACK_PACE_MAX_SEG:
14154 	case TCP_RACK_MIN_TO:
14155 	case TCP_RACK_REORD_THRESH:
14156 	case TCP_RACK_REORD_FADE:
14157 	case TCP_RACK_TLP_THRESH:
14158 	case TCP_RACK_PKT_DELAY:
14159 	case TCP_BBR_ALGORITHM:
14160 	case TCP_BBR_TSLIMITS:
14161 	case TCP_BBR_IWINTSO:
14162 	case TCP_BBR_RECFORCE:
14163 	case TCP_BBR_STARTUP_PG:
14164 	case TCP_BBR_DRAIN_PG:
14165 	case TCP_BBR_RWND_IS_APP:
14166 	case TCP_BBR_PROBE_RTT_INT:
14167 	case TCP_BBR_PROBE_RTT_GAIN:
14168 	case TCP_BBR_PROBE_RTT_LEN:
14169 	case TCP_BBR_STARTUP_LOSS_EXIT:
14170 	case TCP_BBR_USEDEL_RATE:
14171 	case TCP_BBR_MIN_RTO:
14172 	case TCP_BBR_MAX_RTO:
14173 	case TCP_BBR_PACE_PER_SEC:
14174 	case TCP_DELACK:
14175 	case TCP_BBR_PACE_DEL_TAR:
14176 	case TCP_BBR_SEND_IWND_IN_TSO:
14177 	case TCP_BBR_EXTRA_STATE:
14178 	case TCP_BBR_UTTER_MAX_TSO:
14179 	case TCP_BBR_MIN_TOPACEOUT:
14180 	case TCP_BBR_FLOOR_MIN_TSO:
14181 	case TCP_BBR_TSTMP_RAISES:
14182 	case TCP_BBR_POLICER_DETECT:
14183 	case TCP_BBR_USE_RACK_CHEAT:
14184 	case TCP_DATA_AFTER_CLOSE:
14185 	case TCP_BBR_HDWR_PACE:
14186 	case TCP_BBR_PACE_SEG_MAX:
14187 	case TCP_BBR_PACE_SEG_MIN:
14188 	case TCP_BBR_PACE_CROSS:
14189 	case TCP_BBR_PACE_OH:
14190 	case TCP_BBR_TMR_PACE_OH:
14191 	case TCP_BBR_RACK_RTT_USE:
14192 	case TCP_BBR_RETRAN_WTSO:
14193 		break;
14194 	default:
14195 		return (tcp_default_ctloutput(tp, sopt));
14196 		break;
14197 	}
14198 	INP_WUNLOCK(inp);
14199 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14200 	if (error)
14201 		return (error);
14202 	INP_WLOCK(inp);
14203 	if (inp->inp_flags & INP_DROPPED) {
14204 		INP_WUNLOCK(inp);
14205 		return (ECONNRESET);
14206 	}
14207 	if (tp->t_fb != &__tcp_bbr) {
14208 		INP_WUNLOCK(inp);
14209 		return (ENOPROTOOPT);
14210 	}
14211 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14212 	switch (sopt->sopt_name) {
14213 	case TCP_BBR_PACE_PER_SEC:
14214 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14215 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14216 		break;
14217 	case TCP_BBR_PACE_DEL_TAR:
14218 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14219 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14220 		break;
14221 	case TCP_BBR_PACE_SEG_MAX:
14222 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14223 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14224 		break;
14225 	case TCP_BBR_PACE_SEG_MIN:
14226 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14227 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14228 		break;
14229 	case TCP_BBR_PACE_CROSS:
14230 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14231 		bbr->r_ctl.bbr_cross_over = optval;
14232 		break;
14233 	case TCP_BBR_ALGORITHM:
14234 		BBR_OPTS_INC(tcp_bbr_algorithm);
14235 		if (optval && (bbr->rc_use_google == 0)) {
14236 			/* Turn on the google mode */
14237 			bbr_google_mode_on(bbr);
14238 			if ((optval > 3) && (optval < 500)) {
14239 				/*
14240 				 * Must be at least greater than .3%
14241 				 * and must be less than 50.0%.
14242 				 */
14243 				bbr->r_ctl.bbr_google_discount = optval;
14244 			}
14245 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14246 			/* Turn off the google mode */
14247 			bbr_google_mode_off(bbr);
14248 		}
14249 		break;
14250 	case TCP_BBR_TSLIMITS:
14251 		BBR_OPTS_INC(tcp_bbr_tslimits);
14252 		if (optval == 1)
14253 			bbr->rc_use_ts_limit = 1;
14254 		else if (optval == 0)
14255 			bbr->rc_use_ts_limit = 0;
14256 		else
14257 			error = EINVAL;
14258 		break;
14259 
14260 	case TCP_BBR_IWINTSO:
14261 		BBR_OPTS_INC(tcp_bbr_iwintso);
14262 		if ((optval >= 0) && (optval < 128)) {
14263 			uint32_t twin;
14264 
14265 			bbr->rc_init_win = optval;
14266 			twin = bbr_initial_cwnd(bbr, tp);
14267 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14268 				tp->snd_cwnd = twin;
14269 			else
14270 				error = EBUSY;
14271 		} else
14272 			error = EINVAL;
14273 		break;
14274 	case TCP_BBR_STARTUP_PG:
14275 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14276 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14277 			bbr->r_ctl.rc_startup_pg = optval;
14278 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14279 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14280 			}
14281 		} else
14282 			error = EINVAL;
14283 		break;
14284 	case TCP_BBR_DRAIN_PG:
14285 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14286 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14287 			bbr->r_ctl.rc_drain_pg = optval;
14288 		else
14289 			error = EINVAL;
14290 		break;
14291 	case TCP_BBR_PROBE_RTT_LEN:
14292 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14293 		if (optval <= 1)
14294 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14295 		else
14296 			error = EINVAL;
14297 		break;
14298 	case TCP_BBR_PROBE_RTT_GAIN:
14299 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14300 		if (optval <= BBR_UNIT)
14301 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14302 		else
14303 			error = EINVAL;
14304 		break;
14305 	case TCP_BBR_PROBE_RTT_INT:
14306 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14307 		if (optval > 1000)
14308 			bbr->r_ctl.rc_probertt_int = optval;
14309 		else
14310 			error = EINVAL;
14311 		break;
14312 	case TCP_BBR_MIN_TOPACEOUT:
14313 		BBR_OPTS_INC(tcp_bbr_topaceout);
14314 		if (optval == 0) {
14315 			bbr->no_pacing_until = 0;
14316 			bbr->rc_no_pacing = 0;
14317 		} else if (optval <= 0x00ff) {
14318 			bbr->no_pacing_until = optval;
14319 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14320 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14321 				/* Turn on no pacing */
14322 				bbr->rc_no_pacing = 1;
14323 			}
14324 		} else
14325 			error = EINVAL;
14326 		break;
14327 	case TCP_BBR_STARTUP_LOSS_EXIT:
14328 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14329 		bbr->rc_loss_exit = optval;
14330 		break;
14331 	case TCP_BBR_USEDEL_RATE:
14332 		error = EINVAL;
14333 		break;
14334 	case TCP_BBR_MIN_RTO:
14335 		BBR_OPTS_INC(tcp_bbr_min_rto);
14336 		bbr->r_ctl.rc_min_rto_ms = optval;
14337 		break;
14338 	case TCP_BBR_MAX_RTO:
14339 		BBR_OPTS_INC(tcp_bbr_max_rto);
14340 		bbr->rc_max_rto_sec = optval;
14341 		break;
14342 	case TCP_RACK_MIN_TO:
14343 		/* Minimum time between rack t-o's in ms */
14344 		BBR_OPTS_INC(tcp_rack_min_to);
14345 		bbr->r_ctl.rc_min_to = optval;
14346 		break;
14347 	case TCP_RACK_REORD_THRESH:
14348 		/* RACK reorder threshold (shift amount) */
14349 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14350 		if ((optval > 0) && (optval < 31))
14351 			bbr->r_ctl.rc_reorder_shift = optval;
14352 		else
14353 			error = EINVAL;
14354 		break;
14355 	case TCP_RACK_REORD_FADE:
14356 		/* Does reordering fade after ms time */
14357 		BBR_OPTS_INC(tcp_rack_reord_fade);
14358 		bbr->r_ctl.rc_reorder_fade = optval;
14359 		break;
14360 	case TCP_RACK_TLP_THRESH:
14361 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14362 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14363 		if (optval)
14364 			bbr->rc_tlp_threshold = optval;
14365 		else
14366 			error = EINVAL;
14367 		break;
14368 	case TCP_BBR_USE_RACK_CHEAT:
14369 		BBR_OPTS_INC(tcp_use_rackcheat);
14370 		if (bbr->rc_use_google) {
14371 			error = EINVAL;
14372 			break;
14373 		}
14374 		BBR_OPTS_INC(tcp_rack_cheat);
14375 		if (optval)
14376 			bbr->bbr_use_rack_cheat = 1;
14377 		else
14378 			bbr->bbr_use_rack_cheat = 0;
14379 		break;
14380 	case TCP_BBR_FLOOR_MIN_TSO:
14381 		BBR_OPTS_INC(tcp_utter_max_tso);
14382 		if ((optval >= 0) && (optval < 40))
14383 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14384 		else
14385 			error = EINVAL;
14386 		break;
14387 	case TCP_BBR_UTTER_MAX_TSO:
14388 		BBR_OPTS_INC(tcp_utter_max_tso);
14389 		if ((optval >= 0) && (optval < 0xffff))
14390 			bbr->r_ctl.bbr_utter_max = optval;
14391 		else
14392 			error = EINVAL;
14393 		break;
14394 
14395 	case TCP_BBR_EXTRA_STATE:
14396 		BBR_OPTS_INC(tcp_extra_state);
14397 		if (optval)
14398 			bbr->rc_use_idle_restart = 1;
14399 		else
14400 			bbr->rc_use_idle_restart = 0;
14401 		break;
14402 	case TCP_BBR_SEND_IWND_IN_TSO:
14403 		BBR_OPTS_INC(tcp_iwnd_tso);
14404 		if (optval) {
14405 			bbr->bbr_init_win_cheat = 1;
14406 			if (bbr->rc_past_init_win == 0) {
14407 				uint32_t cts;
14408 				cts = tcp_get_usecs(&bbr->rc_tv);
14409 				tcp_bbr_tso_size_check(bbr, cts);
14410 			}
14411 		} else
14412 			bbr->bbr_init_win_cheat = 0;
14413 		break;
14414 	case TCP_BBR_HDWR_PACE:
14415 		BBR_OPTS_INC(tcp_hdwr_pacing);
14416 		if (optval){
14417 			bbr->bbr_hdw_pace_ena = 1;
14418 			bbr->bbr_attempt_hdwr_pace = 0;
14419 		} else {
14420 			bbr->bbr_hdw_pace_ena = 0;
14421 #ifdef RATELIMIT
14422 			if (bbr->r_ctl.crte != NULL) {
14423 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14424 				bbr->r_ctl.crte = NULL;
14425 			}
14426 #endif
14427 		}
14428 		break;
14429 
14430 	case TCP_DELACK:
14431 		BBR_OPTS_INC(tcp_delack);
14432 		if (optval < 100) {
14433 			if (optval == 0) /* off */
14434 				tp->t_delayed_ack = 0;
14435 			else if (optval == 1) /* on which is 2 */
14436 				tp->t_delayed_ack = 2;
14437 			else /* higher than 2 and less than 100 */
14438 				tp->t_delayed_ack = optval;
14439 			if (tp->t_flags & TF_DELACK) {
14440 				tp->t_flags &= ~TF_DELACK;
14441 				tp->t_flags |= TF_ACKNOW;
14442 				NET_EPOCH_ENTER(et);
14443 				bbr_output(tp);
14444 				NET_EPOCH_EXIT(et);
14445 			}
14446 		} else
14447 			error = EINVAL;
14448 		break;
14449 	case TCP_RACK_PKT_DELAY:
14450 		/* RACK added ms i.e. rack-rtt + reord + N */
14451 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14452 		bbr->r_ctl.rc_pkt_delay = optval;
14453 		break;
14454 
14455 	case TCP_BBR_RETRAN_WTSO:
14456 		BBR_OPTS_INC(tcp_retran_wtso);
14457 		if (optval)
14458 			bbr->rc_resends_use_tso = 1;
14459 		else
14460 			bbr->rc_resends_use_tso = 0;
14461 		break;
14462 	case TCP_DATA_AFTER_CLOSE:
14463 		BBR_OPTS_INC(tcp_data_ac);
14464 		if (optval)
14465 			bbr->rc_allow_data_af_clo = 1;
14466 		else
14467 			bbr->rc_allow_data_af_clo = 0;
14468 		break;
14469 	case TCP_BBR_POLICER_DETECT:
14470 		BBR_OPTS_INC(tcp_policer_det);
14471 		if (bbr->rc_use_google == 0)
14472 			error = EINVAL;
14473 		else if (optval)
14474 			bbr->r_use_policer = 1;
14475 		else
14476 			bbr->r_use_policer = 0;
14477 		break;
14478 
14479 	case TCP_BBR_TSTMP_RAISES:
14480 		BBR_OPTS_INC(tcp_ts_raises);
14481 		if (optval)
14482 			bbr->ts_can_raise = 1;
14483 		else
14484 			bbr->ts_can_raise = 0;
14485 		break;
14486 	case TCP_BBR_TMR_PACE_OH:
14487 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14488 		if (bbr->rc_use_google) {
14489 			error = EINVAL;
14490 		} else {
14491 			if (optval)
14492 				bbr->r_ctl.rc_incr_tmrs = 1;
14493 			else
14494 				bbr->r_ctl.rc_incr_tmrs = 0;
14495 		}
14496 		break;
14497 	case TCP_BBR_PACE_OH:
14498 		BBR_OPTS_INC(tcp_pacing_oh);
14499 		if (bbr->rc_use_google) {
14500 			error = EINVAL;
14501 		} else {
14502 			if (optval > (BBR_INCL_TCP_OH|
14503 				      BBR_INCL_IP_OH|
14504 				      BBR_INCL_ENET_OH)) {
14505 				error = EINVAL;
14506 				break;
14507 			}
14508 			if (optval & BBR_INCL_TCP_OH)
14509 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14510 			else
14511 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14512 			if (optval & BBR_INCL_IP_OH)
14513 				bbr->r_ctl.rc_inc_ip_oh = 1;
14514 			else
14515 				bbr->r_ctl.rc_inc_ip_oh = 0;
14516 			if (optval & BBR_INCL_ENET_OH)
14517 				bbr->r_ctl.rc_inc_enet_oh = 1;
14518 			else
14519 				bbr->r_ctl.rc_inc_enet_oh = 0;
14520 		}
14521 		break;
14522 	default:
14523 		return (tcp_default_ctloutput(tp, sopt));
14524 		break;
14525 	}
14526 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14527 	INP_WUNLOCK(inp);
14528 	return (error);
14529 }
14530 
14531 /*
14532  * return 0 on success, error-num on failure
14533  */
14534 static int
14535 bbr_get_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14536 {
14537 	struct inpcb *inp = tptoinpcb(tp);
14538 	struct tcp_bbr *bbr;
14539 	int32_t error, optval;
14540 
14541 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14542 	if (bbr == NULL) {
14543 		INP_WUNLOCK(inp);
14544 		return (EINVAL);
14545 	}
14546 	/*
14547 	 * Because all our options are either boolean or an int, we can just
14548 	 * pull everything into optval and then unlock and copy. If we ever
14549 	 * add a option that is not a int, then this will have quite an
14550 	 * impact to this routine.
14551 	 */
14552 	switch (sopt->sopt_name) {
14553 	case TCP_BBR_PACE_PER_SEC:
14554 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14555 		break;
14556 	case TCP_BBR_PACE_DEL_TAR:
14557 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14558 		break;
14559 	case TCP_BBR_PACE_SEG_MAX:
14560 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14561 		break;
14562 	case TCP_BBR_MIN_TOPACEOUT:
14563 		optval = bbr->no_pacing_until;
14564 		break;
14565 	case TCP_BBR_PACE_SEG_MIN:
14566 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14567 		break;
14568 	case TCP_BBR_PACE_CROSS:
14569 		optval = bbr->r_ctl.bbr_cross_over;
14570 		break;
14571 	case TCP_BBR_ALGORITHM:
14572 		optval = bbr->rc_use_google;
14573 		break;
14574 	case TCP_BBR_TSLIMITS:
14575 		optval = bbr->rc_use_ts_limit;
14576 		break;
14577 	case TCP_BBR_IWINTSO:
14578 		optval = bbr->rc_init_win;
14579 		break;
14580 	case TCP_BBR_STARTUP_PG:
14581 		optval = bbr->r_ctl.rc_startup_pg;
14582 		break;
14583 	case TCP_BBR_DRAIN_PG:
14584 		optval = bbr->r_ctl.rc_drain_pg;
14585 		break;
14586 	case TCP_BBR_PROBE_RTT_INT:
14587 		optval = bbr->r_ctl.rc_probertt_int;
14588 		break;
14589 	case TCP_BBR_PROBE_RTT_LEN:
14590 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14591 		break;
14592 	case TCP_BBR_PROBE_RTT_GAIN:
14593 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14594 		break;
14595 	case TCP_BBR_STARTUP_LOSS_EXIT:
14596 		optval = bbr->rc_loss_exit;
14597 		break;
14598 	case TCP_BBR_USEDEL_RATE:
14599 		error = EINVAL;
14600 		break;
14601 	case TCP_BBR_MIN_RTO:
14602 		optval = bbr->r_ctl.rc_min_rto_ms;
14603 		break;
14604 	case TCP_BBR_MAX_RTO:
14605 		optval = bbr->rc_max_rto_sec;
14606 		break;
14607 	case TCP_RACK_PACE_MAX_SEG:
14608 		/* Max segments in a pace */
14609 		optval = bbr->r_ctl.rc_pace_max_segs;
14610 		break;
14611 	case TCP_RACK_MIN_TO:
14612 		/* Minimum time between rack t-o's in ms */
14613 		optval = bbr->r_ctl.rc_min_to;
14614 		break;
14615 	case TCP_RACK_REORD_THRESH:
14616 		/* RACK reorder threshold (shift amount) */
14617 		optval = bbr->r_ctl.rc_reorder_shift;
14618 		break;
14619 	case TCP_RACK_REORD_FADE:
14620 		/* Does reordering fade after ms time */
14621 		optval = bbr->r_ctl.rc_reorder_fade;
14622 		break;
14623 	case TCP_BBR_USE_RACK_CHEAT:
14624 		/* Do we use the rack cheat for rxt */
14625 		optval = bbr->bbr_use_rack_cheat;
14626 		break;
14627 	case TCP_BBR_FLOOR_MIN_TSO:
14628 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14629 		break;
14630 	case TCP_BBR_UTTER_MAX_TSO:
14631 		optval = bbr->r_ctl.bbr_utter_max;
14632 		break;
14633 	case TCP_BBR_SEND_IWND_IN_TSO:
14634 		/* Do we send TSO size segments initially */
14635 		optval = bbr->bbr_init_win_cheat;
14636 		break;
14637 	case TCP_BBR_EXTRA_STATE:
14638 		optval = bbr->rc_use_idle_restart;
14639 		break;
14640 	case TCP_RACK_TLP_THRESH:
14641 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14642 		optval = bbr->rc_tlp_threshold;
14643 		break;
14644 	case TCP_RACK_PKT_DELAY:
14645 		/* RACK added ms i.e. rack-rtt + reord + N */
14646 		optval = bbr->r_ctl.rc_pkt_delay;
14647 		break;
14648 	case TCP_BBR_RETRAN_WTSO:
14649 		optval = bbr->rc_resends_use_tso;
14650 		break;
14651 	case TCP_DATA_AFTER_CLOSE:
14652 		optval = bbr->rc_allow_data_af_clo;
14653 		break;
14654 	case TCP_DELACK:
14655 		optval = tp->t_delayed_ack;
14656 		break;
14657 	case TCP_BBR_HDWR_PACE:
14658 		optval = bbr->bbr_hdw_pace_ena;
14659 		break;
14660 	case TCP_BBR_POLICER_DETECT:
14661 		optval = bbr->r_use_policer;
14662 		break;
14663 	case TCP_BBR_TSTMP_RAISES:
14664 		optval = bbr->ts_can_raise;
14665 		break;
14666 	case TCP_BBR_TMR_PACE_OH:
14667 		optval = bbr->r_ctl.rc_incr_tmrs;
14668 		break;
14669 	case TCP_BBR_PACE_OH:
14670 		optval = 0;
14671 		if (bbr->r_ctl.rc_inc_tcp_oh)
14672 			optval |= BBR_INCL_TCP_OH;
14673 		if (bbr->r_ctl.rc_inc_ip_oh)
14674 			optval |= BBR_INCL_IP_OH;
14675 		if (bbr->r_ctl.rc_inc_enet_oh)
14676 			optval |= BBR_INCL_ENET_OH;
14677 		break;
14678 	default:
14679 		return (tcp_default_ctloutput(tp, sopt));
14680 		break;
14681 	}
14682 	INP_WUNLOCK(inp);
14683 	error = sooptcopyout(sopt, &optval, sizeof optval);
14684 	return (error);
14685 }
14686 
14687 /*
14688  * return 0 on success, error-num on failure
14689  */
14690 static int
14691 bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt)
14692 {
14693 	if (sopt->sopt_dir == SOPT_SET) {
14694 		return (bbr_set_sockopt(tp, sopt));
14695 	} else if (sopt->sopt_dir == SOPT_GET) {
14696 		return (bbr_get_sockopt(tp, sopt));
14697 	} else {
14698 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14699 	}
14700 }
14701 
14702 static const char *bbr_stack_names[] = {
14703 	__XSTRING(STACKNAME),
14704 #ifdef STACKALIAS
14705 	__XSTRING(STACKALIAS),
14706 #endif
14707 };
14708 
14709 static bool bbr_mod_inited = false;
14710 
14711 static int
14712 tcp_addbbr(module_t mod, int32_t type, void *data)
14713 {
14714 	int32_t err = 0;
14715 	int num_stacks;
14716 
14717 	switch (type) {
14718 	case MOD_LOAD:
14719 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14720 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14721 		    sizeof(struct bbr_sendmap),
14722 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14723 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14724 		    sizeof(struct tcp_bbr),
14725 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14726 		sysctl_ctx_init(&bbr_sysctl_ctx);
14727 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14728 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14729 		    OID_AUTO,
14730 #ifdef STACKALIAS
14731 		    __XSTRING(STACKALIAS),
14732 #else
14733 		    __XSTRING(STACKNAME),
14734 #endif
14735 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14736 		    "");
14737 		if (bbr_sysctl_root == NULL) {
14738 			printf("Failed to add sysctl node\n");
14739 			err = EFAULT;
14740 			goto free_uma;
14741 		}
14742 		bbr_init_sysctls();
14743 		num_stacks = nitems(bbr_stack_names);
14744 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14745 		    bbr_stack_names, &num_stacks);
14746 		if (err) {
14747 			printf("Failed to register %s stack name for "
14748 			    "%s module\n", bbr_stack_names[num_stacks],
14749 			    __XSTRING(MODNAME));
14750 			sysctl_ctx_free(&bbr_sysctl_ctx);
14751 	free_uma:
14752 			uma_zdestroy(bbr_zone);
14753 			uma_zdestroy(bbr_pcb_zone);
14754 			bbr_counter_destroy();
14755 			printf("Failed to register " __XSTRING(MODNAME)
14756 			    " module err:%d\n", err);
14757 			return (err);
14758 		}
14759 		tcp_lro_reg_mbufq();
14760 		bbr_mod_inited = true;
14761 		printf(__XSTRING(MODNAME) " is now available\n");
14762 		break;
14763 	case MOD_QUIESCE:
14764 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14765 		break;
14766 	case MOD_UNLOAD:
14767 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14768 		if (err == EBUSY)
14769 			break;
14770 		if (bbr_mod_inited) {
14771 			uma_zdestroy(bbr_zone);
14772 			uma_zdestroy(bbr_pcb_zone);
14773 			sysctl_ctx_free(&bbr_sysctl_ctx);
14774 			bbr_counter_destroy();
14775 			printf(__XSTRING(MODNAME)
14776 			    " is now no longer available\n");
14777 			bbr_mod_inited = false;
14778 		}
14779 		tcp_lro_dereg_mbufq();
14780 		err = 0;
14781 		break;
14782 	default:
14783 		return (EOPNOTSUPP);
14784 	}
14785 	return (err);
14786 }
14787 
14788 static moduledata_t tcp_bbr = {
14789 	.name = __XSTRING(MODNAME),
14790 	    .evhand = tcp_addbbr,
14791 	    .priv = 0
14792 };
14793 
14794 MODULE_VERSION(MODNAME, 1);
14795 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14796 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14797