xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision 7ef62cebc2f965b0f640263e179276928885e33d)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_ratelimit.h"
40 #include <sys/param.h>
41 #include <sys/arb.h>
42 #include <sys/module.h>
43 #include <sys/kernel.h>
44 #include <sys/libkern.h>
45 #ifdef TCP_HHOOK
46 #include <sys/hhook.h>
47 #endif
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/proc.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/systm.h>
55 #ifdef STATS
56 #include <sys/qmath.h>
57 #include <sys/tree.h>
58 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
59 #endif
60 #include <sys/refcount.h>
61 #include <sys/queue.h>
62 #include <sys/eventhandler.h>
63 #include <sys/smp.h>
64 #include <sys/kthread.h>
65 #include <sys/lock.h>
66 #include <sys/mutex.h>
67 #include <sys/tim_filter.h>
68 #include <sys/time.h>
69 #include <sys/protosw.h>
70 #include <vm/uma.h>
71 #include <sys/kern_prefetch.h>
72 
73 #include <net/route.h>
74 #include <net/route/nhop.h>
75 #include <net/vnet.h>
76 
77 #define TCPSTATES		/* for logging */
78 
79 #include <netinet/in.h>
80 #include <netinet/in_kdtrace.h>
81 #include <netinet/in_pcb.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
84 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
85 #include <netinet/ip_var.h>
86 #include <netinet/ip6.h>
87 #include <netinet6/in6_pcb.h>
88 #include <netinet6/ip6_var.h>
89 #define	TCPOUTFLAGS
90 #include <netinet/tcp.h>
91 #include <netinet/tcp_fsm.h>
92 #include <netinet/tcp_seq.h>
93 #include <netinet/tcp_timer.h>
94 #include <netinet/tcp_var.h>
95 #include <netinet/tcpip.h>
96 #include <netinet/tcp_hpts.h>
97 #include <netinet/cc/cc.h>
98 #include <netinet/tcp_log_buf.h>
99 #include <netinet/tcp_ratelimit.h>
100 #include <netinet/tcp_lro.h>
101 #ifdef TCP_OFFLOAD
102 #include <netinet/tcp_offload.h>
103 #endif
104 #ifdef INET6
105 #include <netinet6/tcp6_var.h>
106 #endif
107 #include <netinet/tcp_fastopen.h>
108 
109 #include <netipsec/ipsec_support.h>
110 #include <net/if.h>
111 #include <net/if_var.h>
112 #include <net/ethernet.h>
113 
114 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
115 #include <netipsec/ipsec.h>
116 #include <netipsec/ipsec6.h>
117 #endif				/* IPSEC */
118 
119 #include <netinet/udp.h>
120 #include <netinet/udp_var.h>
121 #include <machine/in_cksum.h>
122 
123 #ifdef MAC
124 #include <security/mac/mac_framework.h>
125 #endif
126 
127 #include "sack_filter.h"
128 #include "tcp_bbr.h"
129 #include "rack_bbr_common.h"
130 uma_zone_t bbr_zone;
131 uma_zone_t bbr_pcb_zone;
132 
133 struct sysctl_ctx_list bbr_sysctl_ctx;
134 struct sysctl_oid *bbr_sysctl_root;
135 
136 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
137 	(tv) = (value); \
138 	if ((u_long)(tv) < (u_long)(tvmin)) \
139 		(tv) = (tvmin); \
140 	if ((u_long)(tv) > (u_long)(tvmax)) \
141 		(tv) = (tvmax); \
142 } while(0)
143 
144 /*#define BBR_INVARIANT 1*/
145 
146 /*
147  * initial window
148  */
149 static uint32_t bbr_def_init_win = 10;
150 static int32_t bbr_persist_min = 250000;	/* 250ms */
151 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
152 static int32_t bbr_cwnd_may_shrink = 0;
153 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
154 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
155 static int32_t bbr_hardware_pacing_limit = 8000;
156 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
157 static int32_t bbr_no_retran = 0;
158 
159 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
160 static int32_t bbr_max_net_error_cnt = 10;
161 /* Should the following be dynamic too -- loss wise */
162 static int32_t bbr_rtt_gain_thresh = 0;
163 /* Measurement controls */
164 static int32_t bbr_use_google_algo = 1;
165 static int32_t bbr_ts_limiting = 1;
166 static int32_t bbr_ts_can_raise = 0;
167 static int32_t bbr_do_red = 600;
168 static int32_t bbr_red_scale = 20000;
169 static int32_t bbr_red_mul = 1;
170 static int32_t bbr_red_div = 2;
171 static int32_t bbr_red_growth_restrict = 1;
172 static int32_t  bbr_target_is_bbunit = 0;
173 static int32_t bbr_drop_limit = 0;
174 /*
175  * How much gain do we need to see to
176  * stay in startup?
177  */
178 static int32_t bbr_marks_rxt_sack_passed = 0;
179 static int32_t bbr_start_exit = 25;
180 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
181 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
182 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
183 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
184 					 * if we go back ever to where the pacer
185 					 * has priority over timers.
186 					 */
187 static int32_t bbr_policer_call_from_rack_to = 0;
188 static int32_t bbr_policer_detection_enabled = 1;
189 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
190 						 * measurements before we are
191 						 * "good" note that 2 == 1.
192 						 * This is because we use a >
193 						 * comparison. This means if
194 						 * min_measure was 0, it takes
195 						 * num-measures > min(0) and
196 						 * you get 1 measurement and
197 						 * you are good. Set to 1, you
198 						 * have to have two
199 						 * measurements (this is done
200 						 * to prevent it from being ok
201 						 * to have no measurements). */
202 static int32_t bbr_no_pacing_until = 4;
203 
204 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
205 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
206 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
207 
208 static int32_t bbr_target_cwnd_mult_limit = 8;
209 /*
210  * bbr_cwnd_min_val is the number of
211  * segments we hold to in the RTT probe
212  * state typically 4.
213  */
214 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
215 
216 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
217 
218 static int32_t bbr_gain_to_target = 1;
219 static int32_t bbr_gain_gets_extra_too = 1;
220 /*
221  * bbr_high_gain is the 2/ln(2) value we need
222  * to double the sending rate in startup. This
223  * is used for both cwnd and hptsi gain's.
224  */
225 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
226 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
227 static int32_t bbr_use_lower_gain_in_startup = 1;
228 
229 /* thresholds for reduction on drain in sub-states/drain */
230 static int32_t bbr_drain_rtt = BBR_SRTT;
231 static int32_t bbr_drain_floor = 88;
232 static int32_t google_allow_early_out = 1;
233 static int32_t google_consider_lost = 1;
234 static int32_t bbr_drain_drop_mul = 4;
235 static int32_t bbr_drain_drop_div = 5;
236 static int32_t bbr_rand_ot = 50;
237 static int32_t bbr_can_force_probertt = 0;
238 static int32_t bbr_can_adjust_probertt = 1;
239 static int32_t bbr_probertt_sets_rtt = 0;
240 static int32_t bbr_can_use_ts_for_rtt = 1;
241 static int32_t bbr_is_ratio = 0;
242 static int32_t bbr_sub_drain_app_limit = 1;
243 static int32_t bbr_prtt_slam_cwnd = 1;
244 static int32_t bbr_sub_drain_slam_cwnd = 1;
245 static int32_t bbr_slam_cwnd_in_main_drain = 1;
246 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
247 					 * hold */
248 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
249 /*
250  * bbr_drain_gain is the reverse of the high_gain
251  * designed to drain back out the standing queue
252  * that is formed in startup by causing a larger
253  * hptsi gain and thus drainging the packets
254  * in flight.
255  */
256 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
257 static int32_t bbr_rttprobe_gain = 192;
258 
259 /*
260  * The cwnd_gain is the default cwnd gain applied when
261  * calculating a target cwnd. Note that the cwnd is
262  * a secondary factor in the way BBR works (see the
263  * paper and think about it, it will take some time).
264  * Basically the hptsi_gain spreads the packets out
265  * so you never get more than BDP to the peer even
266  * if the cwnd is high. In our implemenation that
267  * means in non-recovery/retransmission scenarios
268  * cwnd will never be reached by the flight-size.
269  */
270 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
271 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
272 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
273 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
274 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
275 static int32_t bbr_ignore_data_after_close = 1;
276 static int16_t bbr_hptsi_gain[] = {
277 	(BBR_UNIT *5 / 4),
278 	(BBR_UNIT * 3 / 4),
279 	BBR_UNIT,
280 	BBR_UNIT,
281 	BBR_UNIT,
282 	BBR_UNIT,
283 	BBR_UNIT,
284 	BBR_UNIT
285 };
286 int32_t bbr_use_rack_resend_cheat = 1;
287 int32_t bbr_sends_full_iwnd = 1;
288 
289 #define BBR_HPTSI_GAIN_MAX 8
290 /*
291  * The BBR module incorporates a number of
292  * TCP ideas that have been put out into the IETF
293  * over the last few years:
294  * - Yuchung Cheng's RACK TCP (for which its named) that
295  *    will stop us using the number of dup acks and instead
296  *    use time as the gage of when we retransmit.
297  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
298  *    of Dukkipati et.al.
299  * - Van Jacobson's et.al BBR.
300  *
301  * RACK depends on SACK, so if an endpoint arrives that
302  * cannot do SACK the state machine below will shuttle the
303  * connection back to using the "default" TCP stack that is
304  * in FreeBSD.
305  *
306  * To implement BBR and RACK the original TCP stack was first decomposed
307  * into a functional state machine with individual states
308  * for each of the possible TCP connection states. The do_segment
309  * functions role in life is to mandate the connection supports SACK
310  * initially and then assure that the RACK state matches the conenction
311  * state before calling the states do_segment function. Data processing
312  * of inbound segments also now happens in the hpts_do_segment in general
313  * with only one exception. This is so we can keep the connection on
314  * a single CPU.
315  *
316  * Each state is simplified due to the fact that the original do_segment
317  * has been decomposed and we *know* what state we are in (no
318  * switches on the state) and all tests for SACK are gone. This
319  * greatly simplifies what each state does.
320  *
321  * TCP output is also over-written with a new version since it
322  * must maintain the new rack scoreboard and has had hptsi
323  * integrated as a requirment. Still todo is to eliminate the
324  * use of the callout_() system and use the hpts for all
325  * timers as well.
326  */
327 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
328 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
329 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
330 						 * free list */
331 static int32_t bbr_tlp_thresh = 1;
332 static int32_t bbr_reorder_thresh = 2;
333 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
334 						 * 60,000,000 - 60 seconds */
335 static int32_t bbr_pkt_delay = 1000;
336 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
337 static int32_t bbr_incr_timers = 1;
338 
339 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
340 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
341 static int32_t bbr_exit_startup_at_loss = 1;
342 
343 /*
344  * bbr_lt_bw_ratio is 1/8th
345  * bbr_lt_bw_diff is  < 4 Kbit/sec
346  */
347 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
348 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
349 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
350 						 * the lt_bw for */
351 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
352 						 * lt_bw */
353 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
354 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
355 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
356 
357 static int32_t bbr_verbose_logging = 0;
358 /*
359  * Currently regular tcp has a rto_min of 30ms
360  * the backoff goes 12 times so that ends up
361  * being a total of 122.850 seconds before a
362  * connection is killed.
363  */
364 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
365 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
366 
367 /****************************************************/
368 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
369 /****************************************************/
370 /* What amount is our formula using to get TSO size */
371 static int32_t bbr_hptsi_per_second = 1000;
372 
373 /*
374  * For hptsi under bbr_cross_over connections what is delay
375  * target 7ms (in usec) combined with a seg_max of 2
376  * gets us close to identical google behavior in
377  * TSO size selection (possibly more 1MSS sends).
378  */
379 static int32_t bbr_hptsi_segments_delay_tar = 7000;
380 
381 /* Does pacing delay include overhead's in its time calculations? */
382 static int32_t bbr_include_enet_oh = 0;
383 static int32_t bbr_include_ip_oh = 1;
384 static int32_t bbr_include_tcp_oh = 1;
385 static int32_t bbr_google_discount = 10;
386 
387 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
388 static int32_t bbr_state_is_pkt_epoch = 0;
389 static int32_t bbr_state_drain_2_tar = 1;
390 /* What is the max the 0 - bbr_cross_over MBPS TSO target
391  * can reach using our delay target. Note that this
392  * value becomes the floor for the cross over
393  * algorithm.
394  */
395 static int32_t bbr_hptsi_segments_max = 2;
396 static int32_t bbr_hptsi_segments_floor = 1;
397 static int32_t bbr_hptsi_utter_max = 0;
398 
399 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
400 static int32_t bbr_hptsi_bytes_min = 1460;
401 static int32_t bbr_all_get_min = 0;
402 
403 /* Cross over point from algo-a to algo-b */
404 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
405 
406 /* Do we deal with our restart state? */
407 static int32_t bbr_uses_idle_restart = 0;
408 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
409 
410 /* Do we allow hardware pacing? */
411 static int32_t bbr_allow_hdwr_pacing = 0;
412 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
413 static int32_t bbr_hdwr_pace_floor = 1;
414 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
415 
416 /****************************************************/
417 static int32_t bbr_resends_use_tso = 0;
418 static int32_t bbr_tlp_max_resend = 2;
419 static int32_t bbr_sack_block_limit = 128;
420 
421 #define  BBR_MAX_STAT 19
422 counter_u64_t bbr_state_time[BBR_MAX_STAT];
423 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
424 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
425 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
426 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
427 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
428 counter_u64_t bbr_flows_whdwr_pacing;
429 counter_u64_t bbr_flows_nohdwr_pacing;
430 
431 counter_u64_t bbr_nohdwr_pacing_enobuf;
432 counter_u64_t bbr_hdwr_pacing_enobuf;
433 
434 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
435 
436 /*
437  * Static defintions we need for forward declarations.
438  */
439 static uint32_t
440 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
441 		      uint32_t useconds_time, uint64_t bw);
442 static uint32_t
443 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
444 static void
445 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
446 static void
447 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
448 static void
449 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
450 		    int dolog);
451 static uint32_t
452 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
453 static void
454 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
455 		 int32_t pkt_epoch, uint32_t losses);
456 static uint32_t
457 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts,
458 		     struct bbr_sendmap *rsm);
459 static uint32_t
460 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
461 static uint32_t
462 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
463 		    struct bbr_sendmap *rsm, uint32_t srtt, uint32_t cts);
464 static void
465 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
466 		 int32_t line);
467 static void
468 bbr_set_state_target(struct tcp_bbr *bbr, int line);
469 static void
470 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
471 static void
472 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick,
473 		       int event, int line);
474 static void
475 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
476 static void
477 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
478 static void
479 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
480 		    uint32_t rtt, uint32_t line, uint8_t is_start,
481 		    uint16_t set);
482 static struct bbr_sendmap *
483 bbr_find_lowest_rsm(struct tcp_bbr *bbr);
484 static __inline uint32_t
485 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
486 static void
487 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot,
488 		 uint8_t which);
489 static void
490 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts,
491 		  uint32_t time_since_sent, uint32_t srtt,
492 		  uint32_t thresh, uint32_t to);
493 static void
494 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
495 static void
496 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
497 		    uint32_t del_by, uint32_t cts, uint32_t sloton,
498 		    uint32_t prev_delay);
499 static void
500 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
501 		  int32_t line);
502 static void
503 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr);
504 static void
505 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
506 static void
507 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
508 static void
509 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
510 static void
511 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
512 			  uint32_t cts, uint32_t usecs, uint64_t bw,
513 			  uint32_t override, int mod);
514 static int bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt);
515 
516 static inline uint8_t
517 bbr_state_val(struct tcp_bbr *bbr)
518 {
519 	return(bbr->rc_bbr_substate);
520 }
521 
522 static inline uint32_t
523 get_min_cwnd(struct tcp_bbr *bbr)
524 {
525 	int mss;
526 
527 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
528 		  bbr->r_ctl.rc_pace_max_segs);
529 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
530 		return (bbr_cwnd_min_val_hs * mss);
531 	else
532 		return (bbr_cwnd_min_val * mss);
533 }
534 
535 static uint32_t
536 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
537 {
538 	uint64_t srtt, var;
539 	uint64_t ret_val;
540 
541 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
542 	if (tp->t_srtt == 0) {
543 		srtt = (uint64_t)BBR_INITIAL_RTO;
544 		var = 0;
545 	} else {
546 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
547 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
548 	}
549 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
550 	    bbr_persist_min, bbr_persist_max);
551 	return ((uint32_t)ret_val);
552 }
553 
554 static uint32_t
555 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
556 {
557 	/*
558 	 * Start the FR timer, we do this based on getting the first one in
559 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
560 	 * events we need to stop the running timer (if its running) before
561 	 * starting the new one.
562 	 */
563 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
564 	int32_t idx;
565 	int32_t is_tlp_timer = 0;
566 	struct bbr_sendmap *rsm;
567 
568 	if (bbr->rc_all_timers_stopped) {
569 		/* All timers have been stopped none are to run */
570 		return (0);
571 	}
572 	if (bbr->rc_in_persist) {
573 		/* We can't start any timer in persists */
574 		return (bbr_get_persists_timer_val(tp, bbr));
575 	}
576 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
577 	if ((rsm == NULL) ||
578 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
579 	    (tp->t_state < TCPS_ESTABLISHED)) {
580 		/* Nothing on the send map */
581 activate_rxt:
582 		if (SEQ_LT(tp->snd_una, tp->snd_max) ||
583 		    sbavail(&tptosocket(tp)->so_snd)) {
584 			uint64_t tov;
585 
586 			time_since_sent = 0;
587 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
588 			if (rsm) {
589 				idx = rsm->r_rtr_cnt - 1;
590 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
591 					tstmp_touse = rsm->r_tim_lastsent[idx];
592 				else
593 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
594 				if (TSTMP_GT(tstmp_touse, cts))
595 				    time_since_sent = cts - tstmp_touse;
596 			}
597 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
598 			if (tp->t_srtt == 0)
599 				tov = BBR_INITIAL_RTO;
600 			else
601 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
602 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
603 			if (tp->t_rxtshift)
604 				tov *= tcp_backoff[tp->t_rxtshift];
605 			if (tov > time_since_sent)
606 				tov -= time_since_sent;
607 			else
608 				tov = bbr->r_ctl.rc_min_to;
609 			TCPT_RANGESET_NOSLOP(to, tov,
610 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
611 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
612 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
613 			return (to);
614 		}
615 		return (0);
616 	}
617 	if (rsm->r_flags & BBR_ACKED) {
618 		rsm = bbr_find_lowest_rsm(bbr);
619 		if (rsm == NULL) {
620 			/* No lowest? */
621 			goto activate_rxt;
622 		}
623 	}
624 	/* Convert from ms to usecs */
625 	if (rsm->r_flags & BBR_SACK_PASSED) {
626 		if ((tp->t_flags & TF_SENTFIN) &&
627 		    ((tp->snd_max - tp->snd_una) == 1) &&
628 		    (rsm->r_flags & BBR_HAS_FIN)) {
629 			/*
630 			 * We don't start a bbr rack timer if all we have is
631 			 * a FIN outstanding.
632 			 */
633 			goto activate_rxt;
634 		}
635 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
636 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
637 		idx = rsm->r_rtr_cnt - 1;
638 		exp = rsm->r_tim_lastsent[idx] + thresh;
639 		if (SEQ_GEQ(exp, cts)) {
640 			to = exp - cts;
641 			if (to < bbr->r_ctl.rc_min_to) {
642 				to = bbr->r_ctl.rc_min_to;
643 			}
644 		} else {
645 			to = bbr->r_ctl.rc_min_to;
646 		}
647 	} else {
648 		/* Ok we need to do a TLP not RACK */
649 		if (bbr->rc_tlp_in_progress != 0) {
650 			/*
651 			 * The previous send was a TLP.
652 			 */
653 			goto activate_rxt;
654 		}
655 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
656 		if (rsm == NULL) {
657 			/* We found no rsm to TLP with. */
658 			goto activate_rxt;
659 		}
660 		if (rsm->r_flags & BBR_HAS_FIN) {
661 			/* If its a FIN we don't do TLP */
662 			rsm = NULL;
663 			goto activate_rxt;
664 		}
665 		time_since_sent = 0;
666 		idx = rsm->r_rtr_cnt - 1;
667 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
668 			tstmp_touse = rsm->r_tim_lastsent[idx];
669 		else
670 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
671 		if (TSTMP_GT(tstmp_touse, cts))
672 		    time_since_sent = cts - tstmp_touse;
673 		is_tlp_timer = 1;
674 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
675 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
676 		if (thresh > time_since_sent)
677 			to = thresh - time_since_sent;
678 		else
679 			to = bbr->r_ctl.rc_min_to;
680 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
681 			/*
682 			 * If the TLP time works out to larger than the max
683 			 * RTO lets not do TLP.. just RTO.
684 			 */
685 			goto activate_rxt;
686 		}
687 		if ((bbr->rc_tlp_rtx_out == 1) &&
688 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
689 			/*
690 			 * Second retransmit of the same TLP
691 			 * lets not.
692 			 */
693 			bbr->rc_tlp_rtx_out = 0;
694 			goto activate_rxt;
695 		}
696 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
697 			/*
698 			 * The tail is no longer the last one I did a probe
699 			 * on
700 			 */
701 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
702 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
703 		}
704 	}
705 	if (is_tlp_timer == 0) {
706 		BBR_STAT_INC(bbr_to_arm_rack);
707 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
708 	} else {
709 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
710 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
711 			/*
712 			 * We have exceeded how many times we can retran the
713 			 * current TLP timer, switch to the RTO timer.
714 			 */
715 			goto activate_rxt;
716 		} else {
717 			BBR_STAT_INC(bbr_to_arm_tlp);
718 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
719 		}
720 	}
721 	return (to);
722 }
723 
724 static inline int32_t
725 bbr_minseg(struct tcp_bbr *bbr)
726 {
727 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
728 }
729 
730 static void
731 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
732 {
733 	struct inpcb *inp = tptoinpcb(tp);
734 	struct hpts_diag diag;
735 	uint32_t delayed_ack = 0;
736 	uint32_t left = 0;
737 	uint32_t hpts_timeout;
738 	uint8_t stopped;
739 	int32_t delay_calc = 0;
740 	uint32_t prev_delay = 0;
741 
742 	if (tcp_in_hpts(tp)) {
743 		/* A previous call is already set up */
744 		return;
745 	}
746 	if ((tp->t_state == TCPS_CLOSED) ||
747 	    (tp->t_state == TCPS_LISTEN)) {
748 		return;
749 	}
750 	stopped = bbr->rc_tmr_stopped;
751 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
752 		left = bbr->r_ctl.rc_timer_exp - cts;
753 	}
754 	bbr->r_ctl.rc_hpts_flags = 0;
755 	bbr->r_ctl.rc_timer_exp = 0;
756 	prev_delay = bbr->r_ctl.rc_last_delay_val;
757 	if (bbr->r_ctl.rc_last_delay_val &&
758 	    (slot == 0)) {
759 		/*
760 		 * If a previous pacer delay was in place we
761 		 * are not coming from the output side (where
762 		 * we calculate a delay, more likely a timer).
763 		 */
764 		slot = bbr->r_ctl.rc_last_delay_val;
765 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
766 			/* Compensate for time passed  */
767 			delay_calc = cts - bbr->rc_pacer_started;
768 			if (delay_calc <= slot)
769 				slot -= delay_calc;
770 		}
771 	}
772 	/* Do we have early to make up for by pushing out the pacing time? */
773 	if (bbr->r_agg_early_set) {
774 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
775 		slot += bbr->r_ctl.rc_agg_early;
776 		bbr->r_ctl.rc_agg_early = 0;
777 		bbr->r_agg_early_set = 0;
778 	}
779 	/* Are we running a total debt that needs to be compensated for? */
780 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
781 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
782 			/* We nuke the delay */
783 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
784 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
785 		} else {
786 			/* We nuke some of the delay, put in a minimal 100usecs  */
787 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
788 			bbr->r_ctl.rc_last_delay_val = slot = 100;
789 		}
790 	}
791 	bbr->r_ctl.rc_last_delay_val = slot;
792 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
793 	if (tp->t_flags & TF_DELACK) {
794 		if (bbr->rc_in_persist == 0) {
795 			delayed_ack = bbr_delack_time;
796 		} else {
797 			/*
798 			 * We are in persists and have
799 			 * gotten a new data element.
800 			 */
801 			if (hpts_timeout > bbr_delack_time) {
802 				/*
803 				 * Lets make the persists timer (which acks)
804 				 * be the smaller of hpts_timeout and bbr_delack_time.
805 				 */
806 				hpts_timeout = bbr_delack_time;
807 			}
808 		}
809 	}
810 	if (delayed_ack &&
811 	    ((hpts_timeout == 0) ||
812 	     (delayed_ack < hpts_timeout))) {
813 		/* We need a Delayed ack timer */
814 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
815 		hpts_timeout = delayed_ack;
816 	}
817 	if (slot) {
818 		/* Mark that we have a pacing timer up */
819 		BBR_STAT_INC(bbr_paced_segments);
820 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
821 	}
822 	/*
823 	 * If no timers are going to run and we will fall off thfe hptsi
824 	 * wheel, we resort to a keep-alive timer if its configured.
825 	 */
826 	if ((hpts_timeout == 0) &&
827 	    (slot == 0)) {
828 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
829 		    (tp->t_state <= TCPS_CLOSING)) {
830 			/*
831 			 * Ok we have no timer (persists, rack, tlp, rxt  or
832 			 * del-ack), we don't have segments being paced. So
833 			 * all that is left is the keepalive timer.
834 			 */
835 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
836 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
837 			} else {
838 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
839 			}
840 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
841 		}
842 	}
843 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
844 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
845 		/*
846 		 * RACK, TLP, persists and RXT timers all are restartable
847 		 * based on actions input .. i.e we received a packet (ack
848 		 * or sack) and that changes things (rw, or snd_una etc).
849 		 * Thus we can restart them with a new value. For
850 		 * keep-alive, delayed_ack we keep track of what was left
851 		 * and restart the timer with a smaller value.
852 		 */
853 		if (left < hpts_timeout)
854 			hpts_timeout = left;
855 	}
856 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
857 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
858 		/*
859 		 * If configured to do so, and the timer is either
860 		 * the TLP or RXT timer, we need to increase the timeout
861 		 * by the pacing time. Consider the bottleneck at my
862 		 * machine as an example, we are sending something
863 		 * to start a TLP on. The last packet won't be emitted
864 		 * fully until the pacing time (the bottleneck will hold
865 		 * the data in place). Once the packet is emitted that
866 		 * is when we want to start waiting for the TLP. This
867 		 * is most evident with hardware pacing (where the nic
868 		 * is holding the packet(s) before emitting). But it
869 		 * can also show up in the network so we do it for all
870 		 * cases. Technically we would take off one packet from
871 		 * this extra delay but this is easier and being more
872 		 * conservative is probably better.
873 		 */
874 		hpts_timeout += slot;
875 	}
876 	if (hpts_timeout) {
877 		/*
878 		 * Hack alert for now we can't time-out over 2147 seconds (a
879 		 * bit more than 35min)
880 		 */
881 		if (hpts_timeout > 0x7ffffffe)
882 			hpts_timeout = 0x7ffffffe;
883 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
884 	} else
885 		bbr->r_ctl.rc_timer_exp = 0;
886 	if ((slot) &&
887 	    (bbr->rc_use_google ||
888 	     bbr->output_error_seen ||
889 	     (slot <= hpts_timeout))  ) {
890 		/*
891 		 * Tell LRO that it can queue packets while
892 		 * we pace.
893 		 */
894 		bbr->rc_tp->t_flags2 |= TF2_MBUF_QUEUE_READY;
895 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
896 		    (bbr->rc_cwnd_limited == 0)) {
897 			/*
898 			 * If we are not cwnd limited and we
899 			 * are running a rack timer we put on
900 			 * the do not disturbe even for sack.
901 			 */
902 			tp->t_flags2 |= TF2_DONT_SACK_QUEUE;
903 		} else
904 			tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
905 		bbr->rc_pacer_started = cts;
906 
907 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(slot),
908 					   __LINE__, &diag);
909 		bbr->rc_timer_first = 0;
910 		bbr->bbr_timer_src = frm;
911 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
912 		bbr_log_hpts_diag(bbr, cts, &diag);
913 	} else if (hpts_timeout) {
914 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(hpts_timeout),
915 					   __LINE__, &diag);
916 		/*
917 		 * We add the flag here as well if the slot is set,
918 		 * since hpts will call in to clear the queue first before
919 		 * calling the output routine (which does our timers).
920 		 * We don't want to set the flag if its just a timer
921 		 * else the arrival of data might (that causes us
922 		 * to send more) might get delayed. Imagine being
923 		 * on a keep-alive timer and a request comes in for
924 		 * more data.
925 		 */
926 		if (slot)
927 			bbr->rc_pacer_started = cts;
928 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
929 		    (bbr->rc_cwnd_limited == 0)) {
930 			/*
931 			 * For a rack timer, don't wake us even
932 			 * if a sack arrives as long as we are
933 			 * not cwnd limited.
934 			 */
935 			tp->t_flags2 |= (TF2_MBUF_QUEUE_READY |
936 			    TF2_DONT_SACK_QUEUE);
937 		} else {
938 			/* All other timers wake us up */
939 			tp->t_flags2 &= ~(TF2_MBUF_QUEUE_READY |
940 			    TF2_DONT_SACK_QUEUE);
941 		}
942 		bbr->bbr_timer_src = frm;
943 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
944 		bbr_log_hpts_diag(bbr, cts, &diag);
945 		bbr->rc_timer_first = 1;
946 	}
947 	bbr->rc_tmr_stopped = 0;
948 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
949 }
950 
951 static void
952 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
953 {
954 	/*
955 	 * We received an ack, and then did not call send or were bounced
956 	 * out due to the hpts was running. Now a timer is up as well, is it
957 	 * the right timer?
958 	 */
959 	struct inpcb *inp;
960 	struct bbr_sendmap *rsm;
961 	uint32_t hpts_timeout;
962 	int tmr_up;
963 
964 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
965 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
966 		return;
967 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
968 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
969 	    (tmr_up == PACE_TMR_RXT)) {
970 		/* Should be an RXT */
971 		return;
972 	}
973 	inp = bbr->rc_inp;
974 	if (rsm == NULL) {
975 		/* Nothing outstanding? */
976 		if (tp->t_flags & TF_DELACK) {
977 			if (tmr_up == PACE_TMR_DELACK)
978 				/*
979 				 * We are supposed to have delayed ack up
980 				 * and we do
981 				 */
982 				return;
983 		} else if (sbavail(&inp->inp_socket->so_snd) &&
984 		    (tmr_up == PACE_TMR_RXT)) {
985 			/*
986 			 * if we hit enobufs then we would expect the
987 			 * possibility of nothing outstanding and the RXT up
988 			 * (and the hptsi timer).
989 			 */
990 			return;
991 		} else if (((V_tcp_always_keepalive ||
992 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
993 			    (tp->t_state <= TCPS_CLOSING)) &&
994 			    (tmr_up == PACE_TMR_KEEP) &&
995 		    (tp->snd_max == tp->snd_una)) {
996 			/* We should have keep alive up and we do */
997 			return;
998 		}
999 	}
1000 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1001 		if ((tp->t_flags & TF_SENTFIN) &&
1002 		    ((tp->snd_max - tp->snd_una) == 1) &&
1003 		    (rsm->r_flags & BBR_HAS_FIN)) {
1004 			/* needs to be a RXT */
1005 			if (tmr_up == PACE_TMR_RXT)
1006 				return;
1007 			else
1008 				goto wrong_timer;
1009 		} else if (tmr_up == PACE_TMR_RACK)
1010 			return;
1011 		else
1012 			goto wrong_timer;
1013 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1014 		/* Rack timer has priority if we have data out */
1015 		return;
1016 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1017 		    ((tmr_up == PACE_TMR_TLP) ||
1018 	    (tmr_up == PACE_TMR_RXT))) {
1019 		/*
1020 		 * Either a TLP or RXT is fine if no sack-passed is in place
1021 		 * and data is outstanding.
1022 		 */
1023 		return;
1024 	} else if (tmr_up == PACE_TMR_DELACK) {
1025 		/*
1026 		 * If the delayed ack was going to go off before the
1027 		 * rtx/tlp/rack timer were going to expire, then that would
1028 		 * be the timer in control. Note we don't check the time
1029 		 * here trusting the code is correct.
1030 		 */
1031 		return;
1032 	}
1033 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1034 	    ((tmr_up == PACE_TMR_RXT) ||
1035 	     (tmr_up == PACE_TMR_TLP) ||
1036 	     (tmr_up == PACE_TMR_RACK))) {
1037 		/*
1038 		 * We have outstanding data and
1039 		 * we *do* have a RACK, TLP or RXT
1040 		 * timer running. We won't restart
1041 		 * anything here since thats probably ok we
1042 		 * will get called with some timer here shortly.
1043 		 */
1044 		return;
1045 	}
1046 	/*
1047 	 * Ok the timer originally started is not what we want now. We will
1048 	 * force the hpts to be stopped if any, and restart with the slot
1049 	 * set to what was in the saved slot.
1050 	 */
1051 wrong_timer:
1052 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1053 		if (tcp_in_hpts(tp))
1054 			tcp_hpts_remove(tp);
1055 		bbr_timer_cancel(bbr, __LINE__, cts);
1056 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1057 		    0);
1058 	} else {
1059 		/*
1060 		 * Output is hptsi so we just need to switch the type of
1061 		 * timer. We don't bother with keep-alive, since when we
1062 		 * jump through the output, it will start the keep-alive if
1063 		 * nothing is sent.
1064 		 *
1065 		 * We only need a delayed-ack added and or the hpts_timeout.
1066 		 */
1067 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1068 		if (tp->t_flags & TF_DELACK) {
1069 			if (hpts_timeout == 0) {
1070 				hpts_timeout = bbr_delack_time;
1071 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1072 			}
1073 			else if (hpts_timeout > bbr_delack_time) {
1074 				hpts_timeout = bbr_delack_time;
1075 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1076 			}
1077 		}
1078 		if (hpts_timeout) {
1079 			if (hpts_timeout > 0x7ffffffe)
1080 				hpts_timeout = 0x7ffffffe;
1081 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1082 		}
1083 	}
1084 }
1085 
1086 int32_t bbr_clear_lost = 0;
1087 
1088 /*
1089  * Considers the two time values now (cts) and earlier.
1090  * If cts is smaller than earlier, we could have
1091  * had a sequence wrap (our counter wraps every
1092  * 70 min or so) or it could be just clock skew
1093  * getting us two different time values. Clock skew
1094  * will show up within 10ms or so. So in such
1095  * a case (where cts is behind earlier time by
1096  * less than 10ms) we return 0. Otherwise we
1097  * return the true difference between them.
1098  */
1099 static inline uint32_t
1100 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1101 	/*
1102 	 * Given two timestamps, the current time stamp cts, and some other
1103 	 * time-stamp taken in theory earlier return the difference. The
1104 	 * trick is here sometimes locking will get the other timestamp
1105 	 * after the cts. If this occurs we need to return 0.
1106 	 */
1107 	if (TSTMP_GEQ(cts, earlier_time))
1108 		return (cts - earlier_time);
1109 	/*
1110 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1111 	 * If its more than 10ms difference then we had a time wrap. Else
1112 	 * its just the normal locking foo. I wonder if we should not go to
1113 	 * 64bit TS and get rid of this issue.
1114 	 */
1115 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1116 		return (0);
1117 	/*
1118 	 * Ok the time must have wrapped. So we need to answer a large
1119 	 * amount of time, which the normal subtraction should do.
1120 	 */
1121 	return (cts - earlier_time);
1122 }
1123 
1124 static int
1125 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1126 {
1127 	uint32_t stat;
1128 	int32_t error;
1129 
1130 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1131 	if (error || req->newptr == NULL)
1132 		return error;
1133 
1134 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1135 	if (error)
1136 		return (error);
1137 	if (stat == 1) {
1138 #ifdef BBR_INVARIANTS
1139 		printf("Clearing BBR lost counters\n");
1140 #endif
1141 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1142 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1143 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1144 	} else if (stat == 2) {
1145 #ifdef BBR_INVARIANTS
1146 		printf("Clearing BBR option counters\n");
1147 #endif
1148 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1149 	} else if (stat == 3) {
1150 #ifdef BBR_INVARIANTS
1151 		printf("Clearing BBR stats counters\n");
1152 #endif
1153 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1154 	} else if (stat == 4) {
1155 #ifdef BBR_INVARIANTS
1156 		printf("Clearing BBR out-size counters\n");
1157 #endif
1158 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1159 	}
1160 	bbr_clear_lost = 0;
1161 	return (0);
1162 }
1163 
1164 static void
1165 bbr_init_sysctls(void)
1166 {
1167 	struct sysctl_oid *bbr_probertt;
1168 	struct sysctl_oid *bbr_hptsi;
1169 	struct sysctl_oid *bbr_measure;
1170 	struct sysctl_oid *bbr_cwnd;
1171 	struct sysctl_oid *bbr_timeout;
1172 	struct sysctl_oid *bbr_states;
1173 	struct sysctl_oid *bbr_startup;
1174 	struct sysctl_oid *bbr_policer;
1175 
1176 	/* Probe rtt controls */
1177 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1178 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1179 	    OID_AUTO,
1180 	    "probertt",
1181 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1182 	    "");
1183 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1184 	    SYSCTL_CHILDREN(bbr_probertt),
1185 	    OID_AUTO, "gain", CTLFLAG_RW,
1186 	    &bbr_rttprobe_gain, 192,
1187 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1188 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1189 	    SYSCTL_CHILDREN(bbr_probertt),
1190 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1191 	    &bbr_rtt_probe_cwndtarg, 4,
1192 	    "How many mss's are outstanding during probe-rtt");
1193 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1194 	    SYSCTL_CHILDREN(bbr_probertt),
1195 	    OID_AUTO, "int", CTLFLAG_RW,
1196 	    &bbr_rtt_probe_limit, 4000000,
1197 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1198 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1199 	    SYSCTL_CHILDREN(bbr_probertt),
1200 	    OID_AUTO, "mintime", CTLFLAG_RW,
1201 	    &bbr_rtt_probe_time, 200000,
1202 	    "How many microseconds in probe-rtt");
1203 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1204 	    SYSCTL_CHILDREN(bbr_probertt),
1205 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1206 	    &bbr_filter_len_sec, 6,
1207 	    "How long in seconds does the rttProp filter run?");
1208 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1209 	    SYSCTL_CHILDREN(bbr_probertt),
1210 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1211 	    &bbr_drain_rtt, BBR_SRTT,
1212 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1213 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1214 	    SYSCTL_CHILDREN(bbr_probertt),
1215 	    OID_AUTO, "can_force", CTLFLAG_RW,
1216 	    &bbr_can_force_probertt, 0,
1217 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1218 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1219 	    SYSCTL_CHILDREN(bbr_probertt),
1220 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1221 	    &bbr_probertt_sets_rtt, 0,
1222 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1223 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1224 	    SYSCTL_CHILDREN(bbr_probertt),
1225 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1226 	    &bbr_can_adjust_probertt, 1,
1227 	    "Can we dynamically adjust the probe-rtt limits and times?");
1228 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1229 	    SYSCTL_CHILDREN(bbr_probertt),
1230 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1231 	    &bbr_is_ratio, 0,
1232 	    "is the limit to filter a ratio?");
1233 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1234 	    SYSCTL_CHILDREN(bbr_probertt),
1235 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1236 	    &bbr_prtt_slam_cwnd, 0,
1237 	    "Should we set/recover cwnd?");
1238 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1239 	    SYSCTL_CHILDREN(bbr_probertt),
1240 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1241 	    &bbr_can_use_ts_for_rtt, 1,
1242 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1243 
1244 	/* Pacing controls */
1245 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1246 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1247 	    OID_AUTO,
1248 	    "pacing",
1249 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1250 	    "");
1251 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1252 	    SYSCTL_CHILDREN(bbr_hptsi),
1253 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1254 	    &bbr_allow_hdwr_pacing, 1,
1255 	    "Do we allow hardware pacing?");
1256 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1257 	    SYSCTL_CHILDREN(bbr_hptsi),
1258 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1259 	    &bbr_hardware_pacing_limit, 4000,
1260 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1261 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1262 	    SYSCTL_CHILDREN(bbr_hptsi),
1263 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1264 	    &bbr_hdwr_pace_adjust, 2,
1265 	    "Multiplier to calculated tso size?");
1266 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1267 	    SYSCTL_CHILDREN(bbr_hptsi),
1268 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1269 	    &bbr_hdwr_pace_floor, 1,
1270 	    "Do we invoke the hardware pacing floor?");
1271 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1272 	    SYSCTL_CHILDREN(bbr_hptsi),
1273 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1274 	    &bbr_hdwr_pacing_delay_cnt, 10,
1275 	    "How many packets must be sent after hdwr pacing is enabled");
1276 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1277 	    SYSCTL_CHILDREN(bbr_hptsi),
1278 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1279 	    &bbr_cross_over, 3000000,
1280 	    "What is the point where we cross over to linux like TSO size set");
1281 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1282 	    SYSCTL_CHILDREN(bbr_hptsi),
1283 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1284 	    &bbr_hptsi_segments_delay_tar, 7000,
1285 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1286 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1287 	    SYSCTL_CHILDREN(bbr_hptsi),
1288 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1289 	    &bbr_include_enet_oh, 0,
1290 	    "Do we include the ethernet overhead in calculating pacing delay?");
1291 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1292 	    SYSCTL_CHILDREN(bbr_hptsi),
1293 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1294 	    &bbr_include_ip_oh, 1,
1295 	    "Do we include the IP overhead in calculating pacing delay?");
1296 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1297 	    SYSCTL_CHILDREN(bbr_hptsi),
1298 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1299 	    &bbr_include_tcp_oh, 0,
1300 	    "Do we include the TCP overhead in calculating pacing delay?");
1301 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1302 	    SYSCTL_CHILDREN(bbr_hptsi),
1303 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1304 	    &bbr_google_discount, 10,
1305 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1306 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1307 	    SYSCTL_CHILDREN(bbr_hptsi),
1308 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1309 	    &bbr_all_get_min, 0,
1310 	    "If you are less than a MSS do you just get the min?");
1311 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1312 	    SYSCTL_CHILDREN(bbr_hptsi),
1313 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1314 	    &bbr_hptsi_bytes_min, 1460,
1315 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1316 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1317 	    SYSCTL_CHILDREN(bbr_hptsi),
1318 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1319 	    &bbr_hptsi_segments_max, 6,
1320 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1321 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1322 	    SYSCTL_CHILDREN(bbr_hptsi),
1323 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1324 	    &bbr_hptsi_segments_floor, 1,
1325 	    "Minimum TSO size we will fall too in segments");
1326 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1327 	    SYSCTL_CHILDREN(bbr_hptsi),
1328 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1329 	    &bbr_hptsi_utter_max, 0,
1330 	    "The absolute maximum that any pacing (outside of hardware) can be");
1331 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1332 	    SYSCTL_CHILDREN(bbr_hptsi),
1333 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1334 	    &bbr_hptsi_per_second, 100,
1335 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1336 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1337 	    SYSCTL_CHILDREN(bbr_hptsi),
1338 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1339 	    &bbr_hptsi_max_mul, 1,
1340 	    "The multiplier for pace len max");
1341 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1342 	    SYSCTL_CHILDREN(bbr_hptsi),
1343 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1344 	    &bbr_hptsi_max_div, 2,
1345 	    "The divisor for pace len max");
1346 	/* Measurement controls */
1347 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1348 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1349 	    OID_AUTO,
1350 	    "measure",
1351 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1352 	    "Measurement controls");
1353 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1354 	    SYSCTL_CHILDREN(bbr_measure),
1355 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1356 	    &bbr_initial_bw_bps, 62500,
1357 	    "Minimum initial b/w in bytes per second");
1358 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1359 	    SYSCTL_CHILDREN(bbr_measure),
1360 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1361 	    &bbr_sack_not_required, 0,
1362 	    "Do we allow bbr to run on connections not supporting SACK?");
1363 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1364 	    SYSCTL_CHILDREN(bbr_measure),
1365 	    OID_AUTO, "use_google", CTLFLAG_RW,
1366 	    &bbr_use_google_algo, 0,
1367 	    "Use has close to google V1.0 has possible?");
1368 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1369 	    SYSCTL_CHILDREN(bbr_measure),
1370 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1371 	    &bbr_ts_limiting, 1,
1372 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1373 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1374 	    SYSCTL_CHILDREN(bbr_measure),
1375 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1376 	    &bbr_ts_can_raise, 0,
1377 	    "Can we raise the b/w via timestamp b/w calculation?");
1378 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1379 	    SYSCTL_CHILDREN(bbr_measure),
1380 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1381 	    &bbr_min_usec_delta, 20000,
1382 	    "How long in usec between ts of our sends in ts validation code?");
1383 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1384 	    SYSCTL_CHILDREN(bbr_measure),
1385 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1386 	    &bbr_min_peer_delta, 20,
1387 	    "What min numerical value should be between the peer deltas?");
1388 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1389 	    SYSCTL_CHILDREN(bbr_measure),
1390 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1391 	    &bbr_delta_percent, 150,
1392 	    "What percentage (150 = 15.0) do we allow variance for?");
1393 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1394 	    SYSCTL_CHILDREN(bbr_measure),
1395 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1396 	    &bbr_min_measurements_req, 1,
1397 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1398 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1399 	    SYSCTL_CHILDREN(bbr_measure),
1400 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1401 	    &bbr_no_pacing_until, 4,
1402 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1403 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1404 	    SYSCTL_CHILDREN(bbr_measure),
1405 	    OID_AUTO, "quanta", CTLFLAG_RW,
1406 	    &bbr_quanta, 2,
1407 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1408 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1409 	    SYSCTL_CHILDREN(bbr_measure),
1410 	    OID_AUTO, "noretran", CTLFLAG_RW,
1411 	    &bbr_no_retran, 0,
1412 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1413 	/* State controls */
1414 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1415 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1416 	    OID_AUTO,
1417 	    "states",
1418 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1419 	    "State controls");
1420 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1421 	    SYSCTL_CHILDREN(bbr_states),
1422 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1423 	    &bbr_uses_idle_restart, 0,
1424 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1425 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1426 	    SYSCTL_CHILDREN(bbr_states),
1427 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1428 	    &bbr_idle_restart_threshold, 100000,
1429 	    "How long must we be idle before we restart??");
1430 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1431 	    SYSCTL_CHILDREN(bbr_states),
1432 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1433 	    &bbr_state_is_pkt_epoch, 0,
1434 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1435 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1436 	    SYSCTL_CHILDREN(bbr_states),
1437 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1438 	    &bbr_rtt_gain_thresh, 0,
1439 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1440 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1441 	    SYSCTL_CHILDREN(bbr_states),
1442 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1443 	    &bbr_drain_floor, 88,
1444 	    "What is the lowest we can drain (pg) too?");
1445 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1446 	    SYSCTL_CHILDREN(bbr_states),
1447 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1448 	    &bbr_state_drain_2_tar, 1,
1449 	    "Do we drain to target in drain substate?");
1450 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1451 	    SYSCTL_CHILDREN(bbr_states),
1452 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1453 	    &bbr_gain_to_target, 1,
1454 	    "Does probe bw gain to target??");
1455 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1456 	    SYSCTL_CHILDREN(bbr_states),
1457 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1458 	    &bbr_gain_gets_extra_too, 1,
1459 	    "Does probe bw gain get the extra time too?");
1460 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1461 	    SYSCTL_CHILDREN(bbr_states),
1462 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1463 	    &bbr_drain_drop_div, 5,
1464 	    "Long drain drop divider?");
1465 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1466 	    SYSCTL_CHILDREN(bbr_states),
1467 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1468 	    &bbr_drain_drop_mul, 4,
1469 	    "Long drain drop multiplier?");
1470 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1471 	    SYSCTL_CHILDREN(bbr_states),
1472 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1473 	    &bbr_rand_ot, 50,
1474 	    "Random discount of the ot?");
1475 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1476 	    SYSCTL_CHILDREN(bbr_states),
1477 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1478 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1479 	    "How many packet-epochs does the b/w delivery rate last?");
1480 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1481 	    SYSCTL_CHILDREN(bbr_states),
1482 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1483 	    &bbr_sub_drain_app_limit, 0,
1484 	    "Does our sub-state drain invoke app limited if its long?");
1485 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1486 	    SYSCTL_CHILDREN(bbr_states),
1487 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1488 	    &bbr_sub_drain_slam_cwnd, 0,
1489 	    "Should we set/recover cwnd for sub-state drain?");
1490 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1491 	    SYSCTL_CHILDREN(bbr_states),
1492 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1493 	    &bbr_slam_cwnd_in_main_drain, 0,
1494 	    "Should we set/recover cwnd for main-state drain?");
1495 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1496 	    SYSCTL_CHILDREN(bbr_states),
1497 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1498 	    &google_allow_early_out, 1,
1499 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1500 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1501 	    SYSCTL_CHILDREN(bbr_states),
1502 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1503 	    &google_consider_lost, 1,
1504 	    "Should we have losses exit gain of probebw in google mode??");
1505 	/* Startup controls */
1506 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1507 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1508 	    OID_AUTO,
1509 	    "startup",
1510 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1511 	    "Startup controls");
1512 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1513 	    SYSCTL_CHILDREN(bbr_startup),
1514 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1515 	    &bbr_sends_full_iwnd, 1,
1516 	    "Do we not pace but burst out initial windows has our TSO size?");
1517 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1518 	    SYSCTL_CHILDREN(bbr_startup),
1519 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1520 	    &bbr_startup_loss_thresh, 2000,
1521 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1522 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1523 	    SYSCTL_CHILDREN(bbr_startup),
1524 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1525 	    &bbr_use_lower_gain_in_startup, 1,
1526 	    "Should we use a lower hptsi gain if we see loss in startup?");
1527 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1528 	    SYSCTL_CHILDREN(bbr_startup),
1529 	    OID_AUTO, "gain", CTLFLAG_RW,
1530 	    &bbr_start_exit, 25,
1531 	    "What gain percent do we need to see to stay in startup??");
1532 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1533 	    SYSCTL_CHILDREN(bbr_startup),
1534 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1535 	    &bbr_low_start_exit, 15,
1536 	    "What gain percent do we need to see to stay in the lower gain startup??");
1537 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1538 	    SYSCTL_CHILDREN(bbr_startup),
1539 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1540 	    &bbr_exit_startup_at_loss, 1,
1541 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1542 	/* CWND controls */
1543 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1544 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1545 	    OID_AUTO,
1546 	    "cwnd",
1547 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1548 	    "Cwnd controls");
1549 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1550 	    SYSCTL_CHILDREN(bbr_cwnd),
1551 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1552 	    &bbr_cwndtarget_rtt_touse, 0,
1553 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1554 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1555 	    SYSCTL_CHILDREN(bbr_cwnd),
1556 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1557 	    &bbr_cwnd_may_shrink, 0,
1558 	    "Can the cwnd shrink if it would grow to more than the target?");
1559 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1560 	    SYSCTL_CHILDREN(bbr_cwnd),
1561 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1562 	    &bbr_target_cwnd_mult_limit, 8,
1563 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1564 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1565 	    SYSCTL_CHILDREN(bbr_cwnd),
1566 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1567 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1568 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1569 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1570 	    SYSCTL_CHILDREN(bbr_cwnd),
1571 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1572 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1573 	    "What is the min cwnd (rttProp > 1ms)");
1574 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1575 	    SYSCTL_CHILDREN(bbr_cwnd),
1576 	    OID_AUTO, "initwin", CTLFLAG_RW,
1577 	    &bbr_def_init_win, 10,
1578 	    "What is the BBR initial window, if 0 use tcp version");
1579 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1580 	    SYSCTL_CHILDREN(bbr_cwnd),
1581 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1582 	    &bbr_do_red, 600,
1583 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1584 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1585 	    SYSCTL_CHILDREN(bbr_cwnd),
1586 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1587 	    &bbr_red_scale, 20000,
1588 	    "What RTT do we scale with?");
1589 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1590 	    SYSCTL_CHILDREN(bbr_cwnd),
1591 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1592 	    &bbr_red_growth_restrict, 1,
1593 	    "Do we restrict cwnd growth for whats in flight?");
1594 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1595 	    SYSCTL_CHILDREN(bbr_cwnd),
1596 	    OID_AUTO, "red_div", CTLFLAG_RW,
1597 	    &bbr_red_div, 2,
1598 	    "If we reduce whats the divisor?");
1599 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1600 	    SYSCTL_CHILDREN(bbr_cwnd),
1601 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1602 	    &bbr_red_mul, 1,
1603 	    "If we reduce whats the mulitiplier?");
1604 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1605 	    SYSCTL_CHILDREN(bbr_cwnd),
1606 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1607 	    &bbr_target_is_bbunit, 0,
1608 	    "Is the state target the pacing_gain or BBR_UNIT?");
1609 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1610 	    SYSCTL_CHILDREN(bbr_cwnd),
1611 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1612 	    &bbr_drop_limit, 0,
1613 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1614 
1615 	/* Timeout controls */
1616 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1617 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1618 	    OID_AUTO,
1619 	    "timeout",
1620 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1621 	    "Time out controls");
1622 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1623 	    SYSCTL_CHILDREN(bbr_timeout),
1624 	    OID_AUTO, "delack", CTLFLAG_RW,
1625 	    &bbr_delack_time, 100000,
1626 	    "BBR's delayed ack time");
1627 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1628 	    SYSCTL_CHILDREN(bbr_timeout),
1629 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1630 	    &bbr_tlp_type_to_use, 3,
1631 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1632 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1633 	    SYSCTL_CHILDREN(bbr_timeout),
1634 	    OID_AUTO, "persmin", CTLFLAG_RW,
1635 	    &bbr_persist_min, 250000,
1636 	    "What is the minimum time in microseconds between persists");
1637 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1638 	    SYSCTL_CHILDREN(bbr_timeout),
1639 	    OID_AUTO, "persmax", CTLFLAG_RW,
1640 	    &bbr_persist_max, 1000000,
1641 	    "What is the largest delay in microseconds between persists");
1642 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1643 	    SYSCTL_CHILDREN(bbr_timeout),
1644 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1645 	    &bbr_tlp_min, 10000,
1646 	    "TLP Min timeout in usecs");
1647 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1648 	    SYSCTL_CHILDREN(bbr_timeout),
1649 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1650 	    &bbr_delayed_ack_time, 200000,
1651 	    "TLP delayed ack compensation value");
1652 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1653 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1654 	    OID_AUTO, "minrto", CTLFLAG_RW,
1655 	    &bbr_rto_min_ms, 30,
1656 	    "Minimum RTO in ms");
1657 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1658 	    SYSCTL_CHILDREN(bbr_timeout),
1659 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1660 	    &bbr_rto_max_sec, 4,
1661 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1662 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1663 	    SYSCTL_CHILDREN(bbr_timeout),
1664 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1665 	    &bbr_tlp_max_resend, 2,
1666 	    "How many times does TLP retry a single segment or multiple with no ACK");
1667 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1668 	    SYSCTL_CHILDREN(bbr_timeout),
1669 	    OID_AUTO, "minto", CTLFLAG_RW,
1670 	    &bbr_min_to, 1000,
1671 	    "Minimum rack timeout in useconds");
1672 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1673 	    SYSCTL_CHILDREN(bbr_timeout),
1674 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1675 	    &bbr_pkt_delay, 1000,
1676 	    "Extra RACK time (in useconds) besides reordering thresh");
1677 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1678 	    SYSCTL_CHILDREN(bbr_timeout),
1679 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1680 	    &bbr_incr_timers, 1,
1681 	    "Increase the RXT/TLP timer by the pacing time used?");
1682 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1683 	    SYSCTL_CHILDREN(bbr_timeout),
1684 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1685 	    &bbr_marks_rxt_sack_passed, 0,
1686 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1687 	/* Policer controls */
1688 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1689 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1690 	    OID_AUTO,
1691 	    "policer",
1692 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1693 	    "Policer controls");
1694 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1695 	    SYSCTL_CHILDREN(bbr_policer),
1696 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1697 	    &bbr_policer_detection_enabled, 1,
1698 	    "Is policer detection enabled??");
1699 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1700 	    SYSCTL_CHILDREN(bbr_policer),
1701 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1702 	    &bbr_lt_intvl_min_rtts, 4,
1703 	    "Minimum number of PE's?");
1704 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1705 	    SYSCTL_CHILDREN(bbr_policer),
1706 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1707 	    &bbr_lt_bw_diff, (4000/8),
1708 	    "Minimal bw diff?");
1709 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1710 	    SYSCTL_CHILDREN(bbr_policer),
1711 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1712 	    &bbr_lt_bw_ratio, 8,
1713 	    "Minimal bw diff?");
1714 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1715 	    SYSCTL_CHILDREN(bbr_policer),
1716 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1717 	    &bbr_policer_call_from_rack_to, 0,
1718 	    "Do we call the policer detection code from a rack-timeout?");
1719 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1720 	    SYSCTL_CHILDREN(bbr_policer),
1721 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1722 	    &bbr_lt_intvl_fp, 0,
1723 	    "What packet epoch do we do false-positive detection at (0=no)?");
1724 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1725 	    SYSCTL_CHILDREN(bbr_policer),
1726 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1727 	    &bbr_lt_loss_thresh, 196,
1728 	    "Loss threshold 196 = 19.6%?");
1729 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1730 	    SYSCTL_CHILDREN(bbr_policer),
1731 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1732 	    &bbr_lt_fd_thresh, 100,
1733 	    "What percentage is the false detection threshold (150=15.0)?");
1734 	/* All the rest */
1735 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1736 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1737 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1738 	    &bbr_use_rack_resend_cheat, 0,
1739 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1740 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1741 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1742 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1743 	    &bbr_error_base_paceout, 10000,
1744 	    "When we hit an error what is the min to pace out in usec's?");
1745 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1746 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1747 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1748 	    &bbr_max_net_error_cnt, 10,
1749 	    "When we hit this many errors in a row, kill the session?");
1750 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1751 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1752 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1753 	    &bbr_ignore_data_after_close, 1,
1754 	    "Do we hold off sending a RST until all pending data is ack'd");
1755 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1756 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1757 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1758 	    &bbr_resends_use_tso, 0,
1759 	    "Can resends use TSO?");
1760 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1761 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1762 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1763 	    &bbr_sack_block_limit, 128,
1764 	    "When do we start ignoring small sack blocks");
1765 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1766 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1767 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1768 	    &bbr_verbose_logging, 0,
1769 	    "Should BBR black box logging be verbose");
1770 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1771 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1772 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1773 	    &bbr_reorder_thresh, 2,
1774 	    "What factor for rack will be added when seeing reordering (shift right)");
1775 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1776 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1777 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1778 	    &bbr_reorder_fade, 0,
1779 	    "Does reorder detection fade, if so how many ms (0 means never)");
1780 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1781 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1782 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1783 	    &bbr_tlp_thresh, 1,
1784 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1785 	/* Stats and counters */
1786 	/* The pacing counters for hdwr/software can't be in the array */
1787 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1788 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1789 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1790 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1791 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1792 	    &bbr_hdwr_pacing_enobuf,
1793 	    "Total number of enobufs for hardware paced flows");
1794 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1795 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1796 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1797 	    &bbr_nohdwr_pacing_enobuf,
1798 	    "Total number of enobufs for non-hardware paced flows");
1799 
1800 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1801 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1802 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1803 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1804 	    &bbr_flows_whdwr_pacing,
1805 	    "Total number of hardware paced flows");
1806 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1807 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1808 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1809 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1810 	    &bbr_flows_nohdwr_pacing,
1811 	    "Total number of software paced flows");
1812 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1813 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1814 	    OID_AUTO, "stats", CTLFLAG_RD,
1815 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1816 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1817 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1818 	    OID_AUTO, "opts", CTLFLAG_RD,
1819 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1820 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1821 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1822 	    OID_AUTO, "lost", CTLFLAG_RD,
1823 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1824 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1825 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1826 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1827 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1828 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1829 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1830 	    OID_AUTO, "statetime", CTLFLAG_RD,
1831 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1832 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1833 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1834 	    OID_AUTO, "outsize", CTLFLAG_RD,
1835 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1836 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1837 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1838 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1839 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1840 }
1841 
1842 static void
1843 bbr_counter_destroy(void)
1844 {
1845 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1846 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1847 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1848 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1849 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1850 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1851 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1852 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1853 	counter_u64_free(bbr_flows_whdwr_pacing);
1854 	counter_u64_free(bbr_flows_nohdwr_pacing);
1855 
1856 }
1857 
1858 static __inline void
1859 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1860 {
1861 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1862 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1863 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1864 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1865 	l->bw_inuse = bbr_get_bw(bbr);
1866 	l->inflight = ctf_flight_size(bbr->rc_tp,
1867 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1868 	l->applimited = bbr->r_ctl.r_app_limited_until;
1869 	l->delivered = bbr->r_ctl.rc_delivered;
1870 	l->timeStamp = cts;
1871 	l->lost = bbr->r_ctl.rc_lost;
1872 	l->bbr_state = bbr->rc_bbr_state;
1873 	l->bbr_substate = bbr_state_val(bbr);
1874 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1875 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1876 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1877 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1878 	l->inhpts = tcp_in_hpts(bbr->rc_tp);
1879 	l->use_lt_bw = bbr->rc_lt_use_bw;
1880 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1881 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1882 }
1883 
1884 static void
1885 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1886 {
1887 	if (tcp_bblogging_on(bbr->rc_tp)) {
1888 		union tcp_log_stackspecific log;
1889 
1890 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1891 		log.u_bbr.flex1 = 0;
1892 		log.u_bbr.flex2 = 0;
1893 		log.u_bbr.flex5 = 0;
1894 		log.u_bbr.flex3 = 0;
1895 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1896 		log.u_bbr.flex7 = reason;
1897 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1898 		log.u_bbr.flex8 = 0;
1899 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1900 		    &bbr->rc_inp->inp_socket->so_rcv,
1901 		    &bbr->rc_inp->inp_socket->so_snd,
1902 		    BBR_LOG_BW_RED_EV, 0,
1903 		    0, &log, false, &bbr->rc_tv);
1904 	}
1905 }
1906 
1907 static void
1908 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1909 {
1910 	if (tcp_bblogging_on(bbr->rc_tp)) {
1911 		union tcp_log_stackspecific log;
1912 
1913 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1914 		log.u_bbr.flex1 = seq;
1915 		log.u_bbr.flex2 = count;
1916 		log.u_bbr.flex8 = mode;
1917 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1918 		    &bbr->rc_inp->inp_socket->so_rcv,
1919 		    &bbr->rc_inp->inp_socket->so_snd,
1920 		    BBR_LOG_LOWGAIN, 0,
1921 		    0, &log, false, &bbr->rc_tv);
1922 	}
1923 }
1924 
1925 static void
1926 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1927     uint8_t reason, uint32_t p_maxseg, int len)
1928 {
1929 	if (tcp_bblogging_on(bbr->rc_tp)) {
1930 		union tcp_log_stackspecific log;
1931 
1932 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1933 		log.u_bbr.flex1 = p_maxseg;
1934 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1935 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1936 		log.u_bbr.flex4 = reason;
1937 		log.u_bbr.flex5 = bbr->rc_in_persist;
1938 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1939 		log.u_bbr.flex7 = p_maxseg;
1940 		log.u_bbr.flex8 = bbr->rc_in_persist;
1941 		log.u_bbr.pkts_out = 0;
1942 		log.u_bbr.applimited = len;
1943 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1944 		    &bbr->rc_inp->inp_socket->so_rcv,
1945 		    &bbr->rc_inp->inp_socket->so_snd,
1946 		    BBR_LOG_JUSTRET, 0,
1947 		    tlen, &log, false, &bbr->rc_tv);
1948 	}
1949 }
1950 
1951 static void
1952 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1953 {
1954 	if (tcp_bblogging_on(bbr->rc_tp)) {
1955 		union tcp_log_stackspecific log;
1956 
1957 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1958 		log.u_bbr.flex1 = seq;
1959 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1960 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1961 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1962 		    &bbr->rc_inp->inp_socket->so_rcv,
1963 		    &bbr->rc_inp->inp_socket->so_snd,
1964 		    BBR_LOG_ENTREC, 0,
1965 		    0, &log, false, &bbr->rc_tv);
1966 	}
1967 }
1968 
1969 static void
1970 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)
1971 {
1972 	if (tcp_bblogging_on(tp)) {
1973 		union tcp_log_stackspecific log;
1974 
1975 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1976 		log.u_bbr.flex1 = tso;
1977 		log.u_bbr.flex2 = maxseg;
1978 		log.u_bbr.flex3 = mtu;
1979 		log.u_bbr.flex4 = csum_flags;
1980 		TCP_LOG_EVENTP(tp, NULL,
1981 		    &bbr->rc_inp->inp_socket->so_rcv,
1982 		    &bbr->rc_inp->inp_socket->so_snd,
1983 		    BBR_LOG_MSGSIZE, 0,
1984 		    0, &log, false, &bbr->rc_tv);
1985 	}
1986 }
1987 
1988 static void
1989 bbr_log_flowend(struct tcp_bbr *bbr)
1990 {
1991 	if (tcp_bblogging_on(bbr->rc_tp)) {
1992 		union tcp_log_stackspecific log;
1993 		struct sockbuf *r, *s;
1994 		struct timeval tv;
1995 
1996 		if (bbr->rc_inp->inp_socket) {
1997 			r = &bbr->rc_inp->inp_socket->so_rcv;
1998 			s = &bbr->rc_inp->inp_socket->so_snd;
1999 		} else {
2000 			r = s = NULL;
2001 		}
2002 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2003 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2004 		    r, s,
2005 		    TCP_LOG_FLOWEND, 0,
2006 		    0, &log, false, &tv);
2007 	}
2008 }
2009 
2010 static void
2011 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2012     uint32_t lost, uint32_t del)
2013 {
2014 	if (tcp_bblogging_on(bbr->rc_tp)) {
2015 		union tcp_log_stackspecific log;
2016 
2017 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2018 		log.u_bbr.flex1 = lost;
2019 		log.u_bbr.flex2 = del;
2020 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2021 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2022 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2023 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2024 		log.u_bbr.flex7 = line;
2025 		log.u_bbr.flex8 = 0;
2026 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2027 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2028 		    &bbr->rc_inp->inp_socket->so_rcv,
2029 		    &bbr->rc_inp->inp_socket->so_snd,
2030 		    BBR_LOG_PKT_EPOCH, 0,
2031 		    0, &log, false, &bbr->rc_tv);
2032 	}
2033 }
2034 
2035 static void
2036 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2037 {
2038 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2039 		union tcp_log_stackspecific log;
2040 
2041 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2042 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2043 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2044 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2045 		log.u_bbr.flex7 = line;
2046 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2047 		    &bbr->rc_inp->inp_socket->so_rcv,
2048 		    &bbr->rc_inp->inp_socket->so_snd,
2049 		    BBR_LOG_TIME_EPOCH, 0,
2050 		    0, &log, false, &bbr->rc_tv);
2051 	}
2052 }
2053 
2054 static void
2055 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2056 {
2057 	if (tcp_bblogging_on(bbr->rc_tp)) {
2058 		union tcp_log_stackspecific log;
2059 
2060 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2061 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2062 		log.u_bbr.flex2 = new_tar;
2063 		log.u_bbr.flex3 = line;
2064 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2065 		log.u_bbr.flex5 = bbr_quanta;
2066 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2067 		log.u_bbr.flex7 = bbr->rc_last_options;
2068 		log.u_bbr.flex8 = meth;
2069 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2070 		    &bbr->rc_inp->inp_socket->so_rcv,
2071 		    &bbr->rc_inp->inp_socket->so_snd,
2072 		    BBR_LOG_STATE_TARGET, 0,
2073 		    0, &log, false, &bbr->rc_tv);
2074 	}
2075 
2076 }
2077 
2078 static void
2079 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2080 {
2081 	if (tcp_bblogging_on(bbr->rc_tp)) {
2082 		union tcp_log_stackspecific log;
2083 
2084 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2085 		log.u_bbr.flex1 = line;
2086 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2087 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2088 		if (bbr_state_is_pkt_epoch)
2089 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2090 		else
2091 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2092 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2093 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2094 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2095 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2096 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2097 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2098 		    &bbr->rc_inp->inp_socket->so_rcv,
2099 		    &bbr->rc_inp->inp_socket->so_snd,
2100 		    BBR_LOG_STATE, 0,
2101 		    0, &log, false, &bbr->rc_tv);
2102 	}
2103 }
2104 
2105 static void
2106 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2107 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2108 {
2109 	if (tcp_bblogging_on(bbr->rc_tp)) {
2110 		union tcp_log_stackspecific log;
2111 
2112 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2113 		log.u_bbr.flex1 = line;
2114 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2115 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2116 		log.u_bbr.flex4 = applied;
2117 		log.u_bbr.flex5 = rtt;
2118 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2119 		log.u_bbr.flex7 = cond;
2120 		log.u_bbr.flex8 = reas;
2121 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2122 		    &bbr->rc_inp->inp_socket->so_rcv,
2123 		    &bbr->rc_inp->inp_socket->so_snd,
2124 		    BBR_LOG_RTT_SHRINKS, 0,
2125 		    0, &log, false, &bbr->rc_tv);
2126 	}
2127 }
2128 
2129 static void
2130 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2131 {
2132 	if (tcp_bblogging_on(bbr->rc_tp)) {
2133 		union tcp_log_stackspecific log;
2134 
2135 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2136 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2137 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2138 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2139 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2140 		    &bbr->rc_inp->inp_socket->so_rcv,
2141 		    &bbr->rc_inp->inp_socket->so_snd,
2142 		    BBR_LOG_EXITREC, 0,
2143 		    0, &log, false, &bbr->rc_tv);
2144 	}
2145 }
2146 
2147 static void
2148 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2149     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2150 {
2151 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2152 		union tcp_log_stackspecific log;
2153 
2154 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2155 		log.u_bbr.flex1 = line;
2156 		log.u_bbr.flex2 = prev_acked;
2157 		log.u_bbr.flex3 = bytes_this_ack;
2158 		log.u_bbr.flex4 = chg;
2159 		log.u_bbr.flex5 = th_ack;
2160 		log.u_bbr.flex6 = target;
2161 		log.u_bbr.flex8 = meth;
2162 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2163 		    &bbr->rc_inp->inp_socket->so_rcv,
2164 		    &bbr->rc_inp->inp_socket->so_snd,
2165 		    BBR_LOG_CWND, 0,
2166 		    0, &log, false, &bbr->rc_tv);
2167 	}
2168 }
2169 
2170 static void
2171 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2172 {
2173 	/*
2174 	 * Log the rtt sample we are applying to the srtt algorithm in
2175 	 * useconds.
2176 	 */
2177 	if (tcp_bblogging_on(bbr->rc_tp)) {
2178 		union tcp_log_stackspecific log;
2179 
2180 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2181 		log.u_bbr.flex1 = rtt;
2182 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2183 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2184 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2185 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2186 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2187 		log.u_bbr.flex6 = tsin;
2188 		log.u_bbr.flex7 = 0;
2189 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2190 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2191 		    &bbr->rc_inp->inp_socket->so_rcv,
2192 		    &bbr->rc_inp->inp_socket->so_snd,
2193 		    TCP_LOG_RTT, 0,
2194 		    0, &log, false, &bbr->rc_tv);
2195 	}
2196 }
2197 
2198 static void
2199 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2200 {
2201 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2202 		union tcp_log_stackspecific log;
2203 
2204 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2205 		log.u_bbr.flex1 = time_in;
2206 		log.u_bbr.flex2 = line;
2207 		log.u_bbr.flex8 = enter_exit;
2208 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2209 		    &bbr->rc_inp->inp_socket->so_rcv,
2210 		    &bbr->rc_inp->inp_socket->so_snd,
2211 		    BBR_LOG_PERSIST, 0,
2212 		    0, &log, false, &bbr->rc_tv);
2213 	}
2214 }
2215 static void
2216 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2217 {
2218 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2219 		union tcp_log_stackspecific log;
2220 
2221 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2222 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2223 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2224 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2225 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2226 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2227 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2228 		    &bbr->rc_inp->inp_socket->so_rcv,
2229 		    &bbr->rc_inp->inp_socket->so_snd,
2230 		    BBR_LOG_ACKCLEAR, 0,
2231 		    0, &log, false, &bbr->rc_tv);
2232 	}
2233 }
2234 
2235 static void
2236 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2237 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2238 {
2239 	if (tcp_bblogging_on(bbr->rc_tp)) {
2240 		union tcp_log_stackspecific log;
2241 		struct timeval tv;
2242 
2243 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2244 		log.u_bbr.flex1 = nsegs;
2245 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2246 		if (m) {
2247 			struct timespec ts;
2248 
2249 			log.u_bbr.flex3 = m->m_flags;
2250 			if (m->m_flags & M_TSTMP) {
2251 				mbuf_tstmp2timespec(m, &ts);
2252 				tv.tv_sec = ts.tv_sec;
2253 				tv.tv_usec = ts.tv_nsec / 1000;
2254 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2255 			} else {
2256 				log.u_bbr.lt_epoch = 0;
2257 			}
2258 			if (m->m_flags & M_TSTMP_LRO) {
2259 				mbuf_tstmp2timeval(m, &tv);
2260 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2261 			} else {
2262 				/* No arrival timestamp */
2263 				log.u_bbr.flex5 = 0;
2264 			}
2265 
2266 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2267 		} else {
2268 			log.u_bbr.flex3 = 0;
2269 			log.u_bbr.flex5 = 0;
2270 			log.u_bbr.flex6 = 0;
2271 			log.u_bbr.pkts_out = 0;
2272 		}
2273 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2274 		log.u_bbr.flex7 = bbr->r_wanted_output;
2275 		log.u_bbr.flex8 = bbr->rc_in_persist;
2276 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2277 		    &bbr->rc_inp->inp_socket->so_rcv,
2278 		    &bbr->rc_inp->inp_socket->so_snd,
2279 		    TCP_LOG_IN, 0,
2280 		    tlen, &log, true, &bbr->rc_tv);
2281 	}
2282 }
2283 
2284 static void
2285 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2286 {
2287 	if (tcp_bblogging_on(bbr->rc_tp)) {
2288 		union tcp_log_stackspecific log;
2289 
2290 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2291 		log.u_bbr.flex1 = did_out;
2292 		log.u_bbr.flex2 = nxt_pkt;
2293 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2294 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2295 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2296 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2297 		log.u_bbr.flex7 = bbr->r_wanted_output;
2298 		log.u_bbr.flex8 = bbr->rc_in_persist;
2299 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2300 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2301 		    &bbr->rc_inp->inp_socket->so_rcv,
2302 		    &bbr->rc_inp->inp_socket->so_snd,
2303 		    BBR_LOG_DOSEG_DONE, 0,
2304 		    0, &log, true, &bbr->rc_tv);
2305 	}
2306 }
2307 
2308 static void
2309 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2310     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2311 {
2312 	if (tcp_bblogging_on(bbr->rc_tp)) {
2313 		union tcp_log_stackspecific log;
2314 
2315 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2316 		log.u_bbr.flex1 = line;
2317 		log.u_bbr.flex2 = o_len;
2318 		log.u_bbr.flex3 = segcnt;
2319 		log.u_bbr.flex4 = segsiz;
2320 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2321 		    &bbr->rc_inp->inp_socket->so_rcv,
2322 		    &bbr->rc_inp->inp_socket->so_snd,
2323 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2324 		    len, &log, true, &bbr->rc_tv);
2325 	}
2326 }
2327 
2328 static void
2329 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2330 {
2331 	if (tcp_bblogging_on(bbr->rc_tp)) {
2332 		union tcp_log_stackspecific log;
2333 
2334 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2335 		log.u_bbr.flex1 = timers;
2336 		log.u_bbr.flex2 = ret;
2337 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2338 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2339 		log.u_bbr.flex5 = cts;
2340 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2341 		log.u_bbr.flex8 = hpts_calling;
2342 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2343 		    &bbr->rc_inp->inp_socket->so_rcv,
2344 		    &bbr->rc_inp->inp_socket->so_snd,
2345 		    BBR_LOG_TO_PROCESS, 0,
2346 		    0, &log, false, &bbr->rc_tv);
2347 	}
2348 }
2349 
2350 static void
2351 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2352 {
2353 	if (tcp_bblogging_on(bbr->rc_tp)) {
2354 		union tcp_log_stackspecific log;
2355 		uint64_t ar;
2356 
2357 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2358 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2359 		log.u_bbr.flex2 = 0;
2360 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2361 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2362 		ar >>= 32;
2363 		ar &= 0x00000000ffffffff;
2364 		log.u_bbr.flex4 = (uint32_t)ar;
2365 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2366 		ar &= 0x00000000ffffffff;
2367 		log.u_bbr.flex5 = (uint32_t)ar;
2368 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2369 		log.u_bbr.flex8 = to_num;
2370 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2371 		    &bbr->rc_inp->inp_socket->so_rcv,
2372 		    &bbr->rc_inp->inp_socket->so_snd,
2373 		    BBR_LOG_RTO, 0,
2374 		    0, &log, false, &bbr->rc_tv);
2375 	}
2376 }
2377 
2378 static void
2379 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2380 {
2381 	if (tcp_bblogging_on(bbr->rc_tp)) {
2382 		union tcp_log_stackspecific log;
2383 
2384 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2385 		log.u_bbr.flex1 = flex1;
2386 		log.u_bbr.flex2 = flex2;
2387 		log.u_bbr.flex3 = flex3;
2388 		log.u_bbr.flex4 = 0;
2389 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2390 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2391 		log.u_bbr.flex8 = reason;
2392 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2393 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2394 		    &bbr->rc_inp->inp_socket->so_rcv,
2395 		    &bbr->rc_inp->inp_socket->so_snd,
2396 		    BBR_LOG_REDUCE, 0,
2397 		    0, &log, false, &bbr->rc_tv);
2398 	}
2399 }
2400 
2401 static void
2402 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2403 {
2404 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2405 		union tcp_log_stackspecific log;
2406 
2407 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2408 		log.u_bbr.flex1 = diag->p_nxt_slot;
2409 		log.u_bbr.flex2 = diag->p_cur_slot;
2410 		log.u_bbr.flex3 = diag->slot_req;
2411 		log.u_bbr.flex4 = diag->inp_hptsslot;
2412 		log.u_bbr.flex5 = diag->slot_remaining;
2413 		log.u_bbr.flex6 = diag->need_new_to;
2414 		log.u_bbr.flex7 = diag->p_hpts_active;
2415 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2416 		/* Hijack other fields as needed  */
2417 		log.u_bbr.epoch = diag->have_slept;
2418 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2419 		log.u_bbr.pkts_out = diag->co_ret;
2420 		log.u_bbr.applimited = diag->hpts_sleep_time;
2421 		log.u_bbr.delivered = diag->p_prev_slot;
2422 		log.u_bbr.inflight = diag->p_runningslot;
2423 		log.u_bbr.bw_inuse = diag->wheel_slot;
2424 		log.u_bbr.rttProp = diag->wheel_cts;
2425 		log.u_bbr.delRate = diag->maxslots;
2426 		log.u_bbr.cur_del_rate = diag->p_curtick;
2427 		log.u_bbr.cur_del_rate <<= 32;
2428 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2429 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2430 		    &bbr->rc_inp->inp_socket->so_rcv,
2431 		    &bbr->rc_inp->inp_socket->so_snd,
2432 		    BBR_LOG_HPTSDIAG, 0,
2433 		    0, &log, false, &bbr->rc_tv);
2434 	}
2435 }
2436 
2437 static void
2438 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2439     uint32_t thresh, uint32_t to)
2440 {
2441 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2442 		union tcp_log_stackspecific log;
2443 
2444 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2445 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2446 		log.u_bbr.flex2 = time_since_sent;
2447 		log.u_bbr.flex3 = srtt;
2448 		log.u_bbr.flex4 = thresh;
2449 		log.u_bbr.flex5 = to;
2450 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2451 		log.u_bbr.flex8 = mode;
2452 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2453 		    &bbr->rc_inp->inp_socket->so_rcv,
2454 		    &bbr->rc_inp->inp_socket->so_snd,
2455 		    BBR_LOG_TIMERPREP, 0,
2456 		    0, &log, false, &bbr->rc_tv);
2457 	}
2458 }
2459 
2460 static void
2461 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2462     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2463 {
2464 	if (tcp_bblogging_on(bbr->rc_tp)) {
2465 		union tcp_log_stackspecific log;
2466 
2467 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2468 		log.u_bbr.flex1 = usecs;
2469 		log.u_bbr.flex2 = len;
2470 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2471 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2472 		if (override)
2473 			log.u_bbr.flex5 = (1 << 2);
2474 		else
2475 			log.u_bbr.flex5 = 0;
2476 		log.u_bbr.flex6 = override;
2477 		log.u_bbr.flex7 = gain;
2478 		log.u_bbr.flex8 = mod;
2479 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2480 		    &bbr->rc_inp->inp_socket->so_rcv,
2481 		    &bbr->rc_inp->inp_socket->so_snd,
2482 		    BBR_LOG_HPTSI_CALC, 0,
2483 		    len, &log, false, &bbr->rc_tv);
2484 	}
2485 }
2486 
2487 static void
2488 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2489 {
2490 	if (tcp_bblogging_on(bbr->rc_tp)) {
2491 		union tcp_log_stackspecific log;
2492 
2493 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2494 
2495 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2496 		log.u_bbr.flex2 = to;
2497 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2498 		log.u_bbr.flex4 = slot;
2499 		log.u_bbr.flex5 = bbr->rc_tp->t_hpts_slot;
2500 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2501 		log.u_bbr.pkts_out = bbr->rc_tp->t_flags2;
2502 		log.u_bbr.flex8 = which;
2503 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2504 		    &bbr->rc_inp->inp_socket->so_rcv,
2505 		    &bbr->rc_inp->inp_socket->so_snd,
2506 		    BBR_LOG_TIMERSTAR, 0,
2507 		    0, &log, false, &bbr->rc_tv);
2508 	}
2509 }
2510 
2511 static void
2512 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)
2513 {
2514 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2515 		union tcp_log_stackspecific log;
2516 
2517 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2518 		log.u_bbr.flex1 = thresh;
2519 		log.u_bbr.flex2 = lro;
2520 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2521 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2522 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2523 		log.u_bbr.flex6 = srtt;
2524 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2525 		log.u_bbr.flex8 = frm;
2526 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2527 		    &bbr->rc_inp->inp_socket->so_rcv,
2528 		    &bbr->rc_inp->inp_socket->so_snd,
2529 		    BBR_LOG_THRESH_CALC, 0,
2530 		    0, &log, false, &bbr->rc_tv);
2531 	}
2532 }
2533 
2534 static void
2535 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2536 {
2537 	if (tcp_bblogging_on(bbr->rc_tp)) {
2538 		union tcp_log_stackspecific log;
2539 
2540 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2541 		log.u_bbr.flex1 = line;
2542 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2543 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2544 		log.u_bbr.flex4 = bbr->rc_in_persist;
2545 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2546 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2547 		log.u_bbr.flex8 = hpts_removed;
2548 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2549 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2550 		    &bbr->rc_inp->inp_socket->so_rcv,
2551 		    &bbr->rc_inp->inp_socket->so_snd,
2552 		    BBR_LOG_TIMERCANC, 0,
2553 		    0, &log, false, &bbr->rc_tv);
2554 	}
2555 }
2556 
2557 static void
2558 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2559 {
2560 	if (tcp_bblogging_on(bbr->rc_tp)) {
2561 		union tcp_log_stackspecific log;
2562 
2563 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2564 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2565 		log.u_bbr.flex2 = (peer_delta >> 32);
2566 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2567 		log.u_bbr.flex4 = (delta >> 32);
2568 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2569 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2570 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2571 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2572 		    &bbr->rc_inp->inp_socket->so_rcv,
2573 		    &bbr->rc_inp->inp_socket->so_snd,
2574 		    BBR_LOG_TSTMP_VAL, 0,
2575 		    0, &log, false, &bbr->rc_tv);
2576 	}
2577 }
2578 
2579 static void
2580 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)
2581 {
2582 	if (tcp_bblogging_on(bbr->rc_tp)) {
2583 		union tcp_log_stackspecific log;
2584 
2585 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2586 		log.u_bbr.flex1 = tsosz;
2587 		log.u_bbr.flex2 = tls;
2588 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2589 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2590 		log.u_bbr.flex5 = old_val;
2591 		log.u_bbr.flex6 = maxseg;
2592 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2593 		log.u_bbr.flex7 <<= 1;
2594 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2595 		if (hdwr)
2596 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2597 		else
2598 			log.u_bbr.flex8 = bbr->rc_use_google;
2599 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2600 		    &bbr->rc_inp->inp_socket->so_rcv,
2601 		    &bbr->rc_inp->inp_socket->so_snd,
2602 		    BBR_LOG_BBRTSO, 0,
2603 		    0, &log, false, &bbr->rc_tv);
2604 	}
2605 }
2606 
2607 static void
2608 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2609 		      uint32_t flags, uint32_t line)
2610 {
2611 	if (tcp_bblogging_on(bbr->rc_tp)) {
2612 		union tcp_log_stackspecific log;
2613 
2614 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2615 		log.u_bbr.flex1 = line;
2616 		log.u_bbr.flex2 = rsm->r_start;
2617 		log.u_bbr.flex3 = rsm->r_end;
2618 		log.u_bbr.flex4 = rsm->r_delivered;
2619 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2620 		log.u_bbr.flex6 = rsm->r_dupack;
2621 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2622 		log.u_bbr.flex8 = rsm->r_flags;
2623 		/* Hijack the pkts_out fids */
2624 		log.u_bbr.applimited = flags;
2625 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2626 		    &bbr->rc_inp->inp_socket->so_rcv,
2627 		    &bbr->rc_inp->inp_socket->so_snd,
2628 		    BBR_RSM_CLEARED, 0,
2629 		    0, &log, false, &bbr->rc_tv);
2630 	}
2631 }
2632 
2633 static void
2634 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2635     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2636     uint32_t flex6, uint32_t pkts_out, int flex7,
2637     uint32_t flex4, uint32_t flex1)
2638 {
2639 
2640 	if (tcp_bblogging_on(bbr->rc_tp)) {
2641 		union tcp_log_stackspecific log;
2642 
2643 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2644 		log.u_bbr.flex1 = flex1;
2645 		log.u_bbr.flex2 = flex2;
2646 		log.u_bbr.flex3 = flex3;
2647 		log.u_bbr.flex4 = flex4;
2648 		log.u_bbr.flex5 = flex5;
2649 		log.u_bbr.flex6 = flex6;
2650 		log.u_bbr.flex7 = flex7;
2651 		/* Hijack the pkts_out fids */
2652 		log.u_bbr.pkts_out = pkts_out;
2653 		log.u_bbr.flex8 = flex8;
2654 		if (bbr->rc_ack_was_delayed)
2655 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2656 		else
2657 			log.u_bbr.epoch = 0;
2658 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2659 		    &bbr->rc_inp->inp_socket->so_rcv,
2660 		    &bbr->rc_inp->inp_socket->so_snd,
2661 		    BBR_LOG_BBRUPD, 0,
2662 		    flex2, &log, false, &bbr->rc_tv);
2663 	}
2664 }
2665 
2666 static void
2667 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2668 	uint32_t newbw, uint32_t obw, uint32_t diff,
2669 	uint32_t tim)
2670 {
2671 	if (/*bbr_verbose_logging && */tcp_bblogging_on(bbr->rc_tp)) {
2672 		union tcp_log_stackspecific log;
2673 
2674 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2675 		log.u_bbr.flex1 = reason;
2676 		log.u_bbr.flex2 = newbw;
2677 		log.u_bbr.flex3 = obw;
2678 		log.u_bbr.flex4 = diff;
2679 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2680 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2681 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2682 		log.u_bbr.pkts_out = tim;
2683 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2684 		if (bbr->rc_lt_use_bw == 0)
2685 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2686 		else
2687 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2688 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2689 		    &bbr->rc_inp->inp_socket->so_rcv,
2690 		    &bbr->rc_inp->inp_socket->so_snd,
2691 		    BBR_LOG_BWSAMP, 0,
2692 		    0, &log, false, &bbr->rc_tv);
2693 	}
2694 }
2695 
2696 static inline void
2697 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2698 {
2699 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2700 		union tcp_log_stackspecific log;
2701 
2702 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2703 		log.u_bbr.flex1 = line;
2704 		log.u_bbr.flex2 = tick;
2705 		log.u_bbr.flex3 = tp->t_maxunacktime;
2706 		log.u_bbr.flex4 = tp->t_acktime;
2707 		log.u_bbr.flex8 = event;
2708 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2709 		    &bbr->rc_inp->inp_socket->so_rcv,
2710 		    &bbr->rc_inp->inp_socket->so_snd,
2711 		    BBR_LOG_PROGRESS, 0,
2712 		    0, &log, false, &bbr->rc_tv);
2713 	}
2714 }
2715 
2716 static void
2717 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2718 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2719 			 int error)
2720 {
2721 	if (tcp_bblogging_on(bbr->rc_tp)) {
2722 		union tcp_log_stackspecific log;
2723 
2724 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2725 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2726 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2727 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2728 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2729 		log.u_bbr.bw_inuse = rate;
2730 		log.u_bbr.flex5 = line;
2731 		log.u_bbr.flex6 = error;
2732 		log.u_bbr.flex8 = bbr->skip_gain;
2733 		log.u_bbr.flex8 <<= 1;
2734 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2735 		log.u_bbr.flex8 <<= 1;
2736 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2737 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2738 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2739 		    &bbr->rc_inp->inp_socket->so_rcv,
2740 		    &bbr->rc_inp->inp_socket->so_snd,
2741 		    BBR_LOG_HDWR_PACE, 0,
2742 		    0, &log, false, &bbr->rc_tv);
2743 	}
2744 }
2745 
2746 static void
2747 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)
2748 {
2749 	if (tcp_bblogging_on(bbr->rc_tp)) {
2750 		union tcp_log_stackspecific log;
2751 
2752 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2753 		log.u_bbr.flex1 = slot;
2754 		log.u_bbr.flex2 = del_by;
2755 		log.u_bbr.flex3 = prev_delay;
2756 		log.u_bbr.flex4 = line;
2757 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2758 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2759 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2760 		log.u_bbr.flex8 = bbr->rc_in_persist;
2761 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2762 		    &bbr->rc_inp->inp_socket->so_rcv,
2763 		    &bbr->rc_inp->inp_socket->so_snd,
2764 		    BBR_LOG_BBRSND, 0,
2765 		    len, &log, false, &bbr->rc_tv);
2766 	}
2767 }
2768 
2769 static void
2770 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)
2771 {
2772 	if (tcp_bblogging_on(bbr->rc_tp)) {
2773 		union tcp_log_stackspecific log;
2774 
2775 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2776 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2777 		log.u_bbr.flex2 = 0;
2778 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2779 		log.u_bbr.flex4 = end;
2780 		log.u_bbr.flex5 = seq;
2781 		log.u_bbr.flex6 = t;
2782 		log.u_bbr.flex7 = match;
2783 		log.u_bbr.flex8 = flags;
2784 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2785 		    &bbr->rc_inp->inp_socket->so_rcv,
2786 		    &bbr->rc_inp->inp_socket->so_snd,
2787 		    BBR_LOG_BBRRTT, 0,
2788 		    0, &log, false, &bbr->rc_tv);
2789 	}
2790 }
2791 
2792 static void
2793 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2794 {
2795 	if (tcp_bblogging_on(bbr->rc_tp)) {
2796 		union tcp_log_stackspecific log;
2797 
2798 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2799 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2800 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2801 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2802 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2803 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2804 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2805 		log.u_bbr.flex7 = 0;
2806 		log.u_bbr.flex8 = entry_method;
2807 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2808 		    &bbr->rc_inp->inp_socket->so_rcv,
2809 		    &bbr->rc_inp->inp_socket->so_snd,
2810 		    BBR_LOG_EXIT_GAIN, 0,
2811 		    0, &log, false, &bbr->rc_tv);
2812 	}
2813 }
2814 
2815 static void
2816 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2817 {
2818 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2819 		union tcp_log_stackspecific log;
2820 
2821 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2822 		/* R-HU */
2823 		log.u_bbr.flex1 = 0;
2824 		log.u_bbr.flex2 = 0;
2825 		log.u_bbr.flex3 = 0;
2826 		log.u_bbr.flex4 = 0;
2827 		log.u_bbr.flex7 = 0;
2828 		log.u_bbr.flex8 = settings_desired;
2829 
2830 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2831 		    &bbr->rc_inp->inp_socket->so_rcv,
2832 		    &bbr->rc_inp->inp_socket->so_snd,
2833 		    BBR_LOG_SETTINGS_CHG, 0,
2834 		    0, &log, false, &bbr->rc_tv);
2835 	}
2836 }
2837 
2838 /*
2839  * Returns the bw from the our filter.
2840  */
2841 static inline uint64_t
2842 bbr_get_full_bw(struct tcp_bbr *bbr)
2843 {
2844 	uint64_t bw;
2845 
2846 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2847 
2848 	return (bw);
2849 }
2850 
2851 static inline void
2852 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2853 {
2854 	uint64_t calclr;
2855 	uint32_t lost, del;
2856 
2857 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2858 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2859 	else
2860 		lost = 0;
2861 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2862 	if (lost == 0)  {
2863 		calclr = 0;
2864 	} else if (del) {
2865 		calclr = lost;
2866 		calclr *= (uint64_t)1000;
2867 		calclr /= (uint64_t)del;
2868 	} else {
2869 		/* Nothing delivered? 100.0% loss */
2870 		calclr = 1000;
2871 	}
2872 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2873 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2874 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2875 	bbr->r_ctl.rc_pkt_epoch++;
2876 	if (bbr->rc_no_pacing &&
2877 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2878 		bbr->rc_no_pacing = 0;
2879 		tcp_bbr_tso_size_check(bbr, cts);
2880 	}
2881 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2882 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2883 	/* What was our loss rate */
2884 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2885 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2886 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2887 }
2888 
2889 static inline void
2890 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2891 {
2892 	uint32_t epoch_time;
2893 
2894 	/* Tick the RTT clock */
2895 	bbr->r_ctl.rc_rtt_epoch++;
2896 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2897 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2898 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2899 }
2900 
2901 static inline void
2902 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2903 {
2904 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2905 		bbr->rc_is_pkt_epoch_now = 1;
2906 	}
2907 }
2908 
2909 /*
2910  * Returns the bw from either the b/w filter
2911  * or from the lt_bw (if the connection is being
2912  * policed).
2913  */
2914 static inline uint64_t
2915 __bbr_get_bw(struct tcp_bbr *bbr)
2916 {
2917 	uint64_t bw, min_bw;
2918 	uint64_t rtt;
2919 	int gm_measure_cnt = 1;
2920 
2921 	/*
2922 	 * For startup we make, like google, a
2923 	 * minimum b/w. This is generated from the
2924 	 * IW and the rttProp. We do fall back to srtt
2925 	 * if for some reason (initial handshake) we don't
2926 	 * have a rttProp. We, in the worst case, fall back
2927 	 * to the configured min_bw (rc_initial_hptsi_bw).
2928 	 */
2929 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2930 		/* Attempt first to use rttProp */
2931 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2932 		if (rtt && (rtt < 0xffffffff)) {
2933 measure:
2934 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2935 				((uint64_t)1000000);
2936 			min_bw /= rtt;
2937 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2938 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2939 			}
2940 
2941 		} else if (bbr->rc_tp->t_srtt != 0) {
2942 			/* No rttProp, use srtt? */
2943 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2944 			goto measure;
2945 		} else {
2946 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2947 		}
2948 	} else
2949 		min_bw = 0;
2950 
2951 	if ((bbr->rc_past_init_win == 0) &&
2952 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2953 		bbr->rc_past_init_win = 1;
2954 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2955 		gm_measure_cnt = 0;
2956 	if (gm_measure_cnt &&
2957 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2958 	     (bbr->rc_past_init_win == 0))) {
2959 		/* For google we use our guess rate until we get 1 measurement */
2960 
2961 use_initial_window:
2962 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2963 		if (rtt && (rtt < 0xffffffff)) {
2964 			/*
2965 			 * We have an RTT measurement. Use that in
2966 			 * combination with our initial window to calculate
2967 			 * a b/w.
2968 			 */
2969 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2970 				((uint64_t)1000000);
2971 			bw /= rtt;
2972 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2973 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2974 			}
2975 		} else {
2976 			/* Drop back to the 40 and punt to a default */
2977 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2978 		}
2979 		if (bw < 1)
2980 			/* Probably should panic */
2981 			bw = 1;
2982 		if (bw > min_bw)
2983 			return (bw);
2984 		else
2985 			return (min_bw);
2986 	}
2987 	if (bbr->rc_lt_use_bw)
2988 		bw = bbr->r_ctl.rc_lt_bw;
2989 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2990 		bw = bbr->r_ctl.red_bw;
2991 	else
2992 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2993 	if (bw == 0) {
2994 		/* We should not be at 0, go to the initial window then  */
2995 		goto use_initial_window;
2996 	}
2997 	if (bw < 1)
2998 		/* Probably should panic */
2999 		bw = 1;
3000 	if (bw < min_bw)
3001 		bw = min_bw;
3002 	return (bw);
3003 }
3004 
3005 static inline uint64_t
3006 bbr_get_bw(struct tcp_bbr *bbr)
3007 {
3008 	uint64_t bw;
3009 
3010 	bw = __bbr_get_bw(bbr);
3011 	return (bw);
3012 }
3013 
3014 static inline void
3015 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3016 {
3017 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3018 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3019 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3020 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3021 }
3022 
3023 static inline void
3024 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3025 {
3026 	bbr->rc_lt_is_sampling = 0;
3027 	bbr->rc_lt_use_bw = 0;
3028 	bbr->r_ctl.rc_lt_bw = 0;
3029 	bbr_reset_lt_bw_interval(bbr, cts);
3030 }
3031 
3032 static inline void
3033 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3034 {
3035 	uint64_t diff;
3036 
3037 	/* Do we have a previous sample? */
3038 	if (bbr->r_ctl.rc_lt_bw) {
3039 		/* Get the diff in bytes per second */
3040 		if (bbr->r_ctl.rc_lt_bw > bw)
3041 			diff = bbr->r_ctl.rc_lt_bw - bw;
3042 		else
3043 			diff = bw - bbr->r_ctl.rc_lt_bw;
3044 		if ((diff <= bbr_lt_bw_diff) ||
3045 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3046 			/* Consider us policed */
3047 			uint32_t saved_bw;
3048 
3049 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3050 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3051 			bbr->rc_lt_use_bw = 1;
3052 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3053 			/*
3054 			 * Use pkt based epoch for measuring length of
3055 			 * policer up
3056 			 */
3057 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3058 			/*
3059 			 * reason 4 is we need to start consider being
3060 			 * policed
3061 			 */
3062 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3063 			return;
3064 		}
3065 	}
3066 	bbr->r_ctl.rc_lt_bw = bw;
3067 	bbr_reset_lt_bw_interval(bbr, cts);
3068 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3069 }
3070 
3071 static void
3072 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3073 {
3074 	uint32_t ran, deduct;
3075 
3076 	ran = arc4random_uniform(bbr_rand_ot);
3077 	if (ran) {
3078 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3079 		bbr->r_ctl.rc_level_state_extra -= deduct;
3080 	}
3081 }
3082 /*
3083  * Return randomly the starting state
3084  * to use in probebw.
3085  */
3086 static uint8_t
3087 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3088 {
3089 	uint32_t ran;
3090 	uint8_t ret_val;
3091 
3092 	/* Initialize the offset to 0 */
3093 	bbr->r_ctl.rc_exta_time_gd = 0;
3094 	bbr->rc_hit_state_1 = 0;
3095 	bbr->r_ctl.rc_level_state_extra = 0;
3096 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3097 	/*
3098 	 * The math works funny here :) the return value is used to set the
3099 	 * substate and then the state change is called which increments by
3100 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3101 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3102 	 * we return 1 - 7, so we dont return 0 and end up starting in
3103 	 * state 1 (DRAIN).
3104 	 */
3105 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3106 	/* Set an epoch */
3107 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3108 		bbr_set_epoch(bbr, cts, __LINE__);
3109 
3110 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3111 	return (ret_val);
3112 }
3113 
3114 static void
3115 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3116 {
3117 	uint32_t diff, d_time;
3118 	uint64_t del_time, bw, lost, delivered;
3119 
3120 	if (bbr->r_use_policer == 0)
3121 		return;
3122 	if (bbr->rc_lt_use_bw) {
3123 		/* We are using lt bw do we stop yet? */
3124 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3125 		if (diff > bbr_lt_bw_max_rtts) {
3126 			/* Reset it all */
3127 reset_all:
3128 			bbr_reset_lt_bw_sampling(bbr, cts);
3129 			if (bbr->rc_filled_pipe) {
3130 				bbr_set_epoch(bbr, cts, __LINE__);
3131 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3132 				bbr_substate_change(bbr, cts, __LINE__, 0);
3133 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3134 				bbr_log_type_statechange(bbr, cts, __LINE__);
3135 			} else {
3136 				/*
3137 				 * This should not happen really
3138 				 * unless we remove the startup/drain
3139 				 * restrictions above.
3140 				 */
3141 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3142 				bbr_set_epoch(bbr, cts, __LINE__);
3143 				bbr->r_ctl.rc_bbr_state_time = cts;
3144 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3145 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3146 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3147 				bbr_set_state_target(bbr, __LINE__);
3148 				bbr_log_type_statechange(bbr, cts, __LINE__);
3149 			}
3150 			/* reason 0 is to stop using lt-bw */
3151 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3152 			return;
3153 		}
3154 		if (bbr_lt_intvl_fp == 0) {
3155 			/* Not doing false-positive detection */
3156 			return;
3157 		}
3158 		/* False positive detection */
3159 		if (diff == bbr_lt_intvl_fp) {
3160 			/* At bbr_lt_intvl_fp we record the lost */
3161 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3162 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3163 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3164 			/* Now is our loss rate still high? */
3165 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3166 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3167 			if ((delivered == 0) ||
3168 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3169 				/* No still below our threshold */
3170 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3171 			} else {
3172 				/* Yikes its still high, it must be a false positive */
3173 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3174 				goto reset_all;
3175 			}
3176 		}
3177 		return;
3178 	}
3179 	/*
3180 	 * Wait for the first loss before sampling, to let the policer
3181 	 * exhaust its tokens and estimate the steady-state rate allowed by
3182 	 * the policer. Starting samples earlier includes bursts that
3183 	 * over-estimate the bw.
3184 	 */
3185 	if (bbr->rc_lt_is_sampling == 0) {
3186 		/* reason 1 is to begin doing the sampling  */
3187 		if (loss_detected == 0)
3188 			return;
3189 		bbr_reset_lt_bw_interval(bbr, cts);
3190 		bbr->rc_lt_is_sampling = 1;
3191 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3192 		return;
3193 	}
3194 	/* Now how long were we delivering long term last> */
3195 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3196 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3197 	else
3198 		d_time = 0;
3199 
3200 	/* To avoid underestimates, reset sampling if we run out of data. */
3201 	if (bbr->r_ctl.r_app_limited_until) {
3202 		/* Can not measure in app-limited state */
3203 		bbr_reset_lt_bw_sampling(bbr, cts);
3204 		/* reason 2 is to reset sampling due to app limits  */
3205 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3206 		return;
3207 	}
3208 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3209 	if (diff < bbr_lt_intvl_min_rtts) {
3210 		/*
3211 		 * need more samples (we don't
3212 		 * start on a round like linux so
3213 		 * we need 1 more).
3214 		 */
3215 		/* 6 is not_enough time or no-loss */
3216 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3217 		return;
3218 	}
3219 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3220 		/*
3221 		 * For now if we wait too long, reset all sampling. We need
3222 		 * to do some research here, its possible that we should
3223 		 * base this on how much loss as occurred.. something like
3224 		 * if its under 10% (or some thresh) reset all otherwise
3225 		 * don't.  Thats for phase II I guess.
3226 		 */
3227 		bbr_reset_lt_bw_sampling(bbr, cts);
3228  		/* reason 3 is to reset sampling due too long of sampling */
3229 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3230 		return;
3231 	}
3232 	/*
3233 	 * End sampling interval when a packet is lost, so we estimate the
3234 	 * policer tokens were exhausted. Stopping the sampling before the
3235 	 * tokens are exhausted under-estimates the policed rate.
3236 	 */
3237 	if (loss_detected == 0) {
3238 		/* 6 is not_enough time or no-loss */
3239 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3240 		return;
3241 	}
3242 	/* Calculate packets lost and delivered in sampling interval. */
3243 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3244 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3245 	if ((delivered == 0) ||
3246 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3247 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3248 		return;
3249 	}
3250 	if (d_time < 1000) {
3251 		/* Not enough time. wait */
3252 		/* 6 is not_enough time or no-loss */
3253 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3254 		return;
3255 	}
3256 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3257 		/* Too long */
3258 		bbr_reset_lt_bw_sampling(bbr, cts);
3259  		/* reason 3 is to reset sampling due too long of sampling */
3260 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3261 		return;
3262 	}
3263 	del_time = d_time;
3264 	bw = delivered;
3265 	bw *= (uint64_t)USECS_IN_SECOND;
3266 	bw /= del_time;
3267 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3268 }
3269 
3270 /*
3271  * Allocate a sendmap from our zone.
3272  */
3273 static struct bbr_sendmap *
3274 bbr_alloc(struct tcp_bbr *bbr)
3275 {
3276 	struct bbr_sendmap *rsm;
3277 
3278 	BBR_STAT_INC(bbr_to_alloc);
3279 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3280 	if (rsm) {
3281 		bbr->r_ctl.rc_num_maps_alloced++;
3282 		return (rsm);
3283 	}
3284 	if (bbr->r_ctl.rc_free_cnt) {
3285 		BBR_STAT_INC(bbr_to_alloc_emerg);
3286 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3287 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3288 		bbr->r_ctl.rc_free_cnt--;
3289 		return (rsm);
3290 	}
3291 	BBR_STAT_INC(bbr_to_alloc_failed);
3292 	return (NULL);
3293 }
3294 
3295 static struct bbr_sendmap *
3296 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3297 {
3298 	if ((V_tcp_map_entries_limit > 0) &&
3299 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3300 		BBR_STAT_INC(bbr_alloc_limited);
3301 		if (!bbr->alloc_limit_reported) {
3302 			bbr->alloc_limit_reported = 1;
3303 			BBR_STAT_INC(bbr_alloc_limited_conns);
3304 		}
3305 		return (NULL);
3306 	}
3307 	return (bbr_alloc(bbr));
3308 }
3309 
3310 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3311 static struct bbr_sendmap *
3312 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3313 {
3314 	struct bbr_sendmap *rsm;
3315 
3316 	if (limit_type) {
3317 		/* currently there is only one limit type */
3318 		if (V_tcp_map_split_limit > 0 &&
3319 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3320 			BBR_STAT_INC(bbr_split_limited);
3321 			if (!bbr->alloc_limit_reported) {
3322 				bbr->alloc_limit_reported = 1;
3323 				BBR_STAT_INC(bbr_alloc_limited_conns);
3324 			}
3325 			return (NULL);
3326 		}
3327 	}
3328 
3329 	/* allocate and mark in the limit type, if set */
3330 	rsm = bbr_alloc(bbr);
3331 	if (rsm != NULL && limit_type) {
3332 		rsm->r_limit_type = limit_type;
3333 		bbr->r_ctl.rc_num_split_allocs++;
3334 	}
3335 	return (rsm);
3336 }
3337 
3338 static void
3339 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3340 {
3341 	if (rsm->r_limit_type) {
3342 		/* currently there is only one limit type */
3343 		bbr->r_ctl.rc_num_split_allocs--;
3344 	}
3345 	if (rsm->r_is_smallmap)
3346 		bbr->r_ctl.rc_num_small_maps_alloced--;
3347 	if (bbr->r_ctl.rc_tlp_send == rsm)
3348 		bbr->r_ctl.rc_tlp_send = NULL;
3349 	if (bbr->r_ctl.rc_resend == rsm) {
3350 		bbr->r_ctl.rc_resend = NULL;
3351 	}
3352 	if (bbr->r_ctl.rc_next == rsm)
3353 		bbr->r_ctl.rc_next = NULL;
3354 	if (bbr->r_ctl.rc_sacklast == rsm)
3355 		bbr->r_ctl.rc_sacklast = NULL;
3356 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3357 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3358 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3359 		rsm->r_limit_type = 0;
3360 		bbr->r_ctl.rc_free_cnt++;
3361 		return;
3362 	}
3363 	bbr->r_ctl.rc_num_maps_alloced--;
3364 	uma_zfree(bbr_zone, rsm);
3365 }
3366 
3367 /*
3368  * Returns the BDP.
3369  */
3370 static uint64_t
3371 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3372 	/*
3373 	 * Calculate the bytes in flight needed given the bw (in bytes per
3374 	 * second) and the specifyed rtt in useconds. We need to put out the
3375 	 * returned value per RTT to match that rate. Gain will normally
3376 	 * raise it up from there.
3377 	 *
3378 	 * This should not overflow as long as the bandwidth is below 1
3379 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3380 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3381 	 */
3382 	uint64_t usec_per_sec;
3383 
3384 	usec_per_sec = USECS_IN_SECOND;
3385 	return ((rtt * bw) / usec_per_sec);
3386 }
3387 
3388 /*
3389  * Return the initial cwnd.
3390  */
3391 static uint32_t
3392 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3393 {
3394 	uint32_t i_cwnd;
3395 
3396 	if (bbr->rc_init_win) {
3397 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3398 	} else if (V_tcp_initcwnd_segments)
3399 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3400 		    max(2 * tp->t_maxseg, 14600));
3401 	else if (V_tcp_do_rfc3390)
3402 		i_cwnd = min(4 * tp->t_maxseg,
3403 		    max(2 * tp->t_maxseg, 4380));
3404 	else {
3405 		/* Per RFC5681 Section 3.1 */
3406 		if (tp->t_maxseg > 2190)
3407 			i_cwnd = 2 * tp->t_maxseg;
3408 		else if (tp->t_maxseg > 1095)
3409 			i_cwnd = 3 * tp->t_maxseg;
3410 		else
3411 			i_cwnd = 4 * tp->t_maxseg;
3412 	}
3413 	return (i_cwnd);
3414 }
3415 
3416 /*
3417  * Given a specified gain, return the target
3418  * cwnd based on that gain.
3419  */
3420 static uint32_t
3421 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3422 {
3423 	uint64_t bdp, rtt;
3424 	uint32_t cwnd;
3425 
3426 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3427 	    (bbr_get_full_bw(bbr) == 0)) {
3428 		/* No measurements yet */
3429 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3430 	}
3431 	/*
3432 	 * Get bytes per RTT needed (rttProp is normally in
3433 	 * bbr_cwndtarget_rtt_touse)
3434 	 */
3435 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3436 	/* Get the bdp from the two values */
3437 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3438 	/* Now apply the gain */
3439 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3440 
3441 	return (cwnd);
3442 }
3443 
3444 static uint32_t
3445 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3446 {
3447 	uint32_t cwnd, mss;
3448 
3449 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3450 	/* Get the base cwnd with gain rounded to a mss */
3451 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3452 	/*
3453 	 * Add in N (2 default since we do not have a
3454 	 * fq layer to trap packets in) quanta's per the I-D
3455 	 * section 4.2.3.2 quanta adjust.
3456 	 */
3457 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3458 	if (bbr->rc_use_google) {
3459 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3460 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3461 			/*
3462 			 * The linux implementation adds
3463 			 * an extra 2 x mss in gain cycle which
3464 			 * is documented no-where except in the code.
3465 			 * so we add more for Neal undocumented feature
3466 			 */
3467 			cwnd += 2 * mss;
3468 		}
3469  		if ((cwnd / mss) & 0x1) {
3470 			/* Round up for odd num mss */
3471 			cwnd += mss;
3472 		}
3473 	}
3474 	/* Are we below the min cwnd? */
3475 	if (cwnd < get_min_cwnd(bbr))
3476 		return (get_min_cwnd(bbr));
3477 	return (cwnd);
3478 }
3479 
3480 static uint16_t
3481 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3482 {
3483 	if (gain < 1)
3484 		gain = 1;
3485 	return (gain);
3486 }
3487 
3488 static uint32_t
3489 bbr_get_header_oh(struct tcp_bbr *bbr)
3490 {
3491 	int seg_oh;
3492 
3493 	seg_oh = 0;
3494 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3495 		/* Do we include TCP overhead? */
3496 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3497 	}
3498 	if (bbr->r_ctl.rc_inc_ip_oh) {
3499 		/* Do we include IP overhead? */
3500 #ifdef INET6
3501 		if (bbr->r_is_v6) {
3502 			seg_oh += sizeof(struct ip6_hdr);
3503 		} else
3504 #endif
3505 		{
3506 
3507 #ifdef INET
3508 			seg_oh += sizeof(struct ip);
3509 #endif
3510 		}
3511 	}
3512 	if (bbr->r_ctl.rc_inc_enet_oh) {
3513 		/* Do we include the ethernet overhead?  */
3514 		seg_oh += sizeof(struct ether_header);
3515 	}
3516 	return(seg_oh);
3517 }
3518 
3519 static uint32_t
3520 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3521 {
3522 	uint64_t divor, res, tim;
3523 
3524 	if (useconds_time == 0)
3525 		return (0);
3526 	gain = bbr_gain_adjust(bbr, gain);
3527 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3528 	tim = useconds_time;
3529 	res = (tim * bw * gain) / divor;
3530 	if (res == 0)
3531 		res = 1;
3532 	return ((uint32_t)res);
3533 }
3534 
3535 /*
3536  * Given a gain and a length return the delay in useconds that
3537  * should be used to evenly space out packets
3538  * on the connection (based on the gain factor).
3539  */
3540 static uint32_t
3541 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3542 {
3543 	uint64_t bw, lentim, res;
3544 	uint32_t usecs, srtt, over = 0;
3545 	uint32_t seg_oh, num_segs, maxseg;
3546 
3547 	if (len == 0)
3548 		return (0);
3549 
3550 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3551 	num_segs = (len + maxseg - 1) / maxseg;
3552 	if (bbr->rc_use_google == 0) {
3553 		seg_oh = bbr_get_header_oh(bbr);
3554 		len += (num_segs * seg_oh);
3555 	}
3556 	gain = bbr_gain_adjust(bbr, gain);
3557 	bw = bbr_get_bw(bbr);
3558 	if (bbr->rc_use_google) {
3559 		uint64_t cbw;
3560 
3561 		/*
3562 		 * Reduce the b/w by the google discount
3563 		 * factor 10 = 1%.
3564 		 */
3565 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3566 		cbw /= (uint64_t)1000;
3567 		/* We don't apply a discount if it results in 0 */
3568 		if (cbw > 0)
3569 			bw = cbw;
3570 	}
3571 	lentim = ((uint64_t)len *
3572 		  (uint64_t)USECS_IN_SECOND *
3573 		  (uint64_t)BBR_UNIT);
3574 	res = lentim / ((uint64_t)gain * bw);
3575 	if (res == 0)
3576 		res = 1;
3577 	usecs = (uint32_t)res;
3578 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3579 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3580 	    (bbr->rc_use_google == 0) &&
3581 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3582 		/*
3583 		 * We cannot let the delay be more than 1/2 the srtt time.
3584 		 * Otherwise we cannot pace out or send properly.
3585 		 */
3586 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3587 		BBR_STAT_INC(bbr_hpts_min_time);
3588 	}
3589 	if (!nolog)
3590 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3591 	return (usecs);
3592 }
3593 
3594 static void
3595 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3596 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3597 {
3598 	uint64_t bw;
3599 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3600 	int32_t meth;
3601 
3602 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3603 
3604 #ifdef STATS
3605 	if ((tp->t_flags & TF_GPUTINPROG) &&
3606 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3607 		/*
3608 		 * Strech acks and compressed acks will cause this to
3609 		 * oscillate but we are doing it the same way as the main
3610 		 * stack so it will be compariable (though possibly not
3611 		 * ideal).
3612 		 */
3613 		int32_t cgput;
3614 		int64_t gput, time_stamp;
3615 
3616 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3617 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3618 		cgput = gput / time_stamp;
3619 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3620 					 cgput);
3621 		if (tp->t_stats_gput_prev > 0)
3622 			stats_voi_update_abs_s32(tp->t_stats,
3623 						 VOI_TCP_GPUT_ND,
3624 						 ((gput - tp->t_stats_gput_prev) * 100) /
3625 						 tp->t_stats_gput_prev);
3626 		tp->t_flags &= ~TF_GPUTINPROG;
3627 		tp->t_stats_gput_prev = cgput;
3628 	}
3629 #endif
3630 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3631 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3632 		/* We don't change anything in probe-rtt */
3633 		return;
3634 	}
3635 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3636 	saved_bytes = bytes_this_ack;
3637 	bytes_this_ack += sack_changed;
3638 	if (bytes_this_ack > prev_acked) {
3639 		bytes_this_ack -= prev_acked;
3640 		/*
3641 		 * A byte ack'd gives us a full mss
3642 		 * to be like linux i.e. they count packets.
3643 		 */
3644 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3645 			bytes_this_ack = maxseg;
3646 	} else {
3647 		/* Unlikely */
3648 		bytes_this_ack = 0;
3649 	}
3650 	cwnd = tp->snd_cwnd;
3651 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3652 	if (bw)
3653 		target_cwnd = bbr_get_target_cwnd(bbr,
3654 						  bw,
3655 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3656 	else
3657 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3658 	if (IN_RECOVERY(tp->t_flags) &&
3659 	    (bbr->bbr_prev_in_rec == 0)) {
3660 		/*
3661 		 * We are entering recovery and
3662 		 * thus packet conservation.
3663 		 */
3664 		bbr->pkt_conservation = 1;
3665 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3666 		cwnd = ctf_flight_size(tp,
3667 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3668 			bytes_this_ack;
3669 	}
3670 	if (IN_RECOVERY(tp->t_flags)) {
3671 		uint32_t flight;
3672 
3673 		bbr->bbr_prev_in_rec = 1;
3674 		if (cwnd > losses) {
3675 			cwnd -= losses;
3676 			if (cwnd < maxseg)
3677 				cwnd = maxseg;
3678 		} else
3679 			cwnd = maxseg;
3680 		flight = ctf_flight_size(tp,
3681 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3682 		bbr_log_type_cwndupd(bbr, flight, 0,
3683 				     losses, 10, 0, 0, line);
3684 		if (bbr->pkt_conservation) {
3685 			uint32_t time_in;
3686 
3687 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3688 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3689 			else
3690 				time_in = 0;
3691 
3692 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3693 				/* Clear packet conservation after an rttProp */
3694 				bbr->pkt_conservation = 0;
3695 			} else {
3696 				if ((flight + bytes_this_ack) > cwnd)
3697 					cwnd = flight + bytes_this_ack;
3698 				if (cwnd < get_min_cwnd(bbr))
3699 					cwnd = get_min_cwnd(bbr);
3700 				tp->snd_cwnd = cwnd;
3701 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3702 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3703 				return;
3704 			}
3705 		}
3706 	} else
3707 		bbr->bbr_prev_in_rec = 0;
3708 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3709 		bbr->r_ctl.restrict_growth--;
3710 		if (bytes_this_ack > maxseg)
3711 			bytes_this_ack = maxseg;
3712 	}
3713 	if (bbr->rc_filled_pipe) {
3714 		/*
3715 		 * Here we have exited startup and filled the pipe. We will
3716 		 * thus allow the cwnd to shrink to the target. We hit here
3717 		 * mostly.
3718 		 */
3719 		uint32_t s_cwnd;
3720 
3721 		meth = 2;
3722 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3723 		if (s_cwnd > cwnd)
3724 			cwnd = s_cwnd;
3725 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3726 			cwnd = s_cwnd;
3727 	} else {
3728 		/*
3729 		 * Here we are still in startup, we increase cwnd by what
3730 		 * has been acked.
3731 		 */
3732 		if ((cwnd < target_cwnd) ||
3733 		    (bbr->rc_past_init_win == 0)) {
3734 			meth = 3;
3735 			cwnd += bytes_this_ack;
3736 		} else {
3737 			/*
3738 			 * Method 4 means we are at target so no gain in
3739 			 * startup and past the initial window.
3740 			 */
3741 			meth = 4;
3742 		}
3743 	}
3744 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3745 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3746 }
3747 
3748 static void
3749 tcp_bbr_partialack(struct tcpcb *tp)
3750 {
3751 	struct tcp_bbr *bbr;
3752 
3753 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3754 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3755 	if (ctf_flight_size(tp,
3756 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3757 	    tp->snd_cwnd) {
3758 		bbr->r_wanted_output = 1;
3759 	}
3760 }
3761 
3762 static void
3763 bbr_post_recovery(struct tcpcb *tp)
3764 {
3765 	struct tcp_bbr *bbr;
3766 	uint32_t  flight;
3767 
3768 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3769 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3770 	/*
3771 	 * Here we just exit recovery.
3772 	 */
3773 	EXIT_RECOVERY(tp->t_flags);
3774 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3775 	bbr->r_recovery_bw = 0;
3776 	tp->snd_recover = tp->snd_una;
3777 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3778 	bbr->pkt_conservation = 0;
3779 	if (bbr->rc_use_google == 0) {
3780 		/*
3781 		 * For non-google mode lets
3782 		 * go ahead and make sure we clear
3783 		 * the recovery state so if we
3784 		 * bounce back in to recovery we
3785 		 * will do PC.
3786 		 */
3787 		bbr->bbr_prev_in_rec = 0;
3788 	}
3789 	bbr_log_type_exit_rec(bbr);
3790 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3791 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3792 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3793 	} else {
3794 		/* For probe-rtt case lets fix up its saved_cwnd */
3795 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3796 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3797 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3798 		}
3799 	}
3800 	flight = ctf_flight_size(tp,
3801 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3802 	if ((bbr->rc_use_google == 0) &&
3803 	    bbr_do_red) {
3804 		uint64_t val, lr2use;
3805 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3806 		uint32_t *cwnd_p;
3807 
3808 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3809 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3810 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3811 			ratio = (uint32_t)val;
3812 		} else
3813 			ratio = 1000;
3814 
3815 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3816 				     bbr->r_ctl.recovery_lr, 21,
3817 				     ratio,
3818 				     bbr->r_ctl.rc_red_cwnd_pe,
3819 				     __LINE__);
3820 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3821 			goto done;
3822 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3823 		     bbr_prtt_slam_cwnd) ||
3824 		    (bbr_sub_drain_slam_cwnd &&
3825 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3826 		     bbr->rc_hit_state_1 &&
3827 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3828 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3829 		     bbr_slam_cwnd_in_main_drain)) {
3830 			/*
3831 			 * Here we must poke at the saved cwnd
3832 			 * as well as the cwnd.
3833 			 */
3834 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3835 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3836 		} else {
3837  			cwnd = tp->snd_cwnd;
3838 			cwnd_p = &tp->snd_cwnd;
3839 		}
3840 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3841 		/* Add the overall lr with the recovery lr */
3842 		if (bbr->r_ctl.rc_lost == 0)
3843 			lr2use = 0;
3844 		else if (bbr->r_ctl.rc_delivered == 0)
3845 			lr2use = 1000;
3846 		else {
3847 			lr2use = bbr->r_ctl.rc_lost * 1000;
3848 			lr2use /= bbr->r_ctl.rc_delivered;
3849 		}
3850 		lr2use += bbr->r_ctl.recovery_lr;
3851 		acks_inflight = (flight / (maxseg * 2));
3852 		if (bbr_red_scale) {
3853 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3854 			lr2use /= bbr_red_scale;
3855 			if ((bbr_red_growth_restrict) &&
3856 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3857 			    bbr->r_ctl.restrict_growth += acks_inflight;
3858 		}
3859 		if (lr2use) {
3860 			val = (uint64_t)cwnd * lr2use;
3861 			val /= 1000;
3862 			if (cwnd > val)
3863 				newcwnd = roundup((cwnd - val), maxseg);
3864 			else
3865 				newcwnd = maxseg;
3866 		} else {
3867 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3868 			val /= (uint64_t)bbr_red_div;
3869 			newcwnd = roundup((uint32_t)val, maxseg);
3870 		}
3871 		/* with standard delayed acks how many acks can I expect? */
3872 		if (bbr_drop_limit == 0) {
3873 			/*
3874 			 * Anticpate how much we will
3875 			 * raise the cwnd based on the acks.
3876 			 */
3877 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3878 				/* We do enforce the min (with the acks) */
3879 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3880 			}
3881 		} else {
3882 			/*
3883 			 * A strict drop limit of N is inplace
3884 			 */
3885 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3886 				newcwnd = bbr_drop_limit * maxseg;
3887 			}
3888 		}
3889 		/* For the next N acks do we restrict the growth */
3890 		*cwnd_p = newcwnd;
3891 		if (tp->snd_cwnd > newcwnd)
3892 			tp->snd_cwnd = newcwnd;
3893 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3894 				     (uint32_t)lr2use,
3895 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3896 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3897 	}
3898 done:
3899 	bbr->r_ctl.recovery_lr = 0;
3900 	if (flight <= tp->snd_cwnd) {
3901 		bbr->r_wanted_output = 1;
3902 	}
3903 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3904 }
3905 
3906 static void
3907 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3908 {
3909 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3910 	/* Limit the drop in b/w to 1/2 our current filter. */
3911 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3912 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3913 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3914 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3915 	tcp_bbr_tso_size_check(bbr, cts);
3916 }
3917 
3918 static void
3919 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3920 {
3921 	struct tcp_bbr *bbr;
3922 
3923 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3924 #ifdef STATS
3925 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3926 #endif
3927 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3928 	switch (type) {
3929 	case CC_NDUPACK:
3930 		if (!IN_RECOVERY(tp->t_flags)) {
3931 			tp->snd_recover = tp->snd_max;
3932 			/* Start a new epoch */
3933 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3934 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3935 				/*
3936 				 * Move forward the lt epoch
3937 				 * so it won't count the truncated
3938 				 * epoch.
3939 				 */
3940 				bbr->r_ctl.rc_lt_epoch++;
3941 			}
3942 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3943 				/*
3944 				 * Just like the policer detection code
3945 				 * if we are in startup we must push
3946 				 * forward the last startup epoch
3947 				 * to hide the truncated PE.
3948 				 */
3949 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3950 			}
3951 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3952 			ENTER_RECOVERY(tp->t_flags);
3953 			bbr->rc_tlp_rtx_out = 0;
3954 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3955 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3956 			if (tcp_in_hpts(bbr->rc_tp) &&
3957 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3958 				/*
3959 				 * When we enter recovery, we need to restart
3960 				 * any timers. This may mean we gain an agg
3961 				 * early, which will be made up for at the last
3962 				 * rxt out.
3963 				 */
3964 				bbr->rc_timer_first = 1;
3965 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3966 			}
3967 			/*
3968 			 * Calculate a new cwnd based on to the current
3969 			 * delivery rate with no gain. We get the bdp
3970 			 * without gaining it up like we normally would and
3971 			 * we use the last cur_del_rate.
3972 			 */
3973 			if ((bbr->rc_use_google == 0) &&
3974 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3975 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3976 				tp->snd_cwnd = ctf_flight_size(tp,
3977 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3978 					(tp->t_maxseg - bbr->rc_last_options);
3979 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3980 					/* We always gate to min cwnd */
3981 					tp->snd_cwnd = get_min_cwnd(bbr);
3982 				}
3983 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3984 			}
3985 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3986 		}
3987 		break;
3988 	case CC_RTO_ERR:
3989 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
3990 		/* RTO was unnecessary, so reset everything. */
3991 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
3992 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3993 			tp->snd_cwnd = tp->snd_cwnd_prev;
3994 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
3995 			tp->snd_recover = tp->snd_recover_prev;
3996 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3997 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
3998 		}
3999 		tp->t_badrxtwin = 0;
4000 		break;
4001 	}
4002 }
4003 
4004 /*
4005  * Indicate whether this ack should be delayed.  We can delay the ack if
4006  * following conditions are met:
4007  *	- There is no delayed ack timer in progress.
4008  *	- Our last ack wasn't a 0-sized window. We never want to delay
4009  *	  the ack that opens up a 0-sized window.
4010  *	- LRO wasn't used for this segment. We make sure by checking that the
4011  *	  segment size is not larger than the MSS.
4012  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4013  *	  connection.
4014  *	- The data being acked is less than a full segment (a stretch ack
4015  *        of more than a segment we should ack.
4016  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4017  */
4018 #define DELAY_ACK(tp, bbr, nsegs)				\
4019 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4020 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4021 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4022 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4023 
4024 /*
4025  * Return the lowest RSM in the map of
4026  * packets still in flight that is not acked.
4027  * This should normally find on the first one
4028  * since we remove packets from the send
4029  * map after they are marked ACKED.
4030  */
4031 static struct bbr_sendmap *
4032 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4033 {
4034 	struct bbr_sendmap *rsm;
4035 
4036 	/*
4037 	 * Walk the time-order transmitted list looking for an rsm that is
4038 	 * not acked. This will be the one that was sent the longest time
4039 	 * ago that is still outstanding.
4040 	 */
4041 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4042 		if (rsm->r_flags & BBR_ACKED) {
4043 			continue;
4044 		}
4045 		goto finish;
4046 	}
4047 finish:
4048 	return (rsm);
4049 }
4050 
4051 static struct bbr_sendmap *
4052 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4053 {
4054 	struct bbr_sendmap *prsm;
4055 
4056 	/*
4057 	 * Walk the sequence order list backward until we hit and arrive at
4058 	 * the highest seq not acked. In theory when this is called it
4059 	 * should be the last segment (which it was not).
4060 	 */
4061 	prsm = rsm;
4062 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4063 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4064 			continue;
4065 		}
4066 		return (prsm);
4067 	}
4068 	return (NULL);
4069 }
4070 
4071 /*
4072  * Returns to the caller the number of microseconds that
4073  * the packet can be outstanding before we think we
4074  * should have had an ack returned.
4075  */
4076 static uint32_t
4077 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4078 {
4079 	/*
4080 	 * lro is the flag we use to determine if we have seen reordering.
4081 	 * If it gets set we have seen reordering. The reorder logic either
4082 	 * works in one of two ways:
4083 	 *
4084 	 * If reorder-fade is configured, then we track the last time we saw
4085 	 * re-ordering occur. If we reach the point where enough time as
4086 	 * passed we no longer consider reordering has occuring.
4087 	 *
4088 	 * Or if reorder-face is 0, then once we see reordering we consider
4089 	 * the connection to alway be subject to reordering and just set lro
4090 	 * to 1.
4091 	 *
4092 	 * In the end if lro is non-zero we add the extra time for
4093 	 * reordering in.
4094 	 */
4095 	int32_t lro;
4096 	uint32_t thresh, t_rxtcur;
4097 
4098 	if (srtt == 0)
4099 		srtt = 1;
4100 	if (bbr->r_ctl.rc_reorder_ts) {
4101 		if (bbr->r_ctl.rc_reorder_fade) {
4102 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4103 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4104 				if (lro == 0) {
4105 					/*
4106 					 * No time as passed since the last
4107 					 * reorder, mark it as reordering.
4108 					 */
4109 					lro = 1;
4110 				}
4111 			} else {
4112 				/* Negative time? */
4113 				lro = 0;
4114 			}
4115 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4116 				/* Turn off reordering seen too */
4117 				bbr->r_ctl.rc_reorder_ts = 0;
4118 				lro = 0;
4119 			}
4120 		} else {
4121 			/* Reodering does not fade */
4122 			lro = 1;
4123 		}
4124 	} else {
4125 		lro = 0;
4126 	}
4127 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4128 	if (lro) {
4129 		/* It must be set, if not you get 1/4 rtt */
4130 		if (bbr->r_ctl.rc_reorder_shift)
4131 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4132 		else
4133 			thresh += (srtt >> 2);
4134 	} else {
4135 		thresh += 1000;
4136 	}
4137 	/* We don't let the rack timeout be above a RTO */
4138 	if ((bbr->rc_tp)->t_srtt == 0)
4139 		t_rxtcur = BBR_INITIAL_RTO;
4140 	else
4141 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4142 	if (thresh > t_rxtcur) {
4143 		thresh = t_rxtcur;
4144 	}
4145 	/* And we don't want it above the RTO max either */
4146 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4147 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4148 	}
4149 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4150 	return (thresh);
4151 }
4152 
4153 /*
4154  * Return to the caller the amount of time in mico-seconds
4155  * that should be used for the TLP timer from the last
4156  * send time of this packet.
4157  */
4158 static uint32_t
4159 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4160     struct bbr_sendmap *rsm, uint32_t srtt,
4161     uint32_t cts)
4162 {
4163 	uint32_t thresh, len, maxseg, t_rxtcur;
4164 	struct bbr_sendmap *prsm;
4165 
4166 	if (srtt == 0)
4167 		srtt = 1;
4168 	if (bbr->rc_tlp_threshold)
4169 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4170 	else
4171 		thresh = (srtt * 2);
4172 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4173 	/* Get the previous sent packet, if any  */
4174 	len = rsm->r_end - rsm->r_start;
4175 
4176 	/* 2.1 behavior */
4177 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4178 	if (prsm && (len <= maxseg)) {
4179 		/*
4180 		 * Two packets outstanding, thresh should be (2*srtt) +
4181 		 * possible inter-packet delay (if any).
4182 		 */
4183 		uint32_t inter_gap = 0;
4184 		int idx, nidx;
4185 
4186 		idx = rsm->r_rtr_cnt - 1;
4187 		nidx = prsm->r_rtr_cnt - 1;
4188 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4189 			/* Yes it was sent later (or at the same time) */
4190 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4191 		}
4192 		thresh += inter_gap;
4193 	} else if (len <= maxseg) {
4194 		/*
4195 		 * Possibly compensate for delayed-ack.
4196 		 */
4197 		uint32_t alt_thresh;
4198 
4199 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4200 		if (alt_thresh > thresh)
4201 			thresh = alt_thresh;
4202 	}
4203 	/* Not above the current  RTO */
4204 	if (tp->t_srtt == 0)
4205 		t_rxtcur = BBR_INITIAL_RTO;
4206 	else
4207 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4208 
4209 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4210 	/* Not above an RTO */
4211 	if (thresh > t_rxtcur) {
4212 		thresh = t_rxtcur;
4213 	}
4214 	/* Not above a RTO max */
4215 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4216 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4217 	}
4218 	/* And now apply the user TLP min */
4219 	if (thresh < bbr_tlp_min) {
4220 		thresh = bbr_tlp_min;
4221 	}
4222 	return (thresh);
4223 }
4224 
4225 /*
4226  * Return one of three RTTs to use (in microseconds).
4227  */
4228 static __inline uint32_t
4229 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4230 {
4231 	uint32_t f_rtt;
4232 	uint32_t srtt;
4233 
4234 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4235 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4236 		/* We have no rtt at all */
4237 		if (bbr->rc_tp->t_srtt == 0)
4238 			f_rtt = BBR_INITIAL_RTO;
4239 		else
4240 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4241 		/*
4242 		 * Since we don't know how good the rtt is apply a
4243 		 * delayed-ack min
4244 		 */
4245 		if (f_rtt < bbr_delayed_ack_time) {
4246 			f_rtt = bbr_delayed_ack_time;
4247 		}
4248 	}
4249 	/* Take the filter version or last measured pkt-rtt */
4250 	if (rtt_type == BBR_RTT_PROP) {
4251 		srtt = f_rtt;
4252 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4253 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4254 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4255 		} else {
4256 			/* No pkt rtt yet */
4257 			srtt = f_rtt;
4258 		}
4259 	} else if (rtt_type == BBR_RTT_RACK) {
4260 		srtt = bbr->r_ctl.rc_last_rtt;
4261 		/* We need to add in any internal delay for our timer */
4262 		if (bbr->rc_ack_was_delayed)
4263 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4264 	} else if (rtt_type == BBR_SRTT) {
4265 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4266 	} else {
4267 		/* TSNH */
4268 		srtt = f_rtt;
4269 #ifdef BBR_INVARIANTS
4270 		panic("Unknown rtt request type %d", rtt_type);
4271 #endif
4272 	}
4273 	return (srtt);
4274 }
4275 
4276 static int
4277 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4278 {
4279 	uint32_t thresh;
4280 
4281 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4282 				      cts, rsm);
4283 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4284 		/* It is lost (past time) */
4285 		return (1);
4286 	}
4287 	return (0);
4288 }
4289 
4290 /*
4291  * Return a sendmap if we need to retransmit something.
4292  */
4293 static struct bbr_sendmap *
4294 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4295 {
4296 	/*
4297 	 * Check to see that we don't need to fall into recovery. We will
4298 	 * need to do so if our oldest transmit is past the time we should
4299 	 * have had an ack.
4300 	 */
4301 
4302 	struct bbr_sendmap *rsm;
4303 	int32_t idx;
4304 
4305 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4306 		/* Nothing outstanding that we know of */
4307 		return (NULL);
4308 	}
4309 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4310 	if (rsm == NULL) {
4311 		/* Nothing in the transmit map */
4312 		return (NULL);
4313 	}
4314 	if (tp->t_flags & TF_SENTFIN) {
4315 		/* Fin restricted, don't find anything once a fin is sent */
4316 		return (NULL);
4317 	}
4318 	if (rsm->r_flags & BBR_ACKED) {
4319 		/*
4320 		 * Ok the first one is acked (this really should not happen
4321 		 * since we remove the from the tmap once they are acked)
4322 		 */
4323 		rsm = bbr_find_lowest_rsm(bbr);
4324 		if (rsm == NULL)
4325 			return (NULL);
4326 	}
4327 	idx = rsm->r_rtr_cnt - 1;
4328 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4329 		/* Send timestamp is the same or less? can't be ready */
4330 		return (NULL);
4331 	}
4332 	/* Get our RTT time */
4333 	if (bbr_is_lost(bbr, rsm, cts) &&
4334 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4335 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4336 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4337 			rsm->r_flags |= BBR_MARKED_LOST;
4338 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4339 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4340 		}
4341 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4342 #ifdef BBR_INVARIANTS
4343 		if ((rsm->r_end - rsm->r_start) == 0)
4344 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4345 #endif
4346 		return (rsm);
4347 	}
4348 	return (NULL);
4349 }
4350 
4351 /*
4352  * RACK Timer, here we simply do logging and house keeping.
4353  * the normal bbr_output_wtime() function will call the
4354  * appropriate thing to check if we need to do a RACK retransmit.
4355  * We return 1, saying don't proceed with bbr_output_wtime only
4356  * when all timers have been stopped (destroyed PCB?).
4357  */
4358 static int
4359 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4360 {
4361 	/*
4362 	 * This timer simply provides an internal trigger to send out data.
4363 	 * The check_recovery_mode call will see if there are needed
4364 	 * retransmissions, if so we will enter fast-recovery. The output
4365 	 * call may or may not do the same thing depending on sysctl
4366 	 * settings.
4367 	 */
4368 	uint32_t lost;
4369 
4370 	if (bbr->rc_all_timers_stopped) {
4371 		return (1);
4372 	}
4373 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4374 		/* Its not time yet */
4375 		return (0);
4376 	}
4377 	BBR_STAT_INC(bbr_to_tot);
4378 	lost = bbr->r_ctl.rc_lost;
4379 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4380 		bbr_set_state(tp, bbr, 0);
4381 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4382 	if (bbr->r_ctl.rc_resend == NULL) {
4383 		/* Lets do the check here */
4384 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4385 	}
4386 	if (bbr_policer_call_from_rack_to)
4387 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4388 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4389 	return (0);
4390 }
4391 
4392 static __inline void
4393 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4394 {
4395 	int idx;
4396 
4397 	nrsm->r_start = start;
4398 	nrsm->r_end = rsm->r_end;
4399 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4400 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4401 	nrsm->r_flags = rsm->r_flags;
4402 	/* We don't transfer forward the SYN flag */
4403 	nrsm->r_flags &= ~BBR_HAS_SYN;
4404 	/* We move forward the FIN flag, not that this should happen */
4405 	rsm->r_flags &= ~BBR_HAS_FIN;
4406 	nrsm->r_dupack = rsm->r_dupack;
4407 	nrsm->r_rtr_bytes = 0;
4408 	nrsm->r_is_gain = rsm->r_is_gain;
4409 	nrsm->r_is_drain = rsm->r_is_drain;
4410 	nrsm->r_delivered = rsm->r_delivered;
4411 	nrsm->r_ts_valid = rsm->r_ts_valid;
4412 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4413 	nrsm->r_del_time = rsm->r_del_time;
4414 	nrsm->r_app_limited = rsm->r_app_limited;
4415 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4416 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4417 	/* We split a piece the lower section looses any just_ret flag. */
4418 	nrsm->r_bbr_state = rsm->r_bbr_state;
4419 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4420 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4421 	}
4422 	rsm->r_end = nrsm->r_start;
4423 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4424 	idx /= 8;
4425 	/* Check if we got too small */
4426 	if ((rsm->r_is_smallmap == 0) &&
4427 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4428 		bbr->r_ctl.rc_num_small_maps_alloced++;
4429 		rsm->r_is_smallmap = 1;
4430 	}
4431 	/* Check the new one as well */
4432 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4433 		bbr->r_ctl.rc_num_small_maps_alloced++;
4434 		nrsm->r_is_smallmap = 1;
4435 	}
4436 }
4437 
4438 static int
4439 bbr_sack_mergable(struct bbr_sendmap *at,
4440 		  uint32_t start, uint32_t end)
4441 {
4442 	/*
4443 	 * Given a sack block defined by
4444 	 * start and end, and a current position
4445 	 * at. Return 1 if either side of at
4446 	 * would show that the block is mergable
4447 	 * to that side. A block to be mergable
4448 	 * must have overlap with the start/end
4449 	 * and be in the SACK'd state.
4450 	 */
4451 	struct bbr_sendmap *l_rsm;
4452 	struct bbr_sendmap *r_rsm;
4453 
4454 	/* first get the either side blocks */
4455 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4456 	r_rsm = TAILQ_NEXT(at, r_next);
4457 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4458 		/* Potentially mergeable */
4459 		if ((l_rsm->r_end == start) ||
4460 		    (SEQ_LT(start, l_rsm->r_end) &&
4461 		     SEQ_GT(end, l_rsm->r_end))) {
4462 			    /*
4463 			     * map blk   |------|
4464 			     * sack blk         |------|
4465 			     * <or>
4466 			     * map blk   |------|
4467 			     * sack blk      |------|
4468 			     */
4469 			    return (1);
4470 		    }
4471 	}
4472 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4473 		/* Potentially mergeable */
4474 		if ((r_rsm->r_start == end) ||
4475 		    (SEQ_LT(start, r_rsm->r_start) &&
4476 		     SEQ_GT(end, r_rsm->r_start))) {
4477 			/*
4478 			 * map blk          |---------|
4479 			 * sack blk    |----|
4480 			 * <or>
4481 			 * map blk          |---------|
4482 			 * sack blk    |-------|
4483 			 */
4484 			return (1);
4485 		}
4486 	}
4487 	return (0);
4488 }
4489 
4490 static struct bbr_sendmap *
4491 bbr_merge_rsm(struct tcp_bbr *bbr,
4492 	      struct bbr_sendmap *l_rsm,
4493 	      struct bbr_sendmap *r_rsm)
4494 {
4495 	/*
4496 	 * We are merging two ack'd RSM's,
4497 	 * the l_rsm is on the left (lower seq
4498 	 * values) and the r_rsm is on the right
4499 	 * (higher seq value). The simplest way
4500 	 * to merge these is to move the right
4501 	 * one into the left. I don't think there
4502 	 * is any reason we need to try to find
4503 	 * the oldest (or last oldest retransmitted).
4504 	 */
4505 	l_rsm->r_end = r_rsm->r_end;
4506 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4507 		l_rsm->r_dupack = r_rsm->r_dupack;
4508 	if (r_rsm->r_rtr_bytes)
4509 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4510 	if (r_rsm->r_in_tmap) {
4511 		/* This really should not happen */
4512 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4513 	}
4514 	if (r_rsm->r_app_limited)
4515 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4516 	/* Now the flags */
4517 	if (r_rsm->r_flags & BBR_HAS_FIN)
4518 		l_rsm->r_flags |= BBR_HAS_FIN;
4519 	if (r_rsm->r_flags & BBR_TLP)
4520 		l_rsm->r_flags |= BBR_TLP;
4521 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4522 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4523 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4524 		/* This really should not happen */
4525 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4526 	}
4527 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4528 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4529 		/* Transfer the split limit to the map we free */
4530 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4531 		l_rsm->r_limit_type = 0;
4532 	}
4533 	bbr_free(bbr, r_rsm);
4534 	return(l_rsm);
4535 }
4536 
4537 /*
4538  * TLP Timer, here we simply setup what segment we want to
4539  * have the TLP expire on, the normal bbr_output_wtime() will then
4540  * send it out.
4541  *
4542  * We return 1, saying don't proceed with bbr_output_wtime only
4543  * when all timers have been stopped (destroyed PCB?).
4544  */
4545 static int
4546 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4547 {
4548 	/*
4549 	 * Tail Loss Probe.
4550 	 */
4551 	struct bbr_sendmap *rsm = NULL;
4552 	struct socket *so;
4553 	uint32_t amm;
4554 	uint32_t out, avail;
4555 	uint32_t maxseg;
4556 	int collapsed_win = 0;
4557 
4558 	if (bbr->rc_all_timers_stopped) {
4559 		return (1);
4560 	}
4561 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4562 		/* Its not time yet */
4563 		return (0);
4564 	}
4565 	if (ctf_progress_timeout_check(tp, true)) {
4566 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4567 		return (-ETIMEDOUT);	/* tcp_drop() */
4568 	}
4569 	/* Did we somehow get into persists? */
4570 	if (bbr->rc_in_persist) {
4571 		return (0);
4572 	}
4573 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4574 		bbr_set_state(tp, bbr, 0);
4575 	BBR_STAT_INC(bbr_tlp_tot);
4576 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4577 	/*
4578 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4579 	 * need to figure out how to force a full MSS segment out.
4580 	 */
4581 	so = tptosocket(tp);
4582 	avail = sbavail(&so->so_snd);
4583 	out = ctf_outstanding(tp);
4584 	if (out > tp->snd_wnd) {
4585 		/* special case, we need a retransmission */
4586 		collapsed_win = 1;
4587 		goto need_retran;
4588 	}
4589 	if (avail > out) {
4590 		/* New data is available */
4591 		amm = avail - out;
4592 		if (amm > maxseg) {
4593 			amm = maxseg;
4594 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4595 			/* not enough to fill a MTU and no-delay is off */
4596 			goto need_retran;
4597 		}
4598 		/* Set the send-new override */
4599 		if ((out + amm) <= tp->snd_wnd) {
4600 			bbr->rc_tlp_new_data = 1;
4601 		} else {
4602 			goto need_retran;
4603 		}
4604 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4605 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4606 		bbr->r_ctl.rc_tlp_send = NULL;
4607 		/* cap any slots */
4608 		BBR_STAT_INC(bbr_tlp_newdata);
4609 		goto send;
4610 	}
4611 need_retran:
4612 	/*
4613 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4614 	 * optionally the first un-acked segment.
4615 	 */
4616 	if (collapsed_win == 0) {
4617 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4618 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4619 			rsm = bbr_find_high_nonack(bbr, rsm);
4620 		}
4621 		if (rsm == NULL) {
4622 			goto restore;
4623 		}
4624 	} else {
4625 		/*
4626 		 * We must find the last segment
4627 		 * that was acceptable by the client.
4628 		 */
4629 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4630 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4631 				/* Found one */
4632 				break;
4633 			}
4634 		}
4635 		if (rsm == NULL) {
4636 			/* None? if so send the first */
4637 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4638 			if (rsm == NULL)
4639 				goto restore;
4640 		}
4641 	}
4642 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4643 		/*
4644 		 * We need to split this the last segment in two.
4645 		 */
4646 		struct bbr_sendmap *nrsm;
4647 
4648 		nrsm = bbr_alloc_full_limit(bbr);
4649 		if (nrsm == NULL) {
4650 			/*
4651 			 * We can't get memory to split, we can either just
4652 			 * not split it. Or retransmit the whole piece, lets
4653 			 * do the large send (BTLP :-) ).
4654 			 */
4655 			goto go_for_it;
4656 		}
4657 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4658 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4659 		if (rsm->r_in_tmap) {
4660 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4661 			nrsm->r_in_tmap = 1;
4662 		}
4663 		rsm->r_flags &= (~BBR_HAS_FIN);
4664 		rsm = nrsm;
4665 	}
4666 go_for_it:
4667 	bbr->r_ctl.rc_tlp_send = rsm;
4668 	bbr->rc_tlp_rtx_out = 1;
4669 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4670 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4671 		tp->t_rxtshift++;
4672 	} else {
4673 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4674 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4675 	}
4676 send:
4677 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4678 		/*
4679 		 * Can't [re]/transmit a segment we have retransmitted the
4680 		 * max times. We need the retransmit timer to take over.
4681 		 */
4682 restore:
4683 		bbr->rc_tlp_new_data = 0;
4684 		bbr->r_ctl.rc_tlp_send = NULL;
4685 		if (rsm)
4686 			rsm->r_flags &= ~BBR_TLP;
4687 		BBR_STAT_INC(bbr_tlp_retran_fail);
4688 		return (0);
4689 	} else if (rsm) {
4690 		rsm->r_flags |= BBR_TLP;
4691 	}
4692 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4693 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4694 		/*
4695 		 * We have retransmitted to many times for TLP. Switch to
4696 		 * the regular RTO timer
4697 		 */
4698 		goto restore;
4699 	}
4700 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4701 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4702 	return (0);
4703 }
4704 
4705 /*
4706  * Delayed ack Timer, here we simply need to setup the
4707  * ACK_NOW flag and remove the DELACK flag. From there
4708  * the output routine will send the ack out.
4709  *
4710  * We only return 1, saying don't proceed, if all timers
4711  * are stopped (destroyed PCB?).
4712  */
4713 static int
4714 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4715 {
4716 	if (bbr->rc_all_timers_stopped) {
4717 		return (1);
4718 	}
4719 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4720 	tp->t_flags &= ~TF_DELACK;
4721 	tp->t_flags |= TF_ACKNOW;
4722 	KMOD_TCPSTAT_INC(tcps_delack);
4723 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4724 	return (0);
4725 }
4726 
4727 /*
4728  * Here we send a KEEP-ALIVE like probe to the
4729  * peer, we do not send data.
4730  *
4731  * We only return 1, saying don't proceed, if all timers
4732  * are stopped (destroyed PCB?).
4733  */
4734 static int
4735 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4736 {
4737 	struct tcptemp *t_template;
4738 	int32_t retval = 1;
4739 
4740 	if (bbr->rc_all_timers_stopped) {
4741 		return (1);
4742 	}
4743 	if (bbr->rc_in_persist == 0)
4744 		return (0);
4745 
4746 	/*
4747 	 * Persistence timer into zero window. Force a byte to be output, if
4748 	 * possible.
4749 	 */
4750 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4751 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4752 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4753 	/*
4754 	 * Have we exceeded the user specified progress time?
4755 	 */
4756 	if (ctf_progress_timeout_check(tp, true)) {
4757 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4758 		return (-ETIMEDOUT);	/* tcp_drop() */
4759 	}
4760 	/*
4761 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4762 	 * window is closed.  After a full backoff, drop the connection if
4763 	 * the idle time (no responses to probes) reaches the maximum
4764 	 * backoff that we would use if retransmitting.
4765 	 */
4766 	if (tp->t_rxtshift >= V_tcp_retries &&
4767 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4768 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4769 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4770 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4771 		return (-ETIMEDOUT);	/* tcp_drop() */
4772 	}
4773 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4774 	    tp->snd_una == tp->snd_max) {
4775 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4776 		retval = 0;
4777 		goto out;
4778 	}
4779 	/*
4780 	 * If the user has closed the socket then drop a persisting
4781 	 * connection after a much reduced timeout.
4782 	 */
4783 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4784 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4785 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4786 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4787 		return (-ETIMEDOUT);	/* tcp_drop() */
4788 	}
4789 	t_template = tcpip_maketemplate(bbr->rc_inp);
4790 	if (t_template) {
4791 		tcp_respond(tp, t_template->tt_ipgen,
4792 			    &t_template->tt_t, (struct mbuf *)NULL,
4793 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4794 		/* This sends an ack */
4795 		if (tp->t_flags & TF_DELACK)
4796 			tp->t_flags &= ~TF_DELACK;
4797 		free(t_template, M_TEMP);
4798 	}
4799 	if (tp->t_rxtshift < V_tcp_retries)
4800 		tp->t_rxtshift++;
4801 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4802 out:
4803 	return (retval);
4804 }
4805 
4806 /*
4807  * If a keepalive goes off, we had no other timers
4808  * happening. We always return 1 here since this
4809  * routine either drops the connection or sends
4810  * out a segment with respond.
4811  */
4812 static int
4813 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4814 {
4815 	struct tcptemp *t_template;
4816 	struct inpcb *inp = tptoinpcb(tp);
4817 
4818 	if (bbr->rc_all_timers_stopped) {
4819 		return (1);
4820 	}
4821 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4822 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4823 	/*
4824 	 * Keep-alive timer went off; send something or drop connection if
4825 	 * idle for too long.
4826 	 */
4827 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4828 	if (tp->t_state < TCPS_ESTABLISHED)
4829 		goto dropit;
4830 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4831 	    tp->t_state <= TCPS_CLOSING) {
4832 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4833 			goto dropit;
4834 		/*
4835 		 * Send a packet designed to force a response if the peer is
4836 		 * up and reachable: either an ACK if the connection is
4837 		 * still alive, or an RST if the peer has closed the
4838 		 * connection due to timeout or reboot. Using sequence
4839 		 * number tp->snd_una-1 causes the transmitted zero-length
4840 		 * segment to lie outside the receive window; by the
4841 		 * protocol spec, this requires the correspondent TCP to
4842 		 * respond.
4843 		 */
4844 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4845 		t_template = tcpip_maketemplate(inp);
4846 		if (t_template) {
4847 			tcp_respond(tp, t_template->tt_ipgen,
4848 			    &t_template->tt_t, (struct mbuf *)NULL,
4849 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4850 			free(t_template, M_TEMP);
4851 		}
4852 	}
4853 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4854 	return (1);
4855 dropit:
4856 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4857 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4858 	return (-ETIMEDOUT);	/* tcp_drop() */
4859 }
4860 
4861 /*
4862  * Retransmit helper function, clear up all the ack
4863  * flags and take care of important book keeping.
4864  */
4865 static void
4866 bbr_remxt_tmr(struct tcpcb *tp)
4867 {
4868 	/*
4869 	 * The retransmit timer went off, all sack'd blocks must be
4870 	 * un-acked.
4871 	 */
4872 	struct bbr_sendmap *rsm, *trsm = NULL;
4873 	struct tcp_bbr *bbr;
4874 	uint32_t cts, lost;
4875 
4876 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4877 	cts = tcp_get_usecs(&bbr->rc_tv);
4878 	lost = bbr->r_ctl.rc_lost;
4879 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4880 		bbr_set_state(tp, bbr, 0);
4881 
4882 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4883 		if (rsm->r_flags & BBR_ACKED) {
4884 			uint32_t old_flags;
4885 
4886 			rsm->r_dupack = 0;
4887 			if (rsm->r_in_tmap == 0) {
4888 				/* We must re-add it back to the tlist */
4889 				if (trsm == NULL) {
4890 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4891 				} else {
4892 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4893 				}
4894 				rsm->r_in_tmap = 1;
4895 			}
4896 			old_flags = rsm->r_flags;
4897 			rsm->r_flags |= BBR_RXT_CLEARED;
4898 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4899 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4900 		} else {
4901 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4902 			    (rsm->r_start == tp->snd_una)) {
4903 				/*
4904 				 * Special case for TCP FO. Where
4905 				 * we sent more data beyond the snd_max.
4906 				 * We don't mark that as lost and stop here.
4907 				 */
4908 				break;
4909 			}
4910 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4911 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4912 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4913 			}
4914 			if (bbr_marks_rxt_sack_passed) {
4915 				/*
4916 				 * With this option, we will rack out
4917 				 * in 1ms increments the rest of the packets.
4918 				 */
4919 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4920 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4921 			} else {
4922 				/*
4923 				 * With this option we only mark them lost
4924 				 * and remove all sack'd markings. We will run
4925 				 * another RXT or a TLP. This will cause
4926 				 * us to eventually send more based on what
4927 				 * ack's come in.
4928 				 */
4929 				rsm->r_flags |= BBR_MARKED_LOST;
4930 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4931 				rsm->r_flags &= ~BBR_SACK_PASSED;
4932 			}
4933 		}
4934 		trsm = rsm;
4935 	}
4936 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4937 	/* Clear the count (we just un-acked them) */
4938 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4939 	bbr->rc_tlp_new_data = 0;
4940 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4941 	/* zap the behindness on a rxt */
4942 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4943 	bbr->r_agg_early_set = 0;
4944 	bbr->r_ctl.rc_agg_early = 0;
4945 	bbr->rc_tlp_rtx_out = 0;
4946 	bbr->r_ctl.rc_sacked = 0;
4947 	bbr->r_ctl.rc_sacklast = NULL;
4948 	bbr->r_timer_override = 1;
4949 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4950 }
4951 
4952 /*
4953  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4954  * we will setup to retransmit the lowest seq number outstanding.
4955  */
4956 static int
4957 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4958 {
4959 	struct inpcb *inp = tptoinpcb(tp);
4960 	int32_t rexmt;
4961 	int32_t retval = 0;
4962 	bool isipv6;
4963 
4964 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4965 	if (bbr->rc_all_timers_stopped) {
4966 		return (1);
4967 	}
4968 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4969 	    (tp->snd_una == tp->snd_max)) {
4970 		/* Nothing outstanding .. nothing to do */
4971 		return (0);
4972 	}
4973 	/*
4974 	 * Retransmission timer went off.  Message has not been acked within
4975 	 * retransmit interval.  Back off to a longer retransmit interval
4976 	 * and retransmit one segment.
4977 	 */
4978 	if (ctf_progress_timeout_check(tp, true)) {
4979 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4980 		return (-ETIMEDOUT);	/* tcp_drop() */
4981 	}
4982 	bbr_remxt_tmr(tp);
4983 	if ((bbr->r_ctl.rc_resend == NULL) ||
4984 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4985 		/*
4986 		 * If the rwnd collapsed on
4987 		 * the one we are retransmitting
4988 		 * it does not count against the
4989 		 * rxt count.
4990 		 */
4991 		tp->t_rxtshift++;
4992 	}
4993 	if (tp->t_rxtshift > V_tcp_retries) {
4994 		tp->t_rxtshift = V_tcp_retries;
4995 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
4996 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
4997 		/* XXXGL: previously t_softerror was casted to uint16_t */
4998 		MPASS(tp->t_softerror >= 0);
4999 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
5000 		return (retval);	/* tcp_drop() */
5001 	}
5002 	if (tp->t_state == TCPS_SYN_SENT) {
5003 		/*
5004 		 * If the SYN was retransmitted, indicate CWND to be limited
5005 		 * to 1 segment in cc_conn_init().
5006 		 */
5007 		tp->snd_cwnd = 1;
5008 	} else if (tp->t_rxtshift == 1) {
5009 		/*
5010 		 * first retransmit; record ssthresh and cwnd so they can be
5011 		 * recovered if this turns out to be a "bad" retransmit. A
5012 		 * retransmit is considered "bad" if an ACK for this segment
5013 		 * is received within RTT/2 interval; the assumption here is
5014 		 * that the ACK was already in flight.  See "On Estimating
5015 		 * End-to-End Network Path Properties" by Allman and Paxson
5016 		 * for more details.
5017 		 */
5018 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5019 		if (!IN_RECOVERY(tp->t_flags)) {
5020 			tp->snd_cwnd_prev = tp->snd_cwnd;
5021 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5022 			tp->snd_recover_prev = tp->snd_recover;
5023 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5024 			tp->t_flags |= TF_PREVVALID;
5025 		} else {
5026 			tp->t_flags &= ~TF_PREVVALID;
5027 		}
5028 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5029 	} else {
5030 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5031 		tp->t_flags &= ~TF_PREVVALID;
5032 	}
5033 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5034 	if ((tp->t_state == TCPS_SYN_SENT) ||
5035 	    (tp->t_state == TCPS_SYN_RECEIVED))
5036 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5037 	else
5038 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5039 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5040 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5041 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5042 	/*
5043 	 * We enter the path for PLMTUD if connection is established or, if
5044 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5045 	 * amount of data we send is very small, we could send it in couple
5046 	 * of packets and process straight to FIN. In that case we won't
5047 	 * catch ESTABLISHED state.
5048 	 */
5049 #ifdef INET6
5050 	isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
5051 #else
5052 	isipv6 = false;
5053 #endif
5054 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5055 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5056 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5057 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5058 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5059 		/*
5060 		 * Idea here is that at each stage of mtu probe (usually,
5061 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5062 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5063 		 * should take care of that.
5064 		 */
5065 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5066 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5067 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5068 		    tp->t_rxtshift % 2 == 0)) {
5069 			/*
5070 			 * Enter Path MTU Black-hole Detection mechanism: -
5071 			 * Disable Path MTU Discovery (IP "DF" bit). -
5072 			 * Reduce MTU to lower value than what we negotiated
5073 			 * with peer.
5074 			 */
5075 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5076 				/*
5077 				 * Record that we may have found a black
5078 				 * hole.
5079 				 */
5080 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5081 				/* Keep track of previous MSS. */
5082 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5083 			}
5084 			/*
5085 			 * Reduce the MSS to blackhole value or to the
5086 			 * default in an attempt to retransmit.
5087 			 */
5088 #ifdef INET6
5089 			isipv6 = bbr->r_is_v6;
5090 			if (isipv6 &&
5091 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5092 				/* Use the sysctl tuneable blackhole MSS. */
5093 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5094 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5095 			} else if (isipv6) {
5096 				/* Use the default MSS. */
5097 				tp->t_maxseg = V_tcp_v6mssdflt;
5098 				/*
5099 				 * Disable Path MTU Discovery when we switch
5100 				 * to minmss.
5101 				 */
5102 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5103 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5104 			}
5105 #endif
5106 #if defined(INET6) && defined(INET)
5107 			else
5108 #endif
5109 #ifdef INET
5110 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5111 				/* Use the sysctl tuneable blackhole MSS. */
5112 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5113 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5114 			} else {
5115 				/* Use the default MSS. */
5116 				tp->t_maxseg = V_tcp_mssdflt;
5117 				/*
5118 				 * Disable Path MTU Discovery when we switch
5119 				 * to minmss.
5120 				 */
5121 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5122 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5123 			}
5124 #endif
5125 		} else {
5126 			/*
5127 			 * If further retransmissions are still unsuccessful
5128 			 * with a lowered MTU, maybe this isn't a blackhole
5129 			 * and we restore the previous MSS and blackhole
5130 			 * detection flags. The limit '6' is determined by
5131 			 * giving each probe stage (1448, 1188, 524) 2
5132 			 * chances to recover.
5133 			 */
5134 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5135 			    (tp->t_rxtshift >= 6)) {
5136 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5137 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5138 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5139 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5140 			}
5141 		}
5142 	}
5143 	/*
5144 	 * Disable RFC1323 and SACK if we haven't got any response to our
5145 	 * third SYN to work-around some broken terminal servers (most of
5146 	 * which have hopefully been retired) that have bad VJ header
5147 	 * compression code which trashes TCP segments containing
5148 	 * unknown-to-them TCP options.
5149 	 */
5150 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5151 	    (tp->t_rxtshift == 3))
5152 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5153 	/*
5154 	 * If we backed off this far, our srtt estimate is probably bogus.
5155 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5156 	 * move the current srtt into rttvar to keep the current retransmit
5157 	 * times until then.
5158 	 */
5159 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5160 #ifdef INET6
5161 		if (bbr->r_is_v6)
5162 			in6_losing(inp);
5163 		else
5164 #endif
5165 			in_losing(inp);
5166 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5167 		tp->t_srtt = 0;
5168 	}
5169 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5170 	tp->snd_recover = tp->snd_max;
5171 	tp->t_flags |= TF_ACKNOW;
5172 	tp->t_rtttime = 0;
5173 
5174 	return (retval);
5175 }
5176 
5177 static int
5178 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5179 {
5180 	int32_t ret = 0;
5181 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5182 
5183 	if (timers == 0) {
5184 		return (0);
5185 	}
5186 	if (tp->t_state == TCPS_LISTEN) {
5187 		/* no timers on listen sockets */
5188 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5189 			return (0);
5190 		return (1);
5191 	}
5192 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5193 		uint32_t left;
5194 
5195 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5196 			ret = -1;
5197 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5198 			return (0);
5199 		}
5200 		if (hpts_calling == 0) {
5201 			ret = -2;
5202 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5203 			return (0);
5204 		}
5205 		/*
5206 		 * Ok our timer went off early and we are not paced false
5207 		 * alarm, go back to sleep.
5208 		 */
5209 		left = bbr->r_ctl.rc_timer_exp - cts;
5210 		ret = -3;
5211 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5212 		tcp_hpts_insert(tp, HPTS_USEC_TO_SLOTS(left));
5213 		return (1);
5214 	}
5215 	bbr->rc_tmr_stopped = 0;
5216 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5217 	if (timers & PACE_TMR_DELACK) {
5218 		ret = bbr_timeout_delack(tp, bbr, cts);
5219 	} else if (timers & PACE_TMR_PERSIT) {
5220 		ret = bbr_timeout_persist(tp, bbr, cts);
5221 	} else if (timers & PACE_TMR_RACK) {
5222 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5223 		ret = bbr_timeout_rack(tp, bbr, cts);
5224 	} else if (timers & PACE_TMR_TLP) {
5225 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5226 		ret = bbr_timeout_tlp(tp, bbr, cts);
5227 	} else if (timers & PACE_TMR_RXT) {
5228 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5229 		ret = bbr_timeout_rxt(tp, bbr, cts);
5230 	} else if (timers & PACE_TMR_KEEP) {
5231 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5232 	}
5233 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5234 	return (ret);
5235 }
5236 
5237 static void
5238 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5239 {
5240 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5241 		uint8_t hpts_removed = 0;
5242 
5243 		if (tcp_in_hpts(bbr->rc_tp) &&
5244 		    (bbr->rc_timer_first == 1)) {
5245 			/*
5246 			 * If we are canceling timer's when we have the
5247 			 * timer ahead of the output being paced. We also
5248 			 * must remove ourselves from the hpts.
5249 			 */
5250 			hpts_removed = 1;
5251 			tcp_hpts_remove(bbr->rc_tp);
5252 			if (bbr->r_ctl.rc_last_delay_val) {
5253 				/* Update the last hptsi delay too */
5254 				uint32_t time_since_send;
5255 
5256 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5257 					time_since_send = cts - bbr->rc_pacer_started;
5258 				else
5259 					time_since_send = 0;
5260 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5261 					/* Cut down our slot time */
5262 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5263 				} else {
5264 					bbr->r_ctl.rc_last_delay_val = 0;
5265 				}
5266 				bbr->rc_pacer_started = cts;
5267 			}
5268 		}
5269 		bbr->rc_timer_first = 0;
5270 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5271 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5272 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5273 	}
5274 }
5275 
5276 static int
5277 bbr_stopall(struct tcpcb *tp)
5278 {
5279 	struct tcp_bbr *bbr;
5280 
5281 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5282 	bbr->rc_all_timers_stopped = 1;
5283 	return (0);
5284 }
5285 
5286 static uint32_t
5287 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5288 {
5289 	struct bbr_sendmap *rsm;
5290 
5291 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5292 	if ((rsm == NULL) || (u_rsm == rsm))
5293 		return (cts);
5294 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5295 }
5296 
5297 static void
5298 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5299      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5300 {
5301 	int32_t idx;
5302 
5303 	rsm->r_rtr_cnt++;
5304 	rsm->r_dupack = 0;
5305 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5306 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5307 		rsm->r_flags |= BBR_OVERMAX;
5308 	}
5309 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5310 		/* Take off the collapsed flag at rxt */
5311 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5312 	}
5313 	if (rsm->r_flags & BBR_MARKED_LOST) {
5314 		/* We have retransmitted, its no longer lost */
5315 		rsm->r_flags &= ~BBR_MARKED_LOST;
5316 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5317 	}
5318 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5319 		/*
5320 		 * We hit a RXT timer on it and
5321 		 * we cleared the "acked" flag.
5322 		 * We now have it going back into
5323 		 * flight, we can remove the cleared
5324 		 * flag and possibly do accounting on
5325 		 * this piece.
5326 		 */
5327 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5328 	}
5329 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5330 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5331 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5332 	}
5333 	idx = rsm->r_rtr_cnt - 1;
5334 	rsm->r_tim_lastsent[idx] = cts;
5335 	rsm->r_pacing_delay = pacing_time;
5336 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5337 	rsm->r_ts_valid = bbr->rc_ts_valid;
5338 	if (bbr->rc_ts_valid)
5339 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5340 	if (bbr->r_ctl.r_app_limited_until)
5341 		rsm->r_app_limited = 1;
5342 	else
5343 		rsm->r_app_limited = 0;
5344 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5345 		rsm->r_bbr_state = bbr_state_val(bbr);
5346 	else
5347 		rsm->r_bbr_state = 8;
5348 	if (rsm->r_flags & BBR_ACKED) {
5349 		/* Problably MTU discovery messing with us */
5350 		uint32_t old_flags;
5351 
5352 		old_flags = rsm->r_flags;
5353 		rsm->r_flags &= ~BBR_ACKED;
5354 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5355 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5356 		if (bbr->r_ctl.rc_sacked == 0)
5357 			bbr->r_ctl.rc_sacklast = NULL;
5358 	}
5359 	if (rsm->r_in_tmap) {
5360 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5361 	}
5362 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5363 	rsm->r_in_tmap = 1;
5364 	if (rsm->r_flags & BBR_SACK_PASSED) {
5365 		/* We have retransmitted due to the SACK pass */
5366 		rsm->r_flags &= ~BBR_SACK_PASSED;
5367 		rsm->r_flags |= BBR_WAS_SACKPASS;
5368 	}
5369 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5370 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5371 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5372 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5373 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5374 		rsm->r_is_gain = 1;
5375 		rsm->r_is_drain = 0;
5376 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5377 		rsm->r_is_drain = 1;
5378 		rsm->r_is_gain = 0;
5379 	} else {
5380 		rsm->r_is_drain = 0;
5381 		rsm->r_is_gain = 0;
5382 	}
5383 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5384 }
5385 
5386 /*
5387  * Returns 0, or the sequence where we stopped
5388  * updating. We also update the lenp to be the amount
5389  * of data left.
5390  */
5391 
5392 static uint32_t
5393 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5394     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5395 {
5396 	/*
5397 	 * We (re-)transmitted starting at rsm->r_start for some length
5398 	 * (possibly less than r_end.
5399 	 */
5400 	struct bbr_sendmap *nrsm;
5401 	uint32_t c_end;
5402 	int32_t len;
5403 
5404 	len = *lenp;
5405 	c_end = rsm->r_start + len;
5406 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5407 		/*
5408 		 * We retransmitted the whole piece or more than the whole
5409 		 * slopping into the next rsm.
5410 		 */
5411 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5412 		if (c_end == rsm->r_end) {
5413 			*lenp = 0;
5414 			return (0);
5415 		} else {
5416 			int32_t act_len;
5417 
5418 			/* Hangs over the end return whats left */
5419 			act_len = rsm->r_end - rsm->r_start;
5420 			*lenp = (len - act_len);
5421 			return (rsm->r_end);
5422 		}
5423 		/* We don't get out of this block. */
5424 	}
5425 	/*
5426 	 * Here we retransmitted less than the whole thing which means we
5427 	 * have to split this into what was transmitted and what was not.
5428 	 */
5429 	nrsm = bbr_alloc_full_limit(bbr);
5430 	if (nrsm == NULL) {
5431 		*lenp = 0;
5432 		return (0);
5433 	}
5434 	/*
5435 	 * So here we are going to take the original rsm and make it what we
5436 	 * retransmitted. nrsm will be the tail portion we did not
5437 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5438 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5439 	 * 1, 6 and the new piece will be 6, 11.
5440 	 */
5441 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5442 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5443 	nrsm->r_dupack = 0;
5444 	if (rsm->r_in_tmap) {
5445 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5446 		nrsm->r_in_tmap = 1;
5447 	}
5448 	rsm->r_flags &= (~BBR_HAS_FIN);
5449 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5450 	*lenp = 0;
5451 	return (0);
5452 }
5453 
5454 static uint64_t
5455 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5456 {
5457 	uint64_t bw;
5458 
5459 	bw = bbr_get_bw(bbr);
5460 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5461 	bw /= (uint64_t)BBR_UNIT;
5462 	return(bw);
5463 }
5464 
5465 static void
5466 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5467 		       uint64_t act_rate, uint64_t rate_wanted)
5468 {
5469 	/*
5470 	 * We could not get a full gains worth
5471 	 * of rate.
5472 	 */
5473 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5474 		/* we can't even get the real rate */
5475 		uint64_t red;
5476 
5477 		bbr->skip_gain = 1;
5478 		bbr->gain_is_limited = 0;
5479 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5480 		if (red)
5481 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5482 	} else {
5483 		/* We can use a lower gain */
5484 		bbr->skip_gain = 0;
5485 		bbr->gain_is_limited = 1;
5486 	}
5487 }
5488 
5489 static void
5490 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5491 {
5492 	const struct tcp_hwrate_limit_table *nrte;
5493 	int error, rate = -1;
5494 
5495 	if (bbr->r_ctl.crte == NULL)
5496 		return;
5497 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5498 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5499 		/* Lost our routes? */
5500 		/* Clear the way for a re-attempt */
5501 		bbr->bbr_attempt_hdwr_pace = 0;
5502 lost_rate:
5503 		bbr->gain_is_limited = 0;
5504 		bbr->skip_gain = 0;
5505 		bbr->bbr_hdrw_pacing = 0;
5506 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5507 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5508 		tcp_bbr_tso_size_check(bbr, cts);
5509 		return;
5510 	}
5511 	rate = bbr_get_hardware_rate(bbr);
5512 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5513 				   bbr->rc_tp,
5514 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5515 				   rate,
5516 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5517 				   &error, NULL);
5518 	if (nrte == NULL) {
5519 		goto lost_rate;
5520 	}
5521 	if (nrte != bbr->r_ctl.crte) {
5522 		bbr->r_ctl.crte = nrte;
5523 		if (error == 0)  {
5524 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5525 			if (bbr->r_ctl.crte->rate < rate) {
5526 				/* We have a problem */
5527 				bbr_setup_less_of_rate(bbr, cts,
5528 						       bbr->r_ctl.crte->rate, rate);
5529 			} else {
5530 				/* We are good */
5531 				bbr->gain_is_limited = 0;
5532 				bbr->skip_gain = 0;
5533 			}
5534 		} else {
5535 			/* A failure should release the tag */
5536 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5537 			bbr->gain_is_limited = 0;
5538 			bbr->skip_gain = 0;
5539 			bbr->bbr_hdrw_pacing = 0;
5540 		}
5541 		bbr_type_log_hdwr_pacing(bbr,
5542 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5543 					 rate,
5544 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5545 					 __LINE__,
5546 					 cts,
5547 					 error);
5548 	}
5549 }
5550 
5551 static void
5552 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5553 {
5554 	/*
5555 	 * If we have hardware pacing support
5556 	 * we need to factor that in for our
5557 	 * TSO size.
5558 	 */
5559 	const struct tcp_hwrate_limit_table *rlp;
5560 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5561 
5562 	if ((bbr->bbr_hdrw_pacing == 0) ||
5563 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5564 	    (bbr->r_ctl.crte == NULL))
5565 		return;
5566 	if (bbr->hw_pacing_set == 0) {
5567 		/* Not yet by the hdwr pacing count delay */
5568 		return;
5569 	}
5570 	if (bbr_hdwr_pace_adjust == 0) {
5571 		/* No adjustment */
5572 		return;
5573 	}
5574 	rlp = bbr->r_ctl.crte;
5575 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5576 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5577 	else
5578 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5579 	/*
5580 	 * So lets first get the
5581 	 * time we will take between
5582 	 * TSO sized sends currently without
5583 	 * hardware help.
5584 	 */
5585 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5586 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5587 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5588 	hdwr_delay *= rlp->time_between;
5589 	if (cur_delay > hdwr_delay)
5590 		delta = cur_delay - hdwr_delay;
5591 	else
5592 		delta = 0;
5593 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5594 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5595 			     1);
5596 	if (delta &&
5597 	    (delta < (max(rlp->time_between,
5598 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5599 		/*
5600 		 * Now lets divide by the pacing
5601 		 * time between each segment the
5602 		 * hardware sends rounding up and
5603 		 * derive a bytes from that. We multiply
5604 		 * that by bbr_hdwr_pace_adjust to get
5605 		 * more bang for our buck.
5606 		 *
5607 		 * The goal is to have the software pacer
5608 		 * waiting no more than an additional
5609 		 * pacing delay if we can (without the
5610 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5611 		 */
5612 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5613 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5614 		seg_sz *= bbr_hdwr_pace_adjust;
5615 		if (bbr_hdwr_pace_floor &&
5616 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5617 			/* Currently hardware paces
5618 			 * out rs_min_seg segments at a time.
5619 			 * We need to make sure we always send at least
5620 			 * a full burst of bbr_hdwr_pace_floor down.
5621 			 */
5622 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5623 		}
5624 		seg_sz *= maxseg;
5625 	} else if (delta == 0) {
5626 		/*
5627 		 * The highest pacing rate is
5628 		 * above our b/w gained. This means
5629 		 * we probably are going quite fast at
5630 		 * the hardware highest rate. Lets just multiply
5631 		 * the calculated TSO size by the
5632 		 * multiplier factor (its probably
5633 		 * 4 segments in the default config for
5634 		 * mlx).
5635 		 */
5636 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5637 		if (bbr_hdwr_pace_floor &&
5638 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5639 			/* Currently hardware paces
5640 			 * out rs_min_seg segments at a time.
5641 			 * We need to make sure we always send at least
5642 			 * a full burst of bbr_hdwr_pace_floor down.
5643 			 */
5644 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5645 		}
5646 	} else {
5647 		/*
5648 		 * The pacing time difference is so
5649 		 * big that the hardware will
5650 		 * pace out more rapidly then we
5651 		 * really want and then we
5652 		 * will have a long delay. Lets just keep
5653 		 * the same TSO size so its as if
5654 		 * we were not using hdwr pacing (we
5655 		 * just gain a bit of spacing from the
5656 		 * hardware if seg_sz > 1).
5657 		 */
5658 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5659 	}
5660 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5661 		new_tso = seg_sz;
5662 	else
5663 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5664 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5665 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5666 
5667 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5668 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5669 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5670 	}
5671 }
5672 
5673 static void
5674 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5675 {
5676 	uint64_t bw;
5677 	uint32_t old_tso = 0, new_tso;
5678 	uint32_t maxseg, bytes;
5679 	uint32_t tls_seg=0;
5680 	/*
5681 	 * Google/linux uses the following algorithm to determine
5682 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5683 	 *
5684 	 *  bytes = bw_in_bytes_per_second / 1000
5685 	 *  bytes = min(bytes, 64k)
5686 	 *  tso_segs = bytes / MSS
5687 	 *  if (bw < 1.2Mbs)
5688 	 *      min_tso_segs = 1
5689 	 *  else
5690 	 *	min_tso_segs = 2
5691 	 * tso_segs = max(tso_segs, min_tso_segs)
5692 	 *
5693 	 * * Note apply a device specific limit (we apply this in the
5694 	 *   tcp_m_copym).
5695 	 * Note that before the initial measurement is made google bursts out
5696 	 * a full iwnd just like new-reno/cubic.
5697 	 *
5698 	 * We do not use this algorithm. Instead we
5699 	 * use a two phased approach:
5700 	 *
5701 	 *  if ( bw <= per-tcb-cross-over)
5702 	 *     goal_tso =  calculate how much with this bw we
5703 	 *                 can send in goal-time seconds.
5704 	 *     if (goal_tso > mss)
5705 	 *         seg = goal_tso / mss
5706 	 *         tso = seg * mss
5707 	 *     else
5708 	 *         tso = mss
5709 	 *     if (tso > per-tcb-max)
5710 	 *         tso = per-tcb-max
5711 	 *  else if ( bw > 512Mbps)
5712 	 *     tso = max-tso (64k/mss)
5713 	 *  else
5714 	 *     goal_tso = bw / per-tcb-divsor
5715 	 *     seg = (goal_tso + mss-1)/mss
5716 	 *     tso = seg * mss
5717 	 *
5718 	 * if (tso < per-tcb-floor)
5719 	 *    tso = per-tcb-floor
5720 	 * if (tso > per-tcb-utter_max)
5721 	 *    tso = per-tcb-utter_max
5722 	 *
5723 	 * Note the default per-tcb-divisor is 1000 (same as google).
5724 	 * the goal cross over is 30Mbps however. To recreate googles
5725 	 * algorithm you need to set:
5726 	 *
5727 	 * cross-over = 23,168,000 bps
5728 	 * goal-time = 18000
5729 	 * per-tcb-max = 2
5730 	 * per-tcb-divisor = 1000
5731 	 * per-tcb-floor = 1
5732 	 *
5733 	 * This will get you "google bbr" behavior with respect to tso size.
5734 	 *
5735 	 * Note we do set anything TSO size until we are past the initial
5736 	 * window. Before that we gnerally use either a single MSS
5737 	 * or we use the full IW size (so we burst a IW at a time)
5738 	 */
5739 
5740 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5741 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5742 	} else {
5743 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5744 	}
5745 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5746 	if (bbr->rc_past_init_win == 0) {
5747 		/*
5748 		 * Not enough data has been acknowledged to make a
5749 		 * judgement. Set up the initial TSO based on if we
5750 		 * are sending a full IW at once or not.
5751 		 */
5752 		if (bbr->rc_use_google)
5753 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5754 		else if (bbr->bbr_init_win_cheat)
5755 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5756 		else
5757 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5758 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5759 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5760 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5761 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5762 		}
5763 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5764 			bbr_adjust_for_hw_pacing(bbr, cts);
5765 		return;
5766 	}
5767 	/**
5768 	 * Now lets set the TSO goal based on our delivery rate in
5769 	 * bytes per second. Note we only do this if
5770 	 * we have acked at least the initial cwnd worth of data.
5771 	 */
5772 	bw = bbr_get_bw(bbr);
5773 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5774 	     (bbr->rc_use_google == 0)) {
5775 		/* We clamp to one MSS in recovery */
5776 		new_tso = maxseg;
5777 	} else if (bbr->rc_use_google) {
5778 		int min_tso_segs;
5779 
5780 		/* Google considers the gain too */
5781 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5782 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5783 			bw /= BBR_UNIT;
5784 		}
5785 		bytes = bw / 1024;
5786 		if (bytes > (64 * 1024))
5787 			bytes = 64 * 1024;
5788 		new_tso = bytes / maxseg;
5789 		if (bw < ONE_POINT_TWO_MEG)
5790 			min_tso_segs = 1;
5791 		else
5792 			min_tso_segs = 2;
5793 		if (new_tso < min_tso_segs)
5794 			new_tso = min_tso_segs;
5795 		new_tso *= maxseg;
5796 	} else if (bbr->rc_no_pacing) {
5797 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5798 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5799 		/*
5800 		 * Calculate the worse case b/w TSO if we are inserting no
5801 		 * more than a delay_target number of TSO's.
5802 		 */
5803 		uint32_t tso_len, min_tso;
5804 
5805 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5806 		if (tso_len > maxseg) {
5807 			new_tso = tso_len / maxseg;
5808 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5809 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5810 			new_tso *= maxseg;
5811 		} else {
5812 			/*
5813 			 * less than a full sized frame yikes.. long rtt or
5814 			 * low bw?
5815 			 */
5816 			min_tso = bbr_minseg(bbr);
5817 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5818 				new_tso = rounddown(tso_len, min_tso);
5819 			else
5820 				new_tso = min_tso;
5821 		}
5822 	} else if (bw > FIVETWELVE_MBPS) {
5823 		/*
5824 		 * This guy is so fast b/w wise that we can TSO as large as
5825 		 * possible of segments that the NIC will allow.
5826 		 */
5827 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5828 	} else {
5829 		/*
5830 		 * This formula is based on attempting to send a segment or
5831 		 * more every bbr_hptsi_per_second. The default is 1000
5832 		 * which means you are targeting what you can send every 1ms
5833 		 * based on the peers bw.
5834 		 *
5835 		 * If the number drops to say 500, then you are looking more
5836 		 * at 2ms and you will raise how much we send in a single
5837 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5838 		 * trade off of course is you will send more at once and
5839 		 * thus tend to clump up the sends into larger "bursts"
5840 		 * building a queue.
5841 		 */
5842 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5843 		new_tso = roundup(bw, (uint64_t)maxseg);
5844 		/*
5845 		 * Gate the floor to match what our lower than 48Mbps
5846 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5847 		 * becomes the floor for this calculation.
5848 		 */
5849 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5850 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5851 	}
5852 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5853 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5854 	if (new_tso > PACE_MAX_IP_BYTES)
5855 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5856 	/* Enforce an utter maximum. */
5857 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5858 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5859 	}
5860 	if (old_tso != new_tso) {
5861 		/* Only log changes */
5862 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5863 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5864 	}
5865 	/* We have hardware pacing! */
5866 	bbr_adjust_for_hw_pacing(bbr, cts);
5867 }
5868 
5869 static void
5870 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5871     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5872     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5873     struct sockbuf *sb)
5874 {
5875 
5876 	struct bbr_sendmap *rsm, *nrsm;
5877 	register uint32_t snd_max, snd_una;
5878 	uint32_t pacing_time;
5879 	/*
5880 	 * Add to the RACK log of packets in flight or retransmitted. If
5881 	 * there is a TS option we will use the TS echoed, if not we will
5882 	 * grab a TS.
5883 	 *
5884 	 * Retransmissions will increment the count and move the ts to its
5885 	 * proper place. Note that if options do not include TS's then we
5886 	 * won't be able to effectively use the ACK for an RTT on a retran.
5887 	 *
5888 	 * Notes about r_start and r_end. Lets consider a send starting at
5889 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5890 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5891 	 * This means that r_end is actually the first sequence for the next
5892 	 * slot (11).
5893 	 *
5894 	 */
5895 	INP_WLOCK_ASSERT(tptoinpcb(tp));
5896 	if (err) {
5897 		/*
5898 		 * We don't log errors -- we could but snd_max does not
5899 		 * advance in this case either.
5900 		 */
5901 		return;
5902 	}
5903 	if (th_flags & TH_RST) {
5904 		/*
5905 		 * We don't log resets and we return immediately from
5906 		 * sending
5907 		 */
5908 		*abandon = 1;
5909 		return;
5910 	}
5911 	snd_una = tp->snd_una;
5912 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5913 		/*
5914 		 * The call to bbr_log_output is made before bumping
5915 		 * snd_max. This means we can record one extra byte on a SYN
5916 		 * or FIN if seq_out is adding more on and a FIN is present
5917 		 * (and we are not resending).
5918 		 */
5919 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5920 			len++;
5921 		if (th_flags & TH_FIN)
5922 			len++;
5923 	}
5924 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5925 		/* Are sending an old segment to induce an ack (keep-alive)? */
5926 		return;
5927 	}
5928 	if (SEQ_LT(seq_out, snd_una)) {
5929 		/* huh? should we panic? */
5930 		uint32_t end;
5931 
5932 		end = seq_out + len;
5933 		seq_out = snd_una;
5934 		len = end - seq_out;
5935 	}
5936 	snd_max = tp->snd_max;
5937 	if (len == 0) {
5938 		/* We don't log zero window probes */
5939 		return;
5940 	}
5941 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5942 	/* First question is it a retransmission? */
5943 	if (seq_out == snd_max) {
5944 again:
5945 		rsm = bbr_alloc(bbr);
5946 		if (rsm == NULL) {
5947 			return;
5948 		}
5949 		rsm->r_flags = 0;
5950 		if (th_flags & TH_SYN)
5951 			rsm->r_flags |= BBR_HAS_SYN;
5952 		if (th_flags & TH_FIN)
5953 			rsm->r_flags |= BBR_HAS_FIN;
5954 		rsm->r_tim_lastsent[0] = cts;
5955 		rsm->r_rtr_cnt = 1;
5956 		rsm->r_rtr_bytes = 0;
5957 		rsm->r_start = seq_out;
5958 		rsm->r_end = rsm->r_start + len;
5959 		rsm->r_dupack = 0;
5960 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5961 		rsm->r_pacing_delay = pacing_time;
5962 		rsm->r_ts_valid = bbr->rc_ts_valid;
5963 		if (bbr->rc_ts_valid)
5964 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5965 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
5966 		if (bbr->r_ctl.r_app_limited_until)
5967 			rsm->r_app_limited = 1;
5968 		else
5969 			rsm->r_app_limited = 0;
5970 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5971 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5972 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5973 		/*
5974 		 * Here we must also add in this rsm since snd_max
5975 		 * is updated after we return from a new send.
5976 		 */
5977 		rsm->r_flight_at_send += len;
5978 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
5979 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5980 		rsm->r_in_tmap = 1;
5981 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5982 			rsm->r_bbr_state = bbr_state_val(bbr);
5983 		else
5984 			rsm->r_bbr_state = 8;
5985 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5986 			rsm->r_is_gain = 1;
5987 			rsm->r_is_drain = 0;
5988 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5989 			rsm->r_is_drain = 1;
5990 			rsm->r_is_gain = 0;
5991 		} else {
5992 			rsm->r_is_drain = 0;
5993 			rsm->r_is_gain = 0;
5994 		}
5995 		return;
5996 	}
5997 	/*
5998 	 * If we reach here its a retransmission and we need to find it.
5999 	 */
6000 more:
6001 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6002 		rsm = hintrsm;
6003 		hintrsm = NULL;
6004 	} else if (bbr->r_ctl.rc_next) {
6005 		/* We have a hint from a previous run */
6006 		rsm = bbr->r_ctl.rc_next;
6007 	} else {
6008 		/* No hints sorry */
6009 		rsm = NULL;
6010 	}
6011 	if ((rsm) && (rsm->r_start == seq_out)) {
6012 		/*
6013 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6014 		 * likely case.
6015 		 */
6016 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6017 		if (len == 0) {
6018 			return;
6019 		} else {
6020 			goto more;
6021 		}
6022 	}
6023 	/* Ok it was not the last pointer go through it the hard way. */
6024 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6025 		if (rsm->r_start == seq_out) {
6026 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6027 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6028 			if (len == 0) {
6029 				return;
6030 			} else {
6031 				continue;
6032 			}
6033 		}
6034 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6035 			/* Transmitted within this piece */
6036 			/*
6037 			 * Ok we must split off the front and then let the
6038 			 * update do the rest
6039 			 */
6040 			nrsm = bbr_alloc_full_limit(bbr);
6041 			if (nrsm == NULL) {
6042 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6043 				return;
6044 			}
6045 			/*
6046 			 * copy rsm to nrsm and then trim the front of rsm
6047 			 * to not include this part.
6048 			 */
6049 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6050 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6051 			if (rsm->r_in_tmap) {
6052 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6053 				nrsm->r_in_tmap = 1;
6054 			}
6055 			rsm->r_flags &= (~BBR_HAS_FIN);
6056 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6057 			if (len == 0) {
6058 				return;
6059 			}
6060 		}
6061 	}
6062 	/*
6063 	 * Hmm not found in map did they retransmit both old and on into the
6064 	 * new?
6065 	 */
6066 	if (seq_out == tp->snd_max) {
6067 		goto again;
6068 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6069 #ifdef BBR_INVARIANTS
6070 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6071 		    seq_out, len, tp->snd_una, tp->snd_max);
6072 		printf("Starting Dump of all rack entries\n");
6073 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6074 			printf("rsm:%p start:%u end:%u\n",
6075 			    rsm, rsm->r_start, rsm->r_end);
6076 		}
6077 		printf("Dump complete\n");
6078 		panic("seq_out not found rack:%p tp:%p",
6079 		    bbr, tp);
6080 #endif
6081 	} else {
6082 #ifdef BBR_INVARIANTS
6083 		/*
6084 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6085 		 * flag)
6086 		 */
6087 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6088 		    seq_out, len, tp->snd_max, tp);
6089 #endif
6090 	}
6091 }
6092 
6093 static void
6094 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6095 {
6096 	/*
6097 	 * Collapse timeout back the cum-ack moved.
6098 	 */
6099 	tp->t_rxtshift = 0;
6100 	tp->t_softerror = 0;
6101 }
6102 
6103 static void
6104 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6105 {
6106 	bbr->rtt_valid = 1;
6107 	bbr->r_ctl.cur_rtt = rtt_usecs;
6108 	bbr->r_ctl.ts_in = tsin;
6109 	if (rsm_send_time)
6110 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6111 }
6112 
6113 static void
6114 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6115 {
6116 	/**
6117 	 * We have in our bbr control:
6118 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6119 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6120 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6121 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6122 	 *
6123 	 * Now we can calculate the time between the sends by doing:
6124 	 *
6125 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6126 	 *
6127 	 * And the peer's time between receiving them by doing:
6128 	 *
6129 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6130 	 *
6131 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6132 	 * We also may find that we can't use the timestamps if say we see
6133 	 * that the peer_delta indicates that though we may have taken 10ms to
6134 	 * pace out the data, it only saw 1ms between the two packets. This would
6135 	 * indicate that somewhere on the path is a batching entity that is giving
6136 	 * out time-slices of the actual b/w. This would mean we could not use
6137 	 * reliably the peers timestamps.
6138 	 *
6139 	 * We expect delta > peer_delta initially. Until we figure out the
6140 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6141 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6142 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6143 	 * put a 1 there. If the value is faster then ours, we will disable the
6144 	 * use of timestamps (though we could revist this later if we find it to be not
6145 	 * just an isolated one or two flows)).
6146 	 *
6147 	 * To detect the batching middle boxes we will come up with our compensation and
6148 	 * if with it in place, we find the peer is drastically off (by some margin) in
6149 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6150 	 *
6151 	 */
6152 	uint64_t delta, peer_delta, delta_up;
6153 
6154 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6155 	if (delta < bbr_min_usec_delta) {
6156 		/*
6157 		 * Have not seen a min amount of time
6158 		 * between our send times so we can
6159 		 * make a determination of the timestamp
6160 		 * yet.
6161 		 */
6162 		return;
6163 	}
6164 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6165 	if (peer_delta < bbr_min_peer_delta) {
6166 		/*
6167 		 * We may have enough in the form of
6168 		 * our delta but the peers number
6169 		 * has not changed that much. It could
6170 		 * be its clock ratio is such that
6171 		 * we need more data (10ms tick) or
6172 		 * there may be other compression scenarios
6173 		 * going on. In any event we need the
6174 		 * spread to be larger.
6175 		 */
6176 		return;
6177 	}
6178 	/* Ok lets first see which way our delta is going */
6179 	if (peer_delta > delta) {
6180 		/* Very unlikely, the peer without
6181 		 * compensation shows that it saw
6182 		 * the two sends arrive further apart
6183 		 * then we saw then in micro-seconds.
6184 		 */
6185 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6186 			/* well it looks like the peer is a micro-second clock. */
6187 			bbr->rc_ts_clock_set = 1;
6188 			bbr->r_ctl.bbr_peer_tsratio = 1;
6189 		} else {
6190 			bbr->rc_ts_cant_be_used = 1;
6191 			bbr->rc_ts_clock_set = 1;
6192 		}
6193 		return;
6194 	}
6195 	/* Ok we know that the peer_delta is smaller than our send distance */
6196 	bbr->rc_ts_clock_set = 1;
6197 	/* First question is it within the percentage that they are using usec time? */
6198 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6199 	if ((peer_delta + delta_up) >= delta) {
6200 		/* Its a usec clock */
6201 		bbr->r_ctl.bbr_peer_tsratio = 1;
6202 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6203 		return;
6204 	}
6205 	/* Ok if not usec, what about 10usec (though unlikely)? */
6206 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6207 	if (((peer_delta * 10) + delta_up) >= delta) {
6208 		bbr->r_ctl.bbr_peer_tsratio = 10;
6209 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6210 		return;
6211 	}
6212 	/* And what about 100usec (though again unlikely)? */
6213 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6214 	if (((peer_delta * 100) + delta_up) >= delta) {
6215 		bbr->r_ctl.bbr_peer_tsratio = 100;
6216 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6217 		return;
6218 	}
6219 	/* And how about 1 msec (the most likely one)? */
6220 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6221 	if (((peer_delta * 1000) + delta_up) >= delta) {
6222 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6223 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6224 		return;
6225 	}
6226 	/* Ok if not msec could it be 10 msec? */
6227 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6228 	if (((peer_delta * 10000) + delta_up) >= delta) {
6229 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6230 		return;
6231 	}
6232 	/* If we fall down here the clock tick so slowly we can't use it */
6233 	bbr->rc_ts_cant_be_used = 1;
6234 	bbr->r_ctl.bbr_peer_tsratio = 0;
6235 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6236 }
6237 
6238 /*
6239  * Collect new round-trip time estimate
6240  * and update averages and current timeout.
6241  */
6242 static void
6243 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6244 {
6245 	int32_t delta;
6246 	uint32_t rtt, tsin;
6247 	int32_t rtt_ticks;
6248 
6249 	if (bbr->rtt_valid == 0)
6250 		/* No valid sample */
6251 		return;
6252 
6253 	rtt = bbr->r_ctl.cur_rtt;
6254 	tsin = bbr->r_ctl.ts_in;
6255 	if (bbr->rc_prtt_set_ts) {
6256 		/*
6257 		 * We are to force feed the rttProp filter due
6258 		 * to an entry into PROBE_RTT. This assures
6259 		 * that the times are sync'd between when we
6260 		 * go into PROBE_RTT and the filter expiration.
6261 		 *
6262 		 * Google does not use a true filter, so they do
6263 		 * this implicitly since they only keep one value
6264 		 * and when they enter probe-rtt they update the
6265 		 * value to the newest rtt.
6266 		 */
6267 		uint32_t rtt_prop;
6268 
6269 		bbr->rc_prtt_set_ts = 0;
6270 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6271 		if (rtt > rtt_prop)
6272 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6273 		else
6274 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6275 	}
6276 #ifdef STATS
6277 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_PATHRTT, imax(0, rtt));
6278 #endif
6279 	if (bbr->rc_ack_was_delayed)
6280 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6281 
6282 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6283 		bbr->r_ctl.rc_lowest_rtt = rtt;
6284 	bbr_log_rtt_sample(bbr, rtt, tsin);
6285 	if (bbr->r_init_rtt) {
6286 		/*
6287 		 * The initial rtt is not-trusted, nuke it and lets get
6288 		 * our first valid measurement in.
6289 		 */
6290 		bbr->r_init_rtt = 0;
6291 		tp->t_srtt = 0;
6292 	}
6293 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6294 		/*
6295 		 * So we have not yet figured out
6296 		 * what the peers TSTMP value is
6297 		 * in (most likely ms). We need a
6298 		 * series of cum-ack's to determine
6299 		 * this reliably.
6300 		 */
6301 		if (bbr->rc_ack_is_cumack) {
6302 			if (bbr->rc_ts_data_set) {
6303 				/* Lets attempt to determine the timestamp granularity. */
6304 				bbr_make_timestamp_determination(bbr);
6305 			} else {
6306 				bbr->rc_ts_data_set = 1;
6307 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6308 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6309 			}
6310 		} else {
6311 			/*
6312 			 * We have to have consecutive acks
6313 			 * reset any "filled" state to none.
6314 			 */
6315 			bbr->rc_ts_data_set = 0;
6316 		}
6317 	}
6318 	/* Round it up */
6319 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6320 	if (rtt_ticks == 0)
6321 		rtt_ticks = 1;
6322 	if (tp->t_srtt != 0) {
6323 		/*
6324 		 * srtt is stored as fixed point with 5 bits after the
6325 		 * binary point (i.e., scaled by 8).  The following magic is
6326 		 * equivalent to the smoothing algorithm in rfc793 with an
6327 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6328 		 * Adjust rtt to origin 0.
6329 		 */
6330 
6331 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6332 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6333 
6334 		tp->t_srtt += delta;
6335 		if (tp->t_srtt <= 0)
6336 			tp->t_srtt = 1;
6337 
6338 		/*
6339 		 * We accumulate a smoothed rtt variance (actually, a
6340 		 * smoothed mean difference), then set the retransmit timer
6341 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6342 		 * is stored as fixed point with 4 bits after the binary
6343 		 * point (scaled by 16).  The following is equivalent to
6344 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6345 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6346 		 * wired-in beta.
6347 		 */
6348 		if (delta < 0)
6349 			delta = -delta;
6350 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6351 		tp->t_rttvar += delta;
6352 		if (tp->t_rttvar <= 0)
6353 			tp->t_rttvar = 1;
6354 	} else {
6355 		/*
6356 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6357 		 * variance to half the rtt (so our first retransmit happens
6358 		 * at 3*rtt).
6359 		 */
6360 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6361 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6362 	}
6363 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6364 	if (tp->t_rttupdated < UCHAR_MAX)
6365 		tp->t_rttupdated++;
6366 #ifdef STATS
6367 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6368 #endif
6369 	/*
6370 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6371 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6372 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6373 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6374 	 * uncertainty in the firing of the timer.  The bias will give us
6375 	 * exactly the 1.5 tick we need.  But, because the bias is
6376 	 * statistical, we have to test that we don't drop below the minimum
6377 	 * feasible timer (which is 2 ticks).
6378 	 */
6379 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6380 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6381 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6382 
6383 	/*
6384 	 * We received an ack for a packet that wasn't retransmitted; it is
6385 	 * probably safe to discard any error indications we've received
6386 	 * recently.  This isn't quite right, but close enough for now (a
6387 	 * route might have failed after we sent a segment, and the return
6388 	 * path might not be symmetrical).
6389 	 */
6390 	tp->t_softerror = 0;
6391 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6392 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6393 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6394 }
6395 
6396 static void
6397 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6398 {
6399 	bbr->r_ctl.rc_rtt_shrinks = cts;
6400 	if (bbr_can_force_probertt &&
6401 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6402 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6403 		/*
6404 		 * We should enter probe-rtt its been too long
6405 		 * since we have been there.
6406 		 */
6407 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6408 	} else
6409 		bbr_check_probe_rtt_limits(bbr, cts);
6410 }
6411 
6412 static void
6413 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6414 {
6415 	uint64_t orig_bw;
6416 
6417 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6418 		/* We never apply a zero measurement */
6419 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6420 				    0, 0, 0, 0, 0, 0);
6421 		return;
6422 	}
6423 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6424 		bbr->r_ctl.r_measurement_count++;
6425 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6426 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6427 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6428 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6429 			    0, 0, 0, 0, 0, 0);
6430 	if (orig_bw &&
6431 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6432 		if (bbr->bbr_hdrw_pacing) {
6433 			/*
6434 			 * Apply a new rate to the hardware
6435 			 * possibly.
6436 			 */
6437 			bbr_update_hardware_pacing_rate(bbr, cts);
6438 		}
6439 		bbr_set_state_target(bbr, __LINE__);
6440 		tcp_bbr_tso_size_check(bbr, cts);
6441 		if (bbr->r_recovery_bw)  {
6442 			bbr_setup_red_bw(bbr, cts);
6443 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6444 		}
6445 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6446 		tcp_bbr_tso_size_check(bbr, cts);
6447 }
6448 
6449 static void
6450 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6451 {
6452 	if (bbr->rc_in_persist == 0) {
6453 		/* We log only when not in persist */
6454 		/* Translate to a Bytes Per Second */
6455 		uint64_t tim, bw, ts_diff, ts_bw;
6456 		uint32_t delivered;
6457 
6458 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6459 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6460 		else
6461 			tim = 1;
6462 		/*
6463 		 * Now that we have processed the tim (skipping the sample
6464 		 * or possibly updating the time, go ahead and
6465 		 * calculate the cdr.
6466 		 */
6467 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6468 		bw = (uint64_t)delivered;
6469 		bw *= (uint64_t)USECS_IN_SECOND;
6470 		bw /= tim;
6471 		if (bw == 0) {
6472 			/* We must have a calculatable amount */
6473 			return;
6474 		}
6475 		/*
6476 		 * If we are using this b/w shove it in now so we
6477 		 * can see in the trace viewer if it gets over-ridden.
6478 		 */
6479 		if (rsm->r_ts_valid &&
6480 		    bbr->rc_ts_valid &&
6481 		    bbr->rc_ts_clock_set &&
6482 		    (bbr->rc_ts_cant_be_used == 0) &&
6483 		    bbr->rc_use_ts_limit) {
6484 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6485 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6486 			if ((delivered == 0) ||
6487 			    (rtt < 1000)) {
6488 				/* Can't use the ts */
6489 				bbr_log_type_bbrupd(bbr, 61, cts,
6490 						    ts_diff,
6491 						    bbr->r_ctl.last_inbound_ts,
6492 						    rsm->r_del_ack_ts, 0,
6493 						    0, 0, 0, delivered);
6494 			} else {
6495 				ts_bw = (uint64_t)delivered;
6496 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6497 				ts_bw /= ts_diff;
6498 				bbr_log_type_bbrupd(bbr, 62, cts,
6499 						    (ts_bw >> 32),
6500 						    (ts_bw & 0xffffffff), 0, 0,
6501 						    0, 0, ts_diff, delivered);
6502 				if ((bbr->ts_can_raise) &&
6503 				    (ts_bw > bw)) {
6504 					bbr_log_type_bbrupd(bbr, 8, cts,
6505 							    delivered,
6506 							    ts_diff,
6507 							    (bw >> 32),
6508 							    (bw & 0x00000000ffffffff),
6509 							    0, 0, 0, 0);
6510 					bw = ts_bw;
6511 				} else if (ts_bw && (ts_bw < bw)) {
6512 					bbr_log_type_bbrupd(bbr, 7, cts,
6513 							    delivered,
6514 							    ts_diff,
6515 							    (bw >> 32),
6516 							    (bw & 0x00000000ffffffff),
6517 							    0, 0, 0, 0);
6518 					bw = ts_bw;
6519 				}
6520 			}
6521 		}
6522 		if (rsm->r_first_sent_time &&
6523 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6524 			uint64_t sbw, sti;
6525 			/*
6526 			 * We use what was in flight at the time of our
6527 			 * send  and the size of this send to figure
6528 			 * out what we have been sending at (amount).
6529 			 * For the time we take from the time of
6530 			 * the send of the first send outstanding
6531 			 * until this send plus this sends pacing
6532 			 * time. This gives us a good calculation
6533 			 * as to the rate we have been sending at.
6534 			 */
6535 
6536 			sbw = (uint64_t)(rsm->r_flight_at_send);
6537 			sbw *= (uint64_t)USECS_IN_SECOND;
6538 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6539 			sti += rsm->r_pacing_delay;
6540 			sbw /= sti;
6541 			if (sbw < bw) {
6542 				bbr_log_type_bbrupd(bbr, 6, cts,
6543 						    delivered,
6544 						    (uint32_t)sti,
6545 						    (bw >> 32),
6546 						    (uint32_t)bw,
6547 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6548 						    (uint32_t)sbw);
6549 				bw = sbw;
6550 			}
6551 		}
6552 		/* Use the google algorithm for b/w measurements */
6553 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6554 		if ((rsm->r_app_limited == 0) ||
6555 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6556 			tcp_bbr_commit_bw(bbr, cts);
6557 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6558 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6559 		}
6560 	}
6561 }
6562 
6563 static void
6564 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6565 {
6566 	if (bbr->rc_in_persist == 0) {
6567 		/* We log only when not in persist */
6568 		/* Translate to a Bytes Per Second */
6569 		uint64_t tim, bw;
6570 		uint32_t delivered;
6571 		int no_apply = 0;
6572 
6573 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6574 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6575 		else
6576 			tim = 1;
6577 		/*
6578 		 * Now that we have processed the tim (skipping the sample
6579 		 * or possibly updating the time, go ahead and
6580 		 * calculate the cdr.
6581 		 */
6582 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6583 		bw = (uint64_t)delivered;
6584 		bw *= (uint64_t)USECS_IN_SECOND;
6585 		bw /= tim;
6586 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6587 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6588 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6589 
6590 			no_apply = 1;
6591 		}
6592 		/*
6593 		 * If we are using this b/w shove it in now so we
6594 		 * can see in the trace viewer if it gets over-ridden.
6595 		 */
6596 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6597 		/* Gate by the sending rate */
6598 		if (rsm->r_first_sent_time &&
6599 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6600 			uint64_t sbw, sti;
6601 			/*
6602 			 * We use what was in flight at the time of our
6603 			 * send  and the size of this send to figure
6604 			 * out what we have been sending at (amount).
6605 			 * For the time we take from the time of
6606 			 * the send of the first send outstanding
6607 			 * until this send plus this sends pacing
6608 			 * time. This gives us a good calculation
6609 			 * as to the rate we have been sending at.
6610 			 */
6611 
6612 			sbw = (uint64_t)(rsm->r_flight_at_send);
6613 			sbw *= (uint64_t)USECS_IN_SECOND;
6614 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6615 			sti += rsm->r_pacing_delay;
6616 			sbw /= sti;
6617 			if (sbw < bw) {
6618 				bbr_log_type_bbrupd(bbr, 6, cts,
6619 						    delivered,
6620 						    (uint32_t)sti,
6621 						    (bw >> 32),
6622 						    (uint32_t)bw,
6623 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6624 						    (uint32_t)sbw);
6625 				bw = sbw;
6626 			}
6627 			if ((sti > tim) &&
6628 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6629 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6630 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6631 				no_apply = 1;
6632 			} else
6633 				no_apply = 0;
6634 		}
6635 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6636 		if ((no_apply == 0) &&
6637 		    ((rsm->r_app_limited == 0) ||
6638 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6639 			tcp_bbr_commit_bw(bbr, cts);
6640 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6641 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6642 		}
6643 	}
6644 }
6645 
6646 static void
6647 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6648     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6649 {
6650 	uint64_t old_rttprop;
6651 
6652 	/* Update our delivery time and amount */
6653 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6654 	bbr->r_ctl.rc_del_time = cts;
6655 	if (rtt == 0) {
6656 		/*
6657 		 * 0 means its a retransmit, for now we don't use these for
6658 		 * the rest of BBR.
6659 		 */
6660 		return;
6661 	}
6662 	if ((bbr->rc_use_google == 0) &&
6663 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6664 	    (match != BBR_RTT_BY_TIMESTAMP)){
6665 		/*
6666 		 * We get a lot of rtt updates, lets not pay attention to
6667 		 * any that are not an exact match. That way we don't have
6668 		 * to worry about timestamps and the whole nonsense of
6669 		 * unsure if its a retransmission etc (if we ever had the
6670 		 * timestamp fixed to always have the last thing sent this
6671 		 * would not be a issue).
6672 		 */
6673 		return;
6674 	}
6675 	if ((bbr_no_retran && bbr->rc_use_google) &&
6676 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6677 	    (match != BBR_RTT_BY_TIMESTAMP)){
6678 		/*
6679 		 * We only do measurements in google mode
6680 		 * with bbr_no_retran on for sure things.
6681 		 */
6682 		return;
6683 	}
6684 	/* Only update srtt if we know by exact match */
6685 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6686 	if (ack_type == BBR_CUM_ACKED)
6687 		bbr->rc_ack_is_cumack = 1;
6688 	else
6689 		bbr->rc_ack_is_cumack = 0;
6690 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6691 	/*
6692 	 * Note the following code differs to the original
6693 	 * BBR spec. It calls for <= not <. However after a
6694 	 * long discussion in email with Neal, he acknowledged
6695 	 * that it should be < than so that we will have flows
6696 	 * going into probe-rtt (we were seeing cases where that
6697 	 * did not happen and caused ugly things to occur). We
6698 	 * have added this agreed upon fix to our code base.
6699 	 */
6700 	if (rtt < old_rttprop) {
6701 		/* Update when we last saw a rtt drop */
6702 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6703 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6704 	}
6705 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6706 	    match, rsm->r_start, rsm->r_flags);
6707 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6708 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6709 		/*
6710 		 * The RTT-prop moved, reset the target (may be a
6711 		 * nop for some states).
6712 		 */
6713 		bbr_set_state_target(bbr, __LINE__);
6714 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6715 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6716 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6717 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6718 			/* It went up */
6719 			bbr_check_probe_rtt_limits(bbr, cts);
6720 	}
6721 	if ((bbr->rc_use_google == 0) &&
6722 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6723 		/*
6724 		 * We don't do b/w update with
6725 		 * these since they are not really
6726 		 * reliable.
6727 		 */
6728 		return;
6729 	}
6730 	if (bbr->r_ctl.r_app_limited_until &&
6731 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6732 		/* We are no longer app-limited */
6733 		bbr->r_ctl.r_app_limited_until = 0;
6734 	}
6735 	if (bbr->rc_use_google) {
6736 		bbr_google_measurement(bbr, rsm, rtt, cts);
6737 	} else {
6738 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6739 	}
6740 }
6741 
6742 /*
6743  * Convert a timestamp that the main stack
6744  * uses (milliseconds) into one that bbr uses
6745  * (microseconds). Return that converted timestamp.
6746  */
6747 static uint32_t
6748 bbr_ts_convert(uint32_t cts) {
6749 	uint32_t sec, msec;
6750 
6751 	sec = cts / MS_IN_USEC;
6752 	msec = cts - (MS_IN_USEC * sec);
6753 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6754 }
6755 
6756 /*
6757  * Return 0 if we did not update the RTT time, return
6758  * 1 if we did.
6759  */
6760 static int
6761 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6762     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6763 {
6764 	int32_t i;
6765 	uint32_t t, uts = 0;
6766 
6767 	if ((rsm->r_flags & BBR_ACKED) ||
6768 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6769 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6770 		/* Already done */
6771 		return (0);
6772 	}
6773 	if (rsm->r_rtt_not_allowed) {
6774 		/* Not allowed */
6775 		return (0);
6776 	}
6777 	if (rsm->r_rtr_cnt == 1) {
6778 		/*
6779 		 * Only one transmit. Hopefully the normal case.
6780 		 */
6781 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6782 			t = cts - rsm->r_tim_lastsent[0];
6783 		else
6784 			t = 1;
6785 		if ((int)t <= 0)
6786 			t = 1;
6787 		bbr->r_ctl.rc_last_rtt = t;
6788 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6789 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6790 		return (1);
6791 	}
6792 	/* Convert to usecs */
6793 	if ((bbr_can_use_ts_for_rtt == 1) &&
6794 	    (bbr->rc_use_google == 1) &&
6795 	    (ack_type == BBR_CUM_ACKED) &&
6796 	    (to->to_flags & TOF_TS) &&
6797 	    (to->to_tsecr != 0)) {
6798 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6799 		if (t < 1)
6800 			t = 1;
6801 		t *= MS_IN_USEC;
6802 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6803 				    BBR_RTT_BY_TIMESTAMP,
6804 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6805 				    ack_type, to);
6806 		return (1);
6807 	}
6808 	uts = bbr_ts_convert(to->to_tsecr);
6809 	if ((to->to_flags & TOF_TS) &&
6810 	    (to->to_tsecr != 0) &&
6811 	    (ack_type == BBR_CUM_ACKED) &&
6812 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6813 		/*
6814 		 * Now which timestamp does it match? In this block the ACK
6815 		 * may be coming from a previous transmission.
6816 		 */
6817 		uint32_t fudge;
6818 
6819 		fudge = BBR_TIMER_FUDGE;
6820 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6821 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6822 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6823 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6824 					t = cts - rsm->r_tim_lastsent[i];
6825 				else
6826 					t = 1;
6827 				if ((int)t <= 0)
6828 					t = 1;
6829 				bbr->r_ctl.rc_last_rtt = t;
6830 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6831 						    rsm->r_tim_lastsent[i], ack_type, to);
6832 				if ((i + 1) < rsm->r_rtr_cnt) {
6833 					/* Likely */
6834 					return (0);
6835 				} else if (rsm->r_flags & BBR_TLP) {
6836 					bbr->rc_tlp_rtx_out = 0;
6837 				}
6838 				return (1);
6839 			}
6840 		}
6841 		/* Fall through if we can't find a matching timestamp */
6842 	}
6843 	/*
6844 	 * Ok its a SACK block that we retransmitted. or a windows
6845 	 * machine without timestamps. We can tell nothing from the
6846 	 * time-stamp since its not there or the time the peer last
6847 	 * recieved a segment that moved forward its cum-ack point.
6848 	 *
6849 	 * Lets look at the last retransmit and see what we can tell
6850 	 * (with BBR for space we only keep 2 note we have to keep
6851 	 * at least 2 so the map can not be condensed more).
6852 	 */
6853 	i = rsm->r_rtr_cnt - 1;
6854 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6855 		t = cts - rsm->r_tim_lastsent[i];
6856 	else
6857 		goto not_sure;
6858 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6859 		/*
6860 		 * We retransmitted and the ack came back in less
6861 		 * than the smallest rtt we have observed in the
6862 		 * windowed rtt. We most likey did an improper
6863 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6864 		 * the rack-draft.
6865 		 *
6866 		 * Use the prior transmission to update all the
6867 		 * information as long as there is only one prior
6868 		 * transmission.
6869 		 */
6870 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6871 #ifdef BBR_INVARIANTS
6872 			if (rsm->r_rtr_cnt == 1)
6873 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6874 #endif
6875 			i = rsm->r_rtr_cnt - 2;
6876 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6877 				t = cts - rsm->r_tim_lastsent[i];
6878 			else
6879 				t = 1;
6880 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6881 					    rsm->r_tim_lastsent[i], ack_type, to);
6882 			return (0);
6883 		} else {
6884 			/*
6885 			 * Too many prior transmissions, just
6886 			 * updated BBR delivered
6887 			 */
6888 not_sure:
6889 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6890 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6891 		}
6892 	} else {
6893 		/*
6894 		 * We retransmitted it and the retransmit did the
6895 		 * job.
6896 		 */
6897 		if (rsm->r_flags & BBR_TLP)
6898 			bbr->rc_tlp_rtx_out = 0;
6899 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6900 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6901 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6902 		else
6903 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6904 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6905 		return (1);
6906 	}
6907 	return (0);
6908 }
6909 
6910 /*
6911  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6912  */
6913 static void
6914 bbr_log_sack_passed(struct tcpcb *tp,
6915     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6916 {
6917 	struct bbr_sendmap *nrsm;
6918 
6919 	nrsm = rsm;
6920 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6921 	    bbr_head, r_tnext) {
6922 		if (nrsm == rsm) {
6923 			/* Skip original segment he is acked */
6924 			continue;
6925 		}
6926 		if (nrsm->r_flags & BBR_ACKED) {
6927 			/* Skip ack'd segments */
6928 			continue;
6929 		}
6930 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6931 			/*
6932 			 * We found one that is already marked
6933 			 * passed, we have been here before and
6934 			 * so all others below this are marked.
6935 			 */
6936 			break;
6937 		}
6938 		BBR_STAT_INC(bbr_sack_passed);
6939 		nrsm->r_flags |= BBR_SACK_PASSED;
6940 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6941 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6942 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6943 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6944 			nrsm->r_flags |= BBR_MARKED_LOST;
6945 		}
6946 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6947 	}
6948 }
6949 
6950 /*
6951  * Returns the number of bytes that were
6952  * newly ack'd by sack blocks.
6953  */
6954 static uint32_t
6955 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6956     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6957 {
6958 	int32_t times = 0;
6959 	uint32_t start, end, changed = 0;
6960 	struct bbr_sendmap *rsm, *nrsm;
6961 	int32_t used_ref = 1;
6962 	uint8_t went_back = 0, went_fwd = 0;
6963 
6964 	start = sack->start;
6965 	end = sack->end;
6966 	rsm = *prsm;
6967 	if (rsm == NULL)
6968 		used_ref = 0;
6969 
6970 	/* Do we locate the block behind where we last were? */
6971 	if (rsm && SEQ_LT(start, rsm->r_start)) {
6972 		went_back = 1;
6973 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
6974 			if (SEQ_GEQ(start, rsm->r_start) &&
6975 			    SEQ_LT(start, rsm->r_end)) {
6976 				goto do_rest_ofb;
6977 			}
6978 		}
6979 	}
6980 start_at_beginning:
6981 	went_fwd = 1;
6982 	/*
6983 	 * Ok lets locate the block where this guy is fwd from rsm (if its
6984 	 * set)
6985 	 */
6986 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
6987 		if (SEQ_GEQ(start, rsm->r_start) &&
6988 		    SEQ_LT(start, rsm->r_end)) {
6989 			break;
6990 		}
6991 	}
6992 do_rest_ofb:
6993 	if (rsm == NULL) {
6994 		/*
6995 		 * This happens when we get duplicate sack blocks with the
6996 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
6997 		 * will not change there location so we would just start at
6998 		 * the end of the first one and get lost.
6999 		 */
7000 		if (tp->t_flags & TF_SENTFIN) {
7001 			/*
7002 			 * Check to see if we have not logged the FIN that
7003 			 * went out.
7004 			 */
7005 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7006 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7007 				/*
7008 				 * Ok we did not get the FIN logged.
7009 				 */
7010 				nrsm->r_end++;
7011 				rsm = nrsm;
7012 				goto do_rest_ofb;
7013 			}
7014 		}
7015 		if (times == 1) {
7016 #ifdef BBR_INVARIANTS
7017 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7018 			    tp, bbr, sack, to, prsm);
7019 #else
7020 			goto out;
7021 #endif
7022 		}
7023 		times++;
7024 		BBR_STAT_INC(bbr_sack_proc_restart);
7025 		rsm = NULL;
7026 		goto start_at_beginning;
7027 	}
7028 	/* Ok we have an ACK for some piece of rsm */
7029 	if (rsm->r_start != start) {
7030 		/*
7031 		 * Need to split this in two pieces the before and after.
7032 		 */
7033 		if (bbr_sack_mergable(rsm, start, end))
7034 			nrsm = bbr_alloc_full_limit(bbr);
7035 		else
7036 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7037 		if (nrsm == NULL) {
7038 			/* We could not allocate ignore the sack */
7039 			struct sackblk blk;
7040 
7041 			blk.start = start;
7042 			blk.end = end;
7043 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7044 			goto out;
7045 		}
7046 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7047 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7048 		if (rsm->r_in_tmap) {
7049 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7050 			nrsm->r_in_tmap = 1;
7051 		}
7052 		rsm->r_flags &= (~BBR_HAS_FIN);
7053 		rsm = nrsm;
7054 	}
7055 	if (SEQ_GEQ(end, rsm->r_end)) {
7056 		/*
7057 		 * The end of this block is either beyond this guy or right
7058 		 * at this guy.
7059 		 */
7060 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7061 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7062 			changed += (rsm->r_end - rsm->r_start);
7063 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7064 			bbr_log_sack_passed(tp, bbr, rsm);
7065 			if (rsm->r_flags & BBR_MARKED_LOST) {
7066 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7067 			}
7068 			/* Is Reordering occuring? */
7069 			if (rsm->r_flags & BBR_SACK_PASSED) {
7070 				BBR_STAT_INC(bbr_reorder_seen);
7071 				bbr->r_ctl.rc_reorder_ts = cts;
7072 				if (rsm->r_flags & BBR_MARKED_LOST) {
7073 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7074 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7075 						/* LT sampling also needs adjustment */
7076 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7077 				}
7078 			}
7079 			rsm->r_flags |= BBR_ACKED;
7080 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7081 			if (rsm->r_in_tmap) {
7082 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7083 				rsm->r_in_tmap = 0;
7084 			}
7085 		}
7086 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7087 		if (end == rsm->r_end) {
7088 			/* This block only - done */
7089 			goto out;
7090 		}
7091 		/* There is more not coverend by this rsm move on */
7092 		start = rsm->r_end;
7093 		nrsm = TAILQ_NEXT(rsm, r_next);
7094 		rsm = nrsm;
7095 		times = 0;
7096 		goto do_rest_ofb;
7097 	}
7098 	if (rsm->r_flags & BBR_ACKED) {
7099 		/* Been here done that */
7100 		goto out;
7101 	}
7102 	/* Ok we need to split off this one at the tail */
7103 	if (bbr_sack_mergable(rsm, start, end))
7104 		nrsm = bbr_alloc_full_limit(bbr);
7105 	else
7106 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7107 	if (nrsm == NULL) {
7108 		/* failed XXXrrs what can we do but loose the sack info? */
7109 		struct sackblk blk;
7110 
7111 		blk.start = start;
7112 		blk.end = end;
7113 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7114 		goto out;
7115 	}
7116 	/* Clone it */
7117 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7118 	/* The sack block does not cover this guy fully */
7119 	rsm->r_flags &= (~BBR_HAS_FIN);
7120 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7121 	if (rsm->r_in_tmap) {
7122 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7123 		nrsm->r_in_tmap = 1;
7124 	}
7125 	nrsm->r_dupack = 0;
7126 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7127 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7128 	changed += (rsm->r_end - rsm->r_start);
7129 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7130 	bbr_log_sack_passed(tp, bbr, rsm);
7131 	/* Is Reordering occuring? */
7132 	if (rsm->r_flags & BBR_MARKED_LOST) {
7133 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7134 	}
7135 	if (rsm->r_flags & BBR_SACK_PASSED) {
7136 		BBR_STAT_INC(bbr_reorder_seen);
7137 		bbr->r_ctl.rc_reorder_ts = cts;
7138 		if (rsm->r_flags & BBR_MARKED_LOST) {
7139 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7140 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7141 				/* LT sampling also needs adjustment */
7142 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7143 		}
7144 	}
7145 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7146 	rsm->r_flags |= BBR_ACKED;
7147 	if (rsm->r_in_tmap) {
7148 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7149 		rsm->r_in_tmap = 0;
7150 	}
7151 out:
7152 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7153 		/*
7154 		 * Now can we merge this newly acked
7155 		 * block with either the previous or
7156 		 * next block?
7157 		 */
7158 		nrsm = TAILQ_NEXT(rsm, r_next);
7159 		if (nrsm &&
7160 		    (nrsm->r_flags & BBR_ACKED)) {
7161 			/* yep this and next can be merged */
7162 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7163 		}
7164 		/* Now what about the previous? */
7165 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7166 		if (nrsm &&
7167 		    (nrsm->r_flags & BBR_ACKED)) {
7168 			/* yep the previous and this can be merged */
7169 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7170 		}
7171 	}
7172 	if (used_ref == 0) {
7173 		BBR_STAT_INC(bbr_sack_proc_all);
7174 	} else {
7175 		BBR_STAT_INC(bbr_sack_proc_short);
7176 	}
7177 	if (went_fwd && went_back) {
7178 		BBR_STAT_INC(bbr_sack_search_both);
7179 	} else if (went_fwd) {
7180 		BBR_STAT_INC(bbr_sack_search_fwd);
7181 	} else if (went_back) {
7182 		BBR_STAT_INC(bbr_sack_search_back);
7183 	}
7184 	/* Save off where the next seq is */
7185 	if (rsm)
7186 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7187 	else
7188 		bbr->r_ctl.rc_sacklast = NULL;
7189 	*prsm = rsm;
7190 	return (changed);
7191 }
7192 
7193 static void inline
7194 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7195 {
7196 	struct bbr_sendmap *tmap;
7197 
7198 	BBR_STAT_INC(bbr_reneges_seen);
7199 	tmap = NULL;
7200 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7201 		/* Its no longer sacked, mark it so */
7202 		uint32_t oflags;
7203 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7204 #ifdef BBR_INVARIANTS
7205 		if (rsm->r_in_tmap) {
7206 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7207 			    bbr, rsm, rsm->r_flags);
7208 		}
7209 #endif
7210 		oflags = rsm->r_flags;
7211 		if (rsm->r_flags & BBR_MARKED_LOST) {
7212 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7213 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7214 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7215 				/* LT sampling also needs adjustment */
7216 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7217 		}
7218 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7219 		rsm->r_flags |= BBR_WAS_RENEGED;
7220 		rsm->r_flags |= BBR_RXT_CLEARED;
7221 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7222 		/* Rebuild it into our tmap */
7223 		if (tmap == NULL) {
7224 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7225 			tmap = rsm;
7226 		} else {
7227 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7228 			tmap = rsm;
7229 		}
7230 		tmap->r_in_tmap = 1;
7231 		/*
7232 		 * XXXrrs Delivered? Should we do anything here?
7233 		 *
7234 		 * Of course we don't on a rxt timeout so maybe its ok that
7235 		 * we don't?
7236 		 *
7237 		 * For now lets not.
7238 		 */
7239 		rsm = TAILQ_NEXT(rsm, r_next);
7240 	}
7241 	/*
7242 	 * Now lets possibly clear the sack filter so we start recognizing
7243 	 * sacks that cover this area.
7244 	 */
7245 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7246 }
7247 
7248 static void
7249 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7250 {
7251 	struct tcp_bbr *bbr;
7252 	struct bbr_sendmap *rsm;
7253 	uint32_t cts;
7254 
7255 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7256 	cts = bbr->r_ctl.rc_rcvtime;
7257 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7258 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7259 		if ((rsm->r_end - rsm->r_start) <= 1) {
7260 			/* Log out the SYN completely */
7261 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7262 			rsm->r_rtr_bytes = 0;
7263 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7264 			if (rsm->r_in_tmap) {
7265 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7266 				rsm->r_in_tmap = 0;
7267 			}
7268 			if (bbr->r_ctl.rc_next == rsm) {
7269 				/* scoot along the marker */
7270 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7271 			}
7272 			if (to != NULL)
7273 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7274 			bbr_free(bbr, rsm);
7275 		} else {
7276 			/* There is more (Fast open)? strip out SYN. */
7277 			rsm->r_flags &= ~BBR_HAS_SYN;
7278 			rsm->r_start++;
7279 		}
7280 	}
7281 }
7282 
7283 /*
7284  * Returns the number of bytes that were
7285  * acknowledged by SACK blocks.
7286  */
7287 
7288 static uint32_t
7289 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7290     uint32_t *prev_acked)
7291 {
7292 	uint32_t changed, last_seq, entered_recovery = 0;
7293 	struct tcp_bbr *bbr;
7294 	struct bbr_sendmap *rsm;
7295 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7296 	register uint32_t th_ack;
7297 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7298 	uint32_t cts, acked, ack_point, sack_changed = 0;
7299 	uint32_t p_maxseg, maxseg, p_acked = 0;
7300 
7301 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7302 	if (tcp_get_flags(th) & TH_RST) {
7303 		/* We don't log resets */
7304 		return (0);
7305 	}
7306 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7307 	cts = bbr->r_ctl.rc_rcvtime;
7308 
7309 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7310 	changed = 0;
7311 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7312 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7313 	th_ack = th->th_ack;
7314 	if (SEQ_GT(th_ack, tp->snd_una)) {
7315 		acked = th_ack - tp->snd_una;
7316 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7317 		bbr->rc_tp->t_acktime = ticks;
7318 	} else
7319 		acked = 0;
7320 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7321 		/* Only sent here for sack processing */
7322 		goto proc_sack;
7323 	}
7324 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7325 		changed = th_ack - rsm->r_start;
7326 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7327 		/*
7328 		 * For the SYN incoming case we will not have called
7329 		 * tcp_output for the sending of the SYN, so there will be
7330 		 * no map. All other cases should probably be a panic.
7331 		 */
7332 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7333 			/*
7334 			 * We have a timestamp that can be used to generate
7335 			 * an initial RTT.
7336 			 */
7337 			uint32_t ts, now, rtt;
7338 
7339 			ts = bbr_ts_convert(to->to_tsecr);
7340 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7341 			rtt = now - ts;
7342 			if (rtt < 1)
7343 				rtt = 1;
7344 			bbr_log_type_bbrrttprop(bbr, rtt,
7345 						tp->iss, 0, cts,
7346 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7347 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7348 			changed = 1;
7349 			bbr->r_wanted_output = 1;
7350 			goto out;
7351 		}
7352 		goto proc_sack;
7353 	} else if (rsm == NULL) {
7354 		goto out;
7355 	}
7356 	if (changed) {
7357 		/*
7358 		 * The ACK point is advancing to th_ack, we must drop off
7359 		 * the packets in the rack log and calculate any eligble
7360 		 * RTT's.
7361 		 */
7362 		bbr->r_wanted_output = 1;
7363 more:
7364 		if (rsm == NULL) {
7365 			if (tp->t_flags & TF_SENTFIN) {
7366 				/* if we send a FIN we will not hav a map */
7367 				goto proc_sack;
7368 			}
7369 #ifdef BBR_INVARIANTS
7370 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7371 			    tp,
7372 			    th, tp->t_state, bbr,
7373 			    tp->snd_una, tp->snd_max, changed);
7374 #endif
7375 			goto proc_sack;
7376 		}
7377 	}
7378 	if (SEQ_LT(th_ack, rsm->r_start)) {
7379 		/* Huh map is missing this */
7380 #ifdef BBR_INVARIANTS
7381 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7382 		    rsm->r_start,
7383 		    th_ack, tp->t_state,
7384 		    bbr->r_state, bbr);
7385 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7386 #endif
7387 		goto proc_sack;
7388 	} else if (th_ack == rsm->r_start) {
7389 		/* None here to ack */
7390 		goto proc_sack;
7391 	}
7392 	/*
7393 	 * Clear the dup ack counter, it will
7394 	 * either be freed or if there is some
7395 	 * remaining we need to start it at zero.
7396 	 */
7397 	rsm->r_dupack = 0;
7398 	/* Now do we consume the whole thing? */
7399 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7400 		/* Its all consumed. */
7401 		uint32_t left;
7402 
7403 		if (rsm->r_flags & BBR_ACKED) {
7404 			/*
7405 			 * It was acked on the scoreboard -- remove it from
7406 			 * total
7407 			 */
7408 			p_acked += (rsm->r_end - rsm->r_start);
7409 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7410 			if (bbr->r_ctl.rc_sacked == 0)
7411 				bbr->r_ctl.rc_sacklast = NULL;
7412 		} else {
7413 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7414 			if (rsm->r_flags & BBR_MARKED_LOST) {
7415 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7416 			}
7417 			if (rsm->r_flags & BBR_SACK_PASSED) {
7418 				/*
7419 				 * There are acked segments ACKED on the
7420 				 * scoreboard further up. We are seeing
7421 				 * reordering.
7422 				 */
7423 				BBR_STAT_INC(bbr_reorder_seen);
7424 				bbr->r_ctl.rc_reorder_ts = cts;
7425 				if (rsm->r_flags & BBR_MARKED_LOST) {
7426 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7427 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7428 						/* LT sampling also needs adjustment */
7429 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7430 				}
7431 			}
7432 			rsm->r_flags &= ~BBR_MARKED_LOST;
7433 		}
7434 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7435 		rsm->r_rtr_bytes = 0;
7436 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7437 		if (rsm->r_in_tmap) {
7438 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7439 			rsm->r_in_tmap = 0;
7440 		}
7441 		if (bbr->r_ctl.rc_next == rsm) {
7442 			/* scoot along the marker */
7443 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7444 		}
7445 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7446 		/* Adjust the packet counts */
7447 		left = th_ack - rsm->r_end;
7448 		/* Free back to zone */
7449 		bbr_free(bbr, rsm);
7450 		if (left) {
7451 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7452 			goto more;
7453 		}
7454 		goto proc_sack;
7455 	}
7456 	if (rsm->r_flags & BBR_ACKED) {
7457 		/*
7458 		 * It was acked on the scoreboard -- remove it from total
7459 		 * for the part being cum-acked.
7460 		 */
7461 		p_acked += (rsm->r_end - rsm->r_start);
7462 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7463 		if (bbr->r_ctl.rc_sacked == 0)
7464 			bbr->r_ctl.rc_sacklast = NULL;
7465 	} else {
7466 		/*
7467 		 * It was acked up to th_ack point for the first time
7468 		 */
7469 		struct bbr_sendmap lrsm;
7470 
7471 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7472 		lrsm.r_end = th_ack;
7473 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7474 	}
7475 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7476 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7477 		/*
7478 		 * It was marked lost and partly ack'd now
7479 		 * for the first time. We lower the rc_lost_bytes
7480 		 * and still leave it MARKED.
7481 		 */
7482 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7483 	}
7484 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7485 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7486 	rsm->r_rtr_bytes = 0;
7487 	/* adjust packet count */
7488 	rsm->r_start = th_ack;
7489 proc_sack:
7490 	/* Check for reneging */
7491 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7492 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7493 		/*
7494 		 * The peer has moved snd_una up to the edge of this send,
7495 		 * i.e. one that it had previously acked. The only way that
7496 		 * can be true if the peer threw away data (space issues)
7497 		 * that it had previously sacked (else it would have given
7498 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7499 		 * markings here.
7500 		 *
7501 		 * Note we have to look to make sure th_ack is our
7502 		 * rsm->r_start in case we get an old ack where th_ack is
7503 		 * behind snd_una.
7504 		 */
7505 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7506 	}
7507 	if ((to->to_flags & TOF_SACK) == 0) {
7508 		/* We are done nothing left to log */
7509 		goto out;
7510 	}
7511 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7512 	if (rsm) {
7513 		last_seq = rsm->r_end;
7514 	} else {
7515 		last_seq = tp->snd_max;
7516 	}
7517 	/* Sack block processing */
7518 	if (SEQ_GT(th_ack, tp->snd_una))
7519 		ack_point = th_ack;
7520 	else
7521 		ack_point = tp->snd_una;
7522 	for (i = 0; i < to->to_nsacks; i++) {
7523 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7524 		    &sack, sizeof(sack));
7525 		sack.start = ntohl(sack.start);
7526 		sack.end = ntohl(sack.end);
7527 		if (SEQ_GT(sack.end, sack.start) &&
7528 		    SEQ_GT(sack.start, ack_point) &&
7529 		    SEQ_LT(sack.start, tp->snd_max) &&
7530 		    SEQ_GT(sack.end, ack_point) &&
7531 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7532 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7533 			    (SEQ_LT(sack.end, last_seq)) &&
7534 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7535 				/*
7536 				 * Not the last piece and its smaller than
7537 				 * 1/8th of a p_maxseg. We ignore this.
7538 				 */
7539 				BBR_STAT_INC(bbr_runt_sacks);
7540 				continue;
7541 			}
7542 			sack_blocks[num_sack_blks] = sack;
7543 			num_sack_blks++;
7544 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7545 		    SEQ_LEQ(sack.end, th_ack)) {
7546 			/*
7547 			 * Its a D-SACK block.
7548 			 */
7549 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7550 		}
7551 	}
7552 	if (num_sack_blks == 0)
7553 		goto out;
7554 	/*
7555 	 * Sort the SACK blocks so we can update the rack scoreboard with
7556 	 * just one pass.
7557 	 */
7558 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7559 				  num_sack_blks, th->th_ack);
7560 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7561 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7562 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7563 	num_sack_blks = new_sb;
7564 	if (num_sack_blks < 2) {
7565 		goto do_sack_work;
7566 	}
7567 	/* Sort the sacks */
7568 	for (i = 0; i < num_sack_blks; i++) {
7569 		for (j = i + 1; j < num_sack_blks; j++) {
7570 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7571 				sack = sack_blocks[i];
7572 				sack_blocks[i] = sack_blocks[j];
7573 				sack_blocks[j] = sack;
7574 			}
7575 		}
7576 	}
7577 	/*
7578 	 * Now are any of the sack block ends the same (yes some
7579 	 * implememtations send these)?
7580 	 */
7581 again:
7582 	if (num_sack_blks > 1) {
7583 		for (i = 0; i < num_sack_blks; i++) {
7584 			for (j = i + 1; j < num_sack_blks; j++) {
7585 				if (sack_blocks[i].end == sack_blocks[j].end) {
7586 					/*
7587 					 * Ok these two have the same end we
7588 					 * want the smallest end and then
7589 					 * throw away the larger and start
7590 					 * again.
7591 					 */
7592 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7593 						/*
7594 						 * The second block covers
7595 						 * more area use that
7596 						 */
7597 						sack_blocks[i].start = sack_blocks[j].start;
7598 					}
7599 					/*
7600 					 * Now collapse out the dup-sack and
7601 					 * lower the count
7602 					 */
7603 					for (k = (j + 1); k < num_sack_blks; k++) {
7604 						sack_blocks[j].start = sack_blocks[k].start;
7605 						sack_blocks[j].end = sack_blocks[k].end;
7606 						j++;
7607 					}
7608 					num_sack_blks--;
7609 					goto again;
7610 				}
7611 			}
7612 		}
7613 	}
7614 do_sack_work:
7615 	rsm = bbr->r_ctl.rc_sacklast;
7616 	for (i = 0; i < num_sack_blks; i++) {
7617 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7618 		if (acked) {
7619 			bbr->r_wanted_output = 1;
7620 			changed += acked;
7621 			sack_changed += acked;
7622 		}
7623 	}
7624 out:
7625 	*prev_acked = p_acked;
7626 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7627 		/*
7628 		 * Ok we have a high probability that we need to go in to
7629 		 * recovery since we have data sack'd
7630 		 */
7631 		struct bbr_sendmap *rsm;
7632 
7633 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7634 		if (rsm) {
7635 			/* Enter recovery */
7636 			entered_recovery = 1;
7637 			bbr->r_wanted_output = 1;
7638 			/*
7639 			 * When we enter recovery we need to assure we send
7640 			 * one packet.
7641 			 */
7642 			if (bbr->r_ctl.rc_resend == NULL) {
7643 				bbr->r_ctl.rc_resend = rsm;
7644 			}
7645 		}
7646 	}
7647 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7648 		/*
7649 		 * See if we need to rack-retransmit anything if so set it
7650 		 * up as the thing to resend assuming something else is not
7651 		 * already in that position.
7652 		 */
7653 		if (bbr->r_ctl.rc_resend == NULL) {
7654 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7655 		}
7656 	}
7657 	/*
7658 	 * We return the amount that changed via sack, this is used by the
7659 	 * ack-received code to augment what was changed between th_ack <->
7660 	 * snd_una.
7661 	 */
7662 	return (sack_changed);
7663 }
7664 
7665 static void
7666 bbr_strike_dupack(struct tcp_bbr *bbr)
7667 {
7668 	struct bbr_sendmap *rsm;
7669 
7670 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7671 	if (rsm && (rsm->r_dupack < 0xff)) {
7672 		rsm->r_dupack++;
7673 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7674 			bbr->r_wanted_output = 1;
7675 	}
7676 }
7677 
7678 /*
7679  * Return value of 1, we do not need to call bbr_process_data().
7680  * return value of 0, bbr_process_data can be called.
7681  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7682  * its unlocked and probably unsafe to touch the TCB.
7683  */
7684 static int
7685 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7686     struct tcpcb *tp, struct tcpopt *to,
7687     uint32_t tiwin, int32_t tlen,
7688     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7689 {
7690 	int32_t ourfinisacked = 0;
7691 	int32_t acked_amount;
7692 	uint16_t nsegs;
7693 	int32_t acked;
7694 	uint32_t lost, sack_changed = 0;
7695 	struct mbuf *mfree;
7696 	struct tcp_bbr *bbr;
7697 	uint32_t prev_acked = 0;
7698 
7699 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7700 	lost = bbr->r_ctl.rc_lost;
7701 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7702 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7703 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7704 		bbr->r_wanted_output = 1;
7705 		return (1);
7706 	}
7707 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7708 		/* Process the ack */
7709 		if (bbr->rc_in_persist)
7710 			tp->t_rxtshift = 0;
7711 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7712 			bbr_strike_dupack(bbr);
7713 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7714 	}
7715 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7716 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7717 		/*
7718 		 * Old ack, behind the last one rcv'd or a duplicate ack
7719 		 * with SACK info.
7720 		 */
7721 		if (th->th_ack == tp->snd_una) {
7722 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7723 			if (bbr->r_state == TCPS_SYN_SENT) {
7724 				/*
7725 				 * Special case on where we sent SYN. When
7726 				 * the SYN-ACK is processed in syn_sent
7727 				 * state it bumps the snd_una. This causes
7728 				 * us to hit here even though we did ack 1
7729 				 * byte.
7730 				 *
7731 				 * Go through the nothing left case so we
7732 				 * send data.
7733 				 */
7734 				goto nothing_left;
7735 			}
7736 		}
7737 		return (0);
7738 	}
7739 	/*
7740 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7741 	 * something we sent.
7742 	 */
7743 	if (tp->t_flags & TF_NEEDSYN) {
7744 		/*
7745 		 * T/TCP: Connection was half-synchronized, and our SYN has
7746 		 * been ACK'd (so connection is now fully synchronized).  Go
7747 		 * to non-starred state, increment snd_una for ACK of SYN,
7748 		 * and check if we can do window scaling.
7749 		 */
7750 		tp->t_flags &= ~TF_NEEDSYN;
7751 		tp->snd_una++;
7752 		/* Do window scaling? */
7753 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7754 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7755 			tp->rcv_scale = tp->request_r_scale;
7756 			/* Send window already scaled. */
7757 		}
7758 	}
7759 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7760 
7761 	acked = BYTES_THIS_ACK(tp, th);
7762 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7763 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7764 
7765 	/*
7766 	 * If we just performed our first retransmit, and the ACK arrives
7767 	 * within our recovery window, then it was a mistake to do the
7768 	 * retransmit in the first place.  Recover our original cwnd and
7769 	 * ssthresh, and proceed to transmit where we left off.
7770 	 */
7771 	if (tp->t_flags & TF_PREVVALID) {
7772 		tp->t_flags &= ~TF_PREVVALID;
7773 		if (tp->t_rxtshift == 1 &&
7774 		    (int)(ticks - tp->t_badrxtwin) < 0)
7775 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7776 	}
7777 	SOCKBUF_LOCK(&so->so_snd);
7778 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7779 	tp->snd_wnd -= acked_amount;
7780 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7781 	/* NB: sowwakeup_locked() does an implicit unlock. */
7782 	sowwakeup_locked(so);
7783 	m_freem(mfree);
7784 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7785 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7786 	}
7787 	tp->snd_una = th->th_ack;
7788 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7789 	if (IN_RECOVERY(tp->t_flags)) {
7790 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7791 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7792 			tcp_bbr_partialack(tp);
7793 		} else {
7794 			bbr_post_recovery(tp);
7795 		}
7796 	}
7797 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7798 		tp->snd_recover = tp->snd_una;
7799 	}
7800 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7801 		tp->snd_nxt = tp->snd_max;
7802 	}
7803 	if (tp->snd_una == tp->snd_max) {
7804 		/* Nothing left outstanding */
7805 nothing_left:
7806 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7807 		if (sbavail(&so->so_snd) == 0)
7808 			bbr->rc_tp->t_acktime = 0;
7809 		if ((sbused(&so->so_snd) == 0) &&
7810 		    (tp->t_flags & TF_SENTFIN)) {
7811 			ourfinisacked = 1;
7812 		}
7813 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7814 		if (bbr->rc_in_persist == 0) {
7815 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7816 		}
7817 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7818 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7819 		/*
7820 		 * We invalidate the last ack here since we
7821 		 * don't want to transfer forward the time
7822 		 * for our sum's calculations.
7823 		 */
7824 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7825 		    (sbavail(&so->so_snd) == 0) &&
7826 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7827 			/*
7828 			 * The socket was gone and the peer sent data, time
7829 			 * to reset him.
7830 			 */
7831 			*ret_val = 1;
7832 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7833 			/* tcp_close will kill the inp pre-log the Reset */
7834 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7835 			tp = tcp_close(tp);
7836 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7837 			BBR_STAT_INC(bbr_dropped_af_data);
7838 			return (1);
7839 		}
7840 		/* Set need output so persist might get set */
7841 		bbr->r_wanted_output = 1;
7842 	}
7843 	if (ofia)
7844 		*ofia = ourfinisacked;
7845 	return (0);
7846 }
7847 
7848 static void
7849 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7850 {
7851 	if (bbr->rc_in_persist == 0) {
7852 		bbr_timer_cancel(bbr, __LINE__, cts);
7853 		bbr->r_ctl.rc_last_delay_val = 0;
7854 		tp->t_rxtshift = 0;
7855 		bbr->rc_in_persist = 1;
7856 		bbr->r_ctl.rc_went_idle_time = cts;
7857 		/* We should be capped when rw went to 0 but just in case */
7858 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7859 		/* Time freezes for the state, so do the accounting now */
7860 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7861 			uint32_t time_in;
7862 
7863 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7864 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7865 				int32_t idx;
7866 
7867 				idx = bbr_state_val(bbr);
7868 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7869 			} else {
7870 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7871 			}
7872 		}
7873 		bbr->r_ctl.rc_bbr_state_time = cts;
7874 	}
7875 }
7876 
7877 static void
7878 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7879 {
7880 	/*
7881 	 * Note that if idle time does not exceed our
7882 	 * threshold, we do nothing continuing the state
7883 	 * transitions we were last walking through.
7884 	 */
7885 	if (idle_time >= bbr_idle_restart_threshold) {
7886 		if (bbr->rc_use_idle_restart) {
7887 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7888 			/*
7889 			 * Set our target using BBR_UNIT, so
7890 			 * we increase at a dramatic rate but
7891 			 * we stop when we get the pipe
7892 			 * full again for our current b/w estimate.
7893 			 */
7894 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7895 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7896 			bbr_set_state_target(bbr, __LINE__);
7897 			/* Now setup our gains to ramp up */
7898 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7899 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7900 			bbr_log_type_statechange(bbr, cts, __LINE__);
7901 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7902 			bbr_substate_change(bbr, cts, __LINE__, 1);
7903 		}
7904 	}
7905 }
7906 
7907 static void
7908 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7909 {
7910 	uint32_t idle_time;
7911 
7912 	if (bbr->rc_in_persist == 0)
7913 		return;
7914 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7915 	bbr->rc_in_persist = 0;
7916 	bbr->rc_hit_state_1 = 0;
7917 	bbr->r_ctl.rc_del_time = cts;
7918 	/*
7919 	 * We invalidate the last ack here since we
7920 	 * don't want to transfer forward the time
7921 	 * for our sum's calculations.
7922 	 */
7923 	if (tcp_in_hpts(bbr->rc_tp)) {
7924 		tcp_hpts_remove(bbr->rc_tp);
7925 		bbr->rc_timer_first = 0;
7926 		bbr->r_ctl.rc_hpts_flags = 0;
7927 		bbr->r_ctl.rc_last_delay_val = 0;
7928 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7929 		bbr->r_agg_early_set = 0;
7930 		bbr->r_ctl.rc_agg_early = 0;
7931 	}
7932 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7933 	if (idle_time >= bbr_rtt_probe_time) {
7934 		/*
7935 		 * This qualifies as a RTT_PROBE session since we drop the
7936 		 * data outstanding to nothing and waited more than
7937 		 * bbr_rtt_probe_time.
7938 		 */
7939 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7940 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7941 	}
7942 	tp->t_rxtshift = 0;
7943 	/*
7944 	 * If in probeBW and we have persisted more than an RTT lets do
7945 	 * special handling.
7946 	 */
7947 	/* Force a time based epoch */
7948 	bbr_set_epoch(bbr, cts, __LINE__);
7949 	/*
7950 	 * Setup the lost so we don't count anything against the guy
7951 	 * we have been stuck with during persists.
7952 	 */
7953 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7954 	/* Time un-freezes for the state */
7955 	bbr->r_ctl.rc_bbr_state_time = cts;
7956 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7957 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7958 		/*
7959 		 * If we are going back to probe-bw
7960 		 * or probe_rtt, we may need to possibly
7961 		 * do a fast restart.
7962 		 */
7963 		bbr_restart_after_idle(bbr, cts, idle_time);
7964 	}
7965 }
7966 
7967 static void
7968 bbr_collapsed_window(struct tcp_bbr *bbr)
7969 {
7970 	/*
7971 	 * Now we must walk the
7972 	 * send map and divide the
7973 	 * ones left stranded. These
7974 	 * guys can't cause us to abort
7975 	 * the connection and are really
7976 	 * "unsent". However if a buggy
7977 	 * client actually did keep some
7978 	 * of the data i.e. collapsed the win
7979 	 * and refused to ack and then opened
7980 	 * the win and acked that data. We would
7981 	 * get into an ack war, the simplier
7982 	 * method then of just pretending we
7983 	 * did not send those segments something
7984 	 * won't work.
7985 	 */
7986 	struct bbr_sendmap *rsm, *nrsm;
7987 	tcp_seq max_seq;
7988 	uint32_t maxseg;
7989 	int can_split = 0;
7990 	int fnd = 0;
7991 
7992 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
7993 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
7994 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
7995 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
7996 		/* Find the first seq past or at maxseq */
7997 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
7998 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
7999 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8000 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8001 			fnd = 1;
8002 			break;
8003 		}
8004 	}
8005 	bbr->rc_has_collapsed = 0;
8006 	if (!fnd) {
8007 		/* Nothing to do strange */
8008 		return;
8009 	}
8010 	/*
8011 	 * Now can we split?
8012 	 *
8013 	 * We don't want to split if splitting
8014 	 * would generate too many small segments
8015 	 * less we let an attacker fragment our
8016 	 * send_map and leave us out of memory.
8017 	 */
8018 	if ((max_seq != rsm->r_start) &&
8019 	    (max_seq != rsm->r_end)){
8020 		/* can we split? */
8021 		int res1, res2;
8022 
8023 		res1 = max_seq - rsm->r_start;
8024 		res2 = rsm->r_end - max_seq;
8025 		if ((res1 >= (maxseg/8)) &&
8026 		    (res2 >= (maxseg/8))) {
8027 			/* No small pieces here */
8028 			can_split = 1;
8029 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8030 			/* We are under the limit */
8031 			can_split = 1;
8032 		}
8033 	}
8034 	/* Ok do we need to split this rsm? */
8035 	if (max_seq == rsm->r_start) {
8036 		/* It's this guy no split required */
8037 		nrsm = rsm;
8038 	} else if (max_seq == rsm->r_end) {
8039 		/* It's the next one no split required. */
8040 		nrsm = TAILQ_NEXT(rsm, r_next);
8041 		if (nrsm == NULL) {
8042 			/* Huh? */
8043 			return;
8044 		}
8045 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8046 		/* yep we need to split it */
8047 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8048 		if (nrsm == NULL) {
8049 			/* failed XXXrrs what can we do mark the whole? */
8050 			nrsm = rsm;
8051 			goto no_split;
8052 		}
8053 		/* Clone it */
8054 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8055 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8056 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8057 		if (rsm->r_in_tmap) {
8058 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8059 			nrsm->r_in_tmap = 1;
8060 		}
8061 	} else {
8062 		/*
8063 		 * Split not allowed just start here just
8064 		 * use this guy.
8065 		 */
8066 		nrsm = rsm;
8067 	}
8068 no_split:
8069 	BBR_STAT_INC(bbr_collapsed_win);
8070 	/* reuse fnd as a count */
8071 	fnd = 0;
8072 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8073 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8074 		fnd++;
8075 		bbr->rc_has_collapsed = 1;
8076 	}
8077 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8078 }
8079 
8080 static void
8081 bbr_un_collapse_window(struct tcp_bbr *bbr)
8082 {
8083 	struct bbr_sendmap *rsm;
8084 	int cleared = 0;
8085 
8086 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8087 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8088 			/* Clear the flag */
8089 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8090 			cleared++;
8091 		} else
8092 			break;
8093 	}
8094 	bbr_log_type_rwnd_collapse(bbr,
8095 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8096 	bbr->rc_has_collapsed = 0;
8097 }
8098 
8099 /*
8100  * Return value of 1, the TCB is unlocked and most
8101  * likely gone, return value of 0, the TCB is still
8102  * locked.
8103  */
8104 static int
8105 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8106     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8107     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8108 {
8109 	/*
8110 	 * Update window information. Don't look at window if no ACK: TAC's
8111 	 * send garbage on first SYN.
8112 	 */
8113 	uint16_t nsegs;
8114 	int32_t tfo_syn;
8115 	struct tcp_bbr *bbr;
8116 
8117 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8118 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8119 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8120 	if ((thflags & TH_ACK) &&
8121 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8122 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8123 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8124 		/* keep track of pure window updates */
8125 		if (tlen == 0 &&
8126 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8127 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8128 		tp->snd_wnd = tiwin;
8129 		tp->snd_wl1 = th->th_seq;
8130 		tp->snd_wl2 = th->th_ack;
8131 		if (tp->snd_wnd > tp->max_sndwnd)
8132 			tp->max_sndwnd = tp->snd_wnd;
8133 		bbr->r_wanted_output = 1;
8134 	} else if (thflags & TH_ACK) {
8135 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8136 			tp->snd_wnd = tiwin;
8137 			tp->snd_wl1 = th->th_seq;
8138 			tp->snd_wl2 = th->th_ack;
8139 		}
8140 	}
8141 	if (tp->snd_wnd < ctf_outstanding(tp))
8142 		/* The peer collapsed its window on us */
8143 		bbr_collapsed_window(bbr);
8144  	else if (bbr->rc_has_collapsed)
8145 		bbr_un_collapse_window(bbr);
8146 	/* Was persist timer active and now we have window space? */
8147 	if ((bbr->rc_in_persist != 0) &&
8148 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8149 				bbr_minseg(bbr)))) {
8150 		/*
8151 		 * Make the rate persist at end of persist mode if idle long
8152 		 * enough
8153 		 */
8154 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8155 
8156 		/* Make sure we output to start the timer */
8157 		bbr->r_wanted_output = 1;
8158 	}
8159 	/* Do we need to enter persist? */
8160 	if ((bbr->rc_in_persist == 0) &&
8161 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8162 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8163 	    (tp->snd_max == tp->snd_una) &&
8164 	    sbavail(&so->so_snd) &&
8165 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8166 		/* No send window.. we must enter persist */
8167 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8168 	}
8169 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8170 		m_freem(m);
8171 		return (0);
8172 	}
8173 	/*
8174 	 * We don't support urgent data but
8175 	 * drag along the up just to make sure
8176 	 * if there is a stack switch no one
8177 	 * is surprised.
8178 	 */
8179 	tp->rcv_up = tp->rcv_nxt;
8180 
8181 	/*
8182 	 * Process the segment text, merging it into the TCP sequencing
8183 	 * queue, and arranging for acknowledgment of receipt if necessary.
8184 	 * This process logically involves adjusting tp->rcv_wnd as data is
8185 	 * presented to the user (this happens in tcp_usrreq.c, case
8186 	 * PRU_RCVD).  If a FIN has already been received on this connection
8187 	 * then we just ignore the text.
8188 	 */
8189 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8190 		   IS_FASTOPEN(tp->t_flags));
8191 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8192 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8193 		tcp_seq save_start = th->th_seq;
8194 		tcp_seq save_rnxt  = tp->rcv_nxt;
8195 		int     save_tlen  = tlen;
8196 
8197 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8198 		/*
8199 		 * Insert segment which includes th into TCP reassembly
8200 		 * queue with control block tp.  Set thflags to whether
8201 		 * reassembly now includes a segment with FIN.  This handles
8202 		 * the common case inline (segment is the next to be
8203 		 * received on an established connection, and the queue is
8204 		 * empty), avoiding linkage into and removal from the queue
8205 		 * and repetition of various conversions. Set DELACK for
8206 		 * segments received in order, but ack immediately when
8207 		 * segments are out of order (so fast retransmit can work).
8208 		 */
8209 		if (th->th_seq == tp->rcv_nxt &&
8210 		    SEGQ_EMPTY(tp) &&
8211 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8212 		    tfo_syn)) {
8213 #ifdef NETFLIX_SB_LIMITS
8214 			u_int mcnt, appended;
8215 
8216 			if (so->so_rcv.sb_shlim) {
8217 				mcnt = m_memcnt(m);
8218 				appended = 0;
8219 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8220 				    CFO_NOSLEEP, NULL) == false) {
8221 					counter_u64_add(tcp_sb_shlim_fails, 1);
8222 					m_freem(m);
8223 					return (0);
8224 				}
8225 			}
8226 
8227 #endif
8228 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8229 				bbr->bbr_segs_rcvd += max(1, nsegs);
8230 				tp->t_flags |= TF_DELACK;
8231 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8232 			} else {
8233 				bbr->r_wanted_output = 1;
8234 				tp->t_flags |= TF_ACKNOW;
8235 			}
8236 			tp->rcv_nxt += tlen;
8237 			if (tlen &&
8238 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8239 			    (tp->t_fbyte_in == 0)) {
8240 				tp->t_fbyte_in = ticks;
8241 				if (tp->t_fbyte_in == 0)
8242 					tp->t_fbyte_in = 1;
8243 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8244 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8245 			}
8246 			thflags = tcp_get_flags(th) & TH_FIN;
8247 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8248 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8249 			SOCKBUF_LOCK(&so->so_rcv);
8250 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8251 				m_freem(m);
8252 			else
8253 #ifdef NETFLIX_SB_LIMITS
8254 				appended =
8255 #endif
8256 					sbappendstream_locked(&so->so_rcv, m, 0);
8257 			/* NB: sorwakeup_locked() does an implicit unlock. */
8258 			sorwakeup_locked(so);
8259 #ifdef NETFLIX_SB_LIMITS
8260 			if (so->so_rcv.sb_shlim && appended != mcnt)
8261 				counter_fo_release(so->so_rcv.sb_shlim,
8262 				    mcnt - appended);
8263 #endif
8264 
8265 		} else {
8266 			/*
8267 			 * XXX: Due to the header drop above "th" is
8268 			 * theoretically invalid by now.  Fortunately
8269 			 * m_adj() doesn't actually frees any mbufs when
8270 			 * trimming from the head.
8271 			 */
8272 			tcp_seq temp = save_start;
8273 
8274 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8275 			tp->t_flags |= TF_ACKNOW;
8276 			if (tp->t_flags & TF_WAKESOR) {
8277 				tp->t_flags &= ~TF_WAKESOR;
8278 				/* NB: sorwakeup_locked() does an implicit unlock. */
8279 				sorwakeup_locked(so);
8280 			}
8281 		}
8282 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8283 		    (save_tlen > 0) &&
8284 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8285 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8286 				/*
8287 				 * DSACK actually handled in the fastpath
8288 				 * above.
8289 				 */
8290 				tcp_update_sack_list(tp, save_start,
8291 				    save_start + save_tlen);
8292 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8293 				if ((tp->rcv_numsacks >= 1) &&
8294 				    (tp->sackblks[0].end == save_start)) {
8295 					/*
8296 					 * Partial overlap, recorded at todrop
8297 					 * above.
8298 					 */
8299 					tcp_update_sack_list(tp,
8300 					    tp->sackblks[0].start,
8301 					    tp->sackblks[0].end);
8302 				} else {
8303 					tcp_update_dsack_list(tp, save_start,
8304 					    save_start + save_tlen);
8305 				}
8306 			} else if (tlen >= save_tlen) {
8307 				/* Update of sackblks. */
8308 				tcp_update_dsack_list(tp, save_start,
8309 				    save_start + save_tlen);
8310 			} else if (tlen > 0) {
8311 				tcp_update_dsack_list(tp, save_start,
8312 				    save_start + tlen);
8313 			}
8314 		}
8315 	} else {
8316 		m_freem(m);
8317 		thflags &= ~TH_FIN;
8318 	}
8319 
8320 	/*
8321 	 * If FIN is received ACK the FIN and let the user know that the
8322 	 * connection is closing.
8323 	 */
8324 	if (thflags & TH_FIN) {
8325 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8326 			/* The socket upcall is handled by socantrcvmore. */
8327 			socantrcvmore(so);
8328 			/*
8329 			 * If connection is half-synchronized (ie NEEDSYN
8330 			 * flag on) then delay ACK, so it may be piggybacked
8331 			 * when SYN is sent. Otherwise, since we received a
8332 			 * FIN then no more input can be expected, send ACK
8333 			 * now.
8334 			 */
8335 			if (tp->t_flags & TF_NEEDSYN) {
8336 				tp->t_flags |= TF_DELACK;
8337 				bbr_timer_cancel(bbr,
8338 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8339 			} else {
8340 				tp->t_flags |= TF_ACKNOW;
8341 			}
8342 			tp->rcv_nxt++;
8343 		}
8344 		switch (tp->t_state) {
8345 			/*
8346 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8347 			 * CLOSE_WAIT state.
8348 			 */
8349 		case TCPS_SYN_RECEIVED:
8350 			tp->t_starttime = ticks;
8351 			/* FALLTHROUGH */
8352 		case TCPS_ESTABLISHED:
8353 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8354 			break;
8355 
8356 			/*
8357 			 * If still in FIN_WAIT_1 STATE FIN has not been
8358 			 * acked so enter the CLOSING state.
8359 			 */
8360 		case TCPS_FIN_WAIT_1:
8361 			tcp_state_change(tp, TCPS_CLOSING);
8362 			break;
8363 
8364 			/*
8365 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8366 			 * starting the time-wait timer, turning off the
8367 			 * other standard timers.
8368 			 */
8369 		case TCPS_FIN_WAIT_2:
8370 			bbr->rc_timer_first = 1;
8371 			bbr_timer_cancel(bbr,
8372 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8373 			tcp_twstart(tp);
8374 			return (1);
8375 		}
8376 	}
8377 	/*
8378 	 * Return any desired output.
8379 	 */
8380 	if ((tp->t_flags & TF_ACKNOW) ||
8381 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8382 		bbr->r_wanted_output = 1;
8383 	}
8384 	return (0);
8385 }
8386 
8387 /*
8388  * Here nothing is really faster, its just that we
8389  * have broken out the fast-data path also just like
8390  * the fast-ack. Return 1 if we processed the packet
8391  * return 0 if you need to take the "slow-path".
8392  */
8393 static int
8394 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8395     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8396     uint32_t tiwin, int32_t nxt_pkt)
8397 {
8398 	uint16_t nsegs;
8399 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8400 	struct tcp_bbr *bbr;
8401 #ifdef NETFLIX_SB_LIMITS
8402 	u_int mcnt, appended;
8403 #endif
8404 
8405 	/* On the hpts and we would have called output */
8406 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8407 
8408 	/*
8409 	 * If last ACK falls within this segment's sequence numbers, record
8410 	 * the timestamp. NOTE that the test is modified according to the
8411 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8412 	 */
8413 	if (bbr->r_ctl.rc_resend != NULL) {
8414 		return (0);
8415 	}
8416 	if (tiwin && tiwin != tp->snd_wnd) {
8417 		return (0);
8418 	}
8419 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8420 		return (0);
8421 	}
8422 	if (__predict_false((to->to_flags & TOF_TS) &&
8423 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8424 		return (0);
8425 	}
8426 	if (__predict_false((th->th_ack != tp->snd_una))) {
8427 		return (0);
8428 	}
8429 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8430 		return (0);
8431 	}
8432 	if ((to->to_flags & TOF_TS) != 0 &&
8433 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8434 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8435 		tp->ts_recent = to->to_tsval;
8436 	}
8437 	/*
8438 	 * This is a pure, in-sequence data packet with nothing on the
8439 	 * reassembly queue and we have enough buffer space to take it.
8440 	 */
8441 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8442 
8443 #ifdef NETFLIX_SB_LIMITS
8444 	if (so->so_rcv.sb_shlim) {
8445 		mcnt = m_memcnt(m);
8446 		appended = 0;
8447 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8448 		    CFO_NOSLEEP, NULL) == false) {
8449 			counter_u64_add(tcp_sb_shlim_fails, 1);
8450 			m_freem(m);
8451 			return (1);
8452 		}
8453 	}
8454 #endif
8455 	/* Clean receiver SACK report if present */
8456 	if (tp->rcv_numsacks)
8457 		tcp_clean_sackreport(tp);
8458 	KMOD_TCPSTAT_INC(tcps_preddat);
8459 	tp->rcv_nxt += tlen;
8460 	if (tlen &&
8461 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8462 	    (tp->t_fbyte_in == 0)) {
8463 		tp->t_fbyte_in = ticks;
8464 		if (tp->t_fbyte_in == 0)
8465 			tp->t_fbyte_in = 1;
8466 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8467 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8468 	}
8469 	/*
8470 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8471 	 */
8472 	tp->snd_wl1 = th->th_seq;
8473 	/*
8474 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8475 	 */
8476 	tp->rcv_up = tp->rcv_nxt;
8477 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8478 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8479 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8480 
8481 	/* Add data to socket buffer. */
8482 	SOCKBUF_LOCK(&so->so_rcv);
8483 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8484 		m_freem(m);
8485 	} else {
8486 		/*
8487 		 * Set new socket buffer size. Give up when limit is
8488 		 * reached.
8489 		 */
8490 		if (newsize)
8491 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8492 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8493 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8494 
8495 #ifdef NETFLIX_SB_LIMITS
8496 		appended =
8497 #endif
8498 			sbappendstream_locked(&so->so_rcv, m, 0);
8499 		ctf_calc_rwin(so, tp);
8500 	}
8501 	/* NB: sorwakeup_locked() does an implicit unlock. */
8502 	sorwakeup_locked(so);
8503 #ifdef NETFLIX_SB_LIMITS
8504 	if (so->so_rcv.sb_shlim && mcnt != appended)
8505 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8506 #endif
8507 	if (DELAY_ACK(tp, bbr, nsegs)) {
8508 		bbr->bbr_segs_rcvd += max(1, nsegs);
8509 		tp->t_flags |= TF_DELACK;
8510 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8511 	} else {
8512 		bbr->r_wanted_output = 1;
8513 		tp->t_flags |= TF_ACKNOW;
8514 	}
8515 	return (1);
8516 }
8517 
8518 /*
8519  * This subfunction is used to try to highly optimize the
8520  * fast path. We again allow window updates that are
8521  * in sequence to remain in the fast-path. We also add
8522  * in the __predict's to attempt to help the compiler.
8523  * Note that if we return a 0, then we can *not* process
8524  * it and the caller should push the packet into the
8525  * slow-path. If we return 1, then all is well and
8526  * the packet is fully processed.
8527  */
8528 static int
8529 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8530     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8531     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8532 {
8533 	int32_t acked;
8534 	uint16_t nsegs;
8535 	uint32_t sack_changed;
8536 	uint32_t prev_acked = 0;
8537 	struct tcp_bbr *bbr;
8538 
8539 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8540 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8541 		return (0);
8542 	}
8543 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8544 		/* Above what we have sent? */
8545 		return (0);
8546 	}
8547 	if (__predict_false(tiwin == 0)) {
8548 		/* zero window */
8549 		return (0);
8550 	}
8551 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8552 		/* We need a SYN or a FIN, unlikely.. */
8553 		return (0);
8554 	}
8555 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8556 		/* Timestamp is behind .. old ack with seq wrap? */
8557 		return (0);
8558 	}
8559 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8560 		/* Still recovering */
8561 		return (0);
8562 	}
8563 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8564 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8565 		/* We are retransmitting */
8566 		return (0);
8567 	}
8568 	if (__predict_false(bbr->rc_in_persist != 0)) {
8569 		/* In persist mode */
8570 		return (0);
8571 	}
8572 	if (bbr->r_ctl.rc_sacked) {
8573 		/* We have sack holes on our scoreboard */
8574 		return (0);
8575 	}
8576 	/* Ok if we reach here, we can process a fast-ack */
8577 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8578 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8579 	/*
8580 	 * We never detect loss in fast ack [we can't
8581 	 * have a sack and can't be in recovery so
8582 	 * we always pass 0 (nothing detected)].
8583 	 */
8584 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8585 	/* Did the window get updated? */
8586 	if (tiwin != tp->snd_wnd) {
8587 		tp->snd_wnd = tiwin;
8588 		tp->snd_wl1 = th->th_seq;
8589 		if (tp->snd_wnd > tp->max_sndwnd)
8590 			tp->max_sndwnd = tp->snd_wnd;
8591 	}
8592 	/* Do we need to exit persists? */
8593 	if ((bbr->rc_in_persist != 0) &&
8594 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8595 			       bbr_minseg(bbr)))) {
8596 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8597 		bbr->r_wanted_output = 1;
8598 	}
8599 	/* Do we need to enter persists? */
8600 	if ((bbr->rc_in_persist == 0) &&
8601 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8602 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8603 	    (tp->snd_max == tp->snd_una) &&
8604 	    sbavail(&so->so_snd) &&
8605 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8606 		/* No send window.. we must enter persist */
8607 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8608 	}
8609 	/*
8610 	 * If last ACK falls within this segment's sequence numbers, record
8611 	 * the timestamp. NOTE that the test is modified according to the
8612 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8613 	 */
8614 	if ((to->to_flags & TOF_TS) != 0 &&
8615 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8616 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8617 		tp->ts_recent = to->to_tsval;
8618 	}
8619 	/*
8620 	 * This is a pure ack for outstanding data.
8621 	 */
8622 	KMOD_TCPSTAT_INC(tcps_predack);
8623 
8624 	/*
8625 	 * "bad retransmit" recovery.
8626 	 */
8627 	if (tp->t_flags & TF_PREVVALID) {
8628 		tp->t_flags &= ~TF_PREVVALID;
8629 		if (tp->t_rxtshift == 1 &&
8630 		    (int)(ticks - tp->t_badrxtwin) < 0)
8631 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8632 	}
8633 	/*
8634 	 * Recalculate the transmit timer / rtt.
8635 	 *
8636 	 * Some boxes send broken timestamp replies during the SYN+ACK
8637 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8638 	 * and blow up the retransmit timer.
8639 	 */
8640 	acked = BYTES_THIS_ACK(tp, th);
8641 
8642 #ifdef TCP_HHOOK
8643 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8644 	hhook_run_tcp_est_in(tp, th, to);
8645 #endif
8646 
8647 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8648 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8649 	sbdrop(&so->so_snd, acked);
8650 
8651 	if (SEQ_GT(th->th_ack, tp->snd_una))
8652 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8653 	tp->snd_una = th->th_ack;
8654 	if (tp->snd_wnd < ctf_outstanding(tp))
8655 		/* The peer collapsed its window on us */
8656 		bbr_collapsed_window(bbr);
8657 	else if (bbr->rc_has_collapsed)
8658 		bbr_un_collapse_window(bbr);
8659 
8660 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8661 		tp->snd_recover = tp->snd_una;
8662 	}
8663 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8664 	/*
8665 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8666 	 */
8667 	tp->snd_wl2 = th->th_ack;
8668 	m_freem(m);
8669 	/*
8670 	 * If all outstanding data are acked, stop retransmit timer,
8671 	 * otherwise restart timer using current (possibly backed-off)
8672 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8673 	 * If data are ready to send, let tcp_output decide between more
8674 	 * output or persist.
8675 	 * Wake up the socket if we have room to write more.
8676 	 */
8677 	sowwakeup(so);
8678 	if (tp->snd_una == tp->snd_max) {
8679 		/* Nothing left outstanding */
8680 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8681 		if (sbavail(&so->so_snd) == 0)
8682 			bbr->rc_tp->t_acktime = 0;
8683 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8684 		if (bbr->rc_in_persist == 0) {
8685 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8686 		}
8687 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8688 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8689 		/*
8690 		 * We invalidate the last ack here since we
8691 		 * don't want to transfer forward the time
8692 		 * for our sum's calculations.
8693 		 */
8694 		bbr->r_wanted_output = 1;
8695 	}
8696 	if (sbavail(&so->so_snd)) {
8697 		bbr->r_wanted_output = 1;
8698 	}
8699 	return (1);
8700 }
8701 
8702 /*
8703  * Return value of 1, the TCB is unlocked and most
8704  * likely gone, return value of 0, the TCB is still
8705  * locked.
8706  */
8707 static int
8708 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8709     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8710     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8711 {
8712 	int32_t todrop;
8713 	int32_t ourfinisacked = 0;
8714 	struct tcp_bbr *bbr;
8715 	int32_t ret_val = 0;
8716 
8717 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8718 
8719 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8720 	ctf_calc_rwin(so, tp);
8721 	/*
8722 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8723 	 * SYN, drop the input. if seg contains a RST, then drop the
8724 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8725 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8726 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8727 	 * not support ECN so we will not say we are capable. if SYN has
8728 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8729 	 * segment to be acked (eventually) continue processing rest of
8730 	 * data/controls, beginning with URG
8731 	 */
8732 	if ((thflags & TH_ACK) &&
8733 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8734 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8735 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8736 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8737 		return (1);
8738 	}
8739 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8740 		TCP_PROBE5(connect__refused, NULL, tp,
8741 		    mtod(m, const char *), tp, th);
8742 		tp = tcp_drop(tp, ECONNREFUSED);
8743 		ctf_do_drop(m, tp);
8744 		return (1);
8745 	}
8746 	if (thflags & TH_RST) {
8747 		ctf_do_drop(m, tp);
8748 		return (1);
8749 	}
8750 	if (!(thflags & TH_SYN)) {
8751 		ctf_do_drop(m, tp);
8752 		return (1);
8753 	}
8754 	tp->irs = th->th_seq;
8755 	tcp_rcvseqinit(tp);
8756 	if (thflags & TH_ACK) {
8757 		int tfo_partial = 0;
8758 
8759 		KMOD_TCPSTAT_INC(tcps_connects);
8760 		soisconnected(so);
8761 #ifdef MAC
8762 		mac_socketpeer_set_from_mbuf(m, so);
8763 #endif
8764 		/* Do window scaling on this connection? */
8765 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8766 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8767 			tp->rcv_scale = tp->request_r_scale;
8768 		}
8769 		tp->rcv_adv += min(tp->rcv_wnd,
8770 		    TCP_MAXWIN << tp->rcv_scale);
8771 		/*
8772 		 * If not all the data that was sent in the TFO SYN
8773 		 * has been acked, resend the remainder right away.
8774 		 */
8775 		if (IS_FASTOPEN(tp->t_flags) &&
8776 		    (tp->snd_una != tp->snd_max)) {
8777 			tp->snd_nxt = th->th_ack;
8778 			tfo_partial = 1;
8779 		}
8780 		/*
8781 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8782 		 * will be turned on later.
8783 		 */
8784 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8785 			bbr->bbr_segs_rcvd += 1;
8786 			tp->t_flags |= TF_DELACK;
8787 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8788 		} else {
8789 			bbr->r_wanted_output = 1;
8790 			tp->t_flags |= TF_ACKNOW;
8791 		}
8792 		if (SEQ_GT(th->th_ack, tp->iss)) {
8793 			/*
8794 			 * The SYN is acked
8795 			 * handle it specially.
8796 			 */
8797 			bbr_log_syn(tp, to);
8798 		}
8799 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8800 			/*
8801 			 * We advance snd_una for the
8802 			 * fast open case. If th_ack is
8803 			 * acknowledging data beyond
8804 			 * snd_una we can't just call
8805 			 * ack-processing since the
8806 			 * data stream in our send-map
8807 			 * will start at snd_una + 1 (one
8808 			 * beyond the SYN). If its just
8809 			 * equal we don't need to do that
8810 			 * and there is no send_map.
8811 			 */
8812 			tp->snd_una++;
8813 		}
8814 		/*
8815 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8816 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8817 		 */
8818 		tp->t_starttime = ticks;
8819 		if (tp->t_flags & TF_NEEDFIN) {
8820 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8821 			tp->t_flags &= ~TF_NEEDFIN;
8822 			thflags &= ~TH_SYN;
8823 		} else {
8824 			tcp_state_change(tp, TCPS_ESTABLISHED);
8825 			TCP_PROBE5(connect__established, NULL, tp,
8826 			    mtod(m, const char *), tp, th);
8827 			cc_conn_init(tp);
8828 		}
8829 	} else {
8830 		/*
8831 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8832 		 * open.  If segment contains CC option and there is a
8833 		 * cached CC, apply TAO test. If it succeeds, connection is *
8834 		 * half-synchronized. Otherwise, do 3-way handshake:
8835 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8836 		 * there was no CC option, clear cached CC value.
8837 		 */
8838 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
8839 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8840 	}
8841 	/*
8842 	 * Advance th->th_seq to correspond to first data byte. If data,
8843 	 * trim to stay within window, dropping FIN if necessary.
8844 	 */
8845 	th->th_seq++;
8846 	if (tlen > tp->rcv_wnd) {
8847 		todrop = tlen - tp->rcv_wnd;
8848 		m_adj(m, -todrop);
8849 		tlen = tp->rcv_wnd;
8850 		thflags &= ~TH_FIN;
8851 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8852 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8853 	}
8854 	tp->snd_wl1 = th->th_seq - 1;
8855 	tp->rcv_up = th->th_seq;
8856 	/*
8857 	 * Client side of transaction: already sent SYN and data. If the
8858 	 * remote host used T/TCP to validate the SYN, our data will be
8859 	 * ACK'd; if so, enter normal data segment processing in the middle
8860 	 * of step 5, ack processing. Otherwise, goto step 6.
8861 	 */
8862 	if (thflags & TH_ACK) {
8863 		if ((to->to_flags & TOF_TS) != 0) {
8864 			uint32_t t, rtt;
8865 
8866 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8867 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8868 				rtt = t - to->to_tsecr;
8869 				if (rtt == 0) {
8870 					rtt = 1;
8871 				}
8872 				rtt *= MS_IN_USEC;
8873 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8874 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8875 						       rtt, bbr->r_ctl.rc_rcvtime);
8876 			}
8877 		}
8878 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8879 			return (ret_val);
8880 		/* We may have changed to FIN_WAIT_1 above */
8881 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8882 			/*
8883 			 * In FIN_WAIT_1 STATE in addition to the processing
8884 			 * for the ESTABLISHED state if our FIN is now
8885 			 * acknowledged then enter FIN_WAIT_2.
8886 			 */
8887 			if (ourfinisacked) {
8888 				/*
8889 				 * If we can't receive any more data, then
8890 				 * closing user can proceed. Starting the
8891 				 * timer is contrary to the specification,
8892 				 * but if we don't get a FIN we'll hang
8893 				 * forever.
8894 				 *
8895 				 * XXXjl: we should release the tp also, and
8896 				 * use a compressed state.
8897 				 */
8898 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8899 					soisdisconnected(so);
8900 					tcp_timer_activate(tp, TT_2MSL,
8901 					    (tcp_fast_finwait2_recycle ?
8902 					    tcp_finwait2_timeout :
8903 					    TP_MAXIDLE(tp)));
8904 				}
8905 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8906 			}
8907 		}
8908 	}
8909 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8910 	    tiwin, thflags, nxt_pkt));
8911 }
8912 
8913 /*
8914  * Return value of 1, the TCB is unlocked and most
8915  * likely gone, return value of 0, the TCB is still
8916  * locked.
8917  */
8918 static int
8919 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8920 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8921 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8922 {
8923 	int32_t ourfinisacked = 0;
8924 	int32_t ret_val;
8925 	struct tcp_bbr *bbr;
8926 
8927 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8928 
8929 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8930 	ctf_calc_rwin(so, tp);
8931 	if ((thflags & TH_RST) ||
8932 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
8933 		return (ctf_process_rst(m, th, so, tp));
8934 	if ((thflags & TH_ACK) &&
8935 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8936 	     SEQ_GT(th->th_ack, tp->snd_max))) {
8937 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8938 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8939 		return (1);
8940 	}
8941 	if (IS_FASTOPEN(tp->t_flags)) {
8942 		/*
8943 		 * When a TFO connection is in SYN_RECEIVED, the only valid
8944 		 * packets are the initial SYN, a retransmit/copy of the
8945 		 * initial SYN (possibly with a subset of the original
8946 		 * data), a valid ACK, a FIN, or a RST.
8947 		 */
8948 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
8949 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8950 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8951 			return (1);
8952 		} else if (thflags & TH_SYN) {
8953 			/* non-initial SYN is ignored */
8954 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
8955 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
8956 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
8957 				ctf_do_drop(m, NULL);
8958 				return (0);
8959 			}
8960 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
8961 			ctf_do_drop(m, NULL);
8962 			return (0);
8963 		}
8964 	}
8965 	/*
8966 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
8967 	 * it's less than ts_recent, drop it.
8968 	 */
8969 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
8970 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
8971 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
8972 			return (ret_val);
8973 	}
8974 	/*
8975 	 * In the SYN-RECEIVED state, validate that the packet belongs to
8976 	 * this connection before trimming the data to fit the receive
8977 	 * window.  Check the sequence number versus IRS since we know the
8978 	 * sequence numbers haven't wrapped.  This is a partial fix for the
8979 	 * "LAND" DoS attack.
8980 	 */
8981 	if (SEQ_LT(th->th_seq, tp->irs)) {
8982 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8983 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8984 		return (1);
8985 	}
8986 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
8987 		return (ret_val);
8988 	}
8989 	/*
8990 	 * If last ACK falls within this segment's sequence numbers, record
8991 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
8992 	 * from the latest proposal of the tcplw@cray.com list (Braden
8993 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
8994 	 * with our earlier PAWS tests, so this check should be solely
8995 	 * predicated on the sequence space of this segment. 3) That we
8996 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
8997 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
8998 	 * SEG.Len, This modified check allows us to overcome RFC1323's
8999 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9000 	 * p.869. In such cases, we can still calculate the RTT correctly
9001 	 * when RCV.NXT == Last.ACK.Sent.
9002 	 */
9003 	if ((to->to_flags & TOF_TS) != 0 &&
9004 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9005 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9006 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9007 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9008 		tp->ts_recent = to->to_tsval;
9009 	}
9010 	tp->snd_wnd = tiwin;
9011 	/*
9012 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9013 	 * is on (half-synchronized state), then queue data for later
9014 	 * processing; else drop segment and return.
9015 	 */
9016 	if ((thflags & TH_ACK) == 0) {
9017 		if (IS_FASTOPEN(tp->t_flags)) {
9018 			cc_conn_init(tp);
9019 		}
9020 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9021 					 tiwin, thflags, nxt_pkt));
9022 	}
9023 	KMOD_TCPSTAT_INC(tcps_connects);
9024 	if (tp->t_flags & TF_SONOTCONN) {
9025 		tp->t_flags &= ~TF_SONOTCONN;
9026 		soisconnected(so);
9027 	}
9028 	/* Do window scaling? */
9029 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9030 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9031 		tp->rcv_scale = tp->request_r_scale;
9032 	}
9033 	/*
9034 	 * ok for the first time in lets see if we can use the ts to figure
9035 	 * out what the initial RTT was.
9036 	 */
9037 	if ((to->to_flags & TOF_TS) != 0) {
9038 		uint32_t t, rtt;
9039 
9040 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9041 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9042 			rtt = t - to->to_tsecr;
9043 			if (rtt == 0) {
9044 				rtt = 1;
9045 			}
9046 			rtt *= MS_IN_USEC;
9047 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9048 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9049 		}
9050 	}
9051 	/* Drop off any SYN in the send map (probably not there)  */
9052 	if (thflags & TH_ACK)
9053 		bbr_log_syn(tp, to);
9054 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9055 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9056 		tp->t_tfo_pending = NULL;
9057 	}
9058 	/*
9059 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9060 	 * FIN-WAIT-1
9061 	 */
9062 	tp->t_starttime = ticks;
9063 	if (tp->t_flags & TF_NEEDFIN) {
9064 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9065 		tp->t_flags &= ~TF_NEEDFIN;
9066 	} else {
9067 		tcp_state_change(tp, TCPS_ESTABLISHED);
9068 		TCP_PROBE5(accept__established, NULL, tp,
9069 			   mtod(m, const char *), tp, th);
9070 		/*
9071 		 * TFO connections call cc_conn_init() during SYN
9072 		 * processing.  Calling it again here for such connections
9073 		 * is not harmless as it would undo the snd_cwnd reduction
9074 		 * that occurs when a TFO SYN|ACK is retransmitted.
9075 		 */
9076 		if (!IS_FASTOPEN(tp->t_flags))
9077 			cc_conn_init(tp);
9078 	}
9079 	/*
9080 	 * Account for the ACK of our SYN prior to
9081 	 * regular ACK processing below, except for
9082 	 * simultaneous SYN, which is handled later.
9083 	 */
9084 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9085 		tp->snd_una++;
9086 	/*
9087 	 * If segment contains data or ACK, will call tcp_reass() later; if
9088 	 * not, do so now to pass queued data to user.
9089 	 */
9090 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9091 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9092 			(struct mbuf *)0);
9093 		if (tp->t_flags & TF_WAKESOR) {
9094 			tp->t_flags &= ~TF_WAKESOR;
9095 			/* NB: sorwakeup_locked() does an implicit unlock. */
9096 			sorwakeup_locked(so);
9097 		}
9098 	}
9099 	tp->snd_wl1 = th->th_seq - 1;
9100 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9101 		return (ret_val);
9102 	}
9103 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9104 		/* We could have went to FIN_WAIT_1 (or EST) above */
9105 		/*
9106 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9107 		 * ESTABLISHED state if our FIN is now acknowledged then
9108 		 * enter FIN_WAIT_2.
9109 		 */
9110 		if (ourfinisacked) {
9111 			/*
9112 			 * If we can't receive any more data, then closing
9113 			 * user can proceed. Starting the timer is contrary
9114 			 * to the specification, but if we don't get a FIN
9115 			 * we'll hang forever.
9116 			 *
9117 			 * XXXjl: we should release the tp also, and use a
9118 			 * compressed state.
9119 			 */
9120 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9121 				soisdisconnected(so);
9122 				tcp_timer_activate(tp, TT_2MSL,
9123 						   (tcp_fast_finwait2_recycle ?
9124 						    tcp_finwait2_timeout :
9125 						    TP_MAXIDLE(tp)));
9126 			}
9127 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9128 		}
9129 	}
9130 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9131 				 tiwin, thflags, nxt_pkt));
9132 }
9133 
9134 /*
9135  * Return value of 1, the TCB is unlocked and most
9136  * likely gone, return value of 0, the TCB is still
9137  * locked.
9138  */
9139 static int
9140 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9141     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9142     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9143 {
9144 	struct tcp_bbr *bbr;
9145 	int32_t ret_val;
9146 
9147 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9148 
9149 	/*
9150 	 * Header prediction: check for the two common cases of a
9151 	 * uni-directional data xfer.  If the packet has no control flags,
9152 	 * is in-sequence, the window didn't change and we're not
9153 	 * retransmitting, it's a candidate.  If the length is zero and the
9154 	 * ack moved forward, we're the sender side of the xfer.  Just free
9155 	 * the data acked & wake any higher level process that was blocked
9156 	 * waiting for space.  If the length is non-zero and the ack didn't
9157 	 * move, we're the receiver side.  If we're getting packets in-order
9158 	 * (the reassembly queue is empty), add the data toc The socket
9159 	 * buffer and note that we need a delayed ack. Make sure that the
9160 	 * hidden state-flags are also off. Since we check for
9161 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9162 	 */
9163 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9164 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9165 		/*
9166 		 * If we have delived under 4 segments increase the initial
9167 		 * window if raised by the peer. We use this to determine
9168 		 * dynamic and static rwnd's at the end of a connection.
9169 		 */
9170 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9171 	}
9172 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9173 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9174 	    __predict_true(SEGQ_EMPTY(tp)) &&
9175 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9176 		if (tlen == 0) {
9177 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9178 			    tiwin, nxt_pkt, iptos)) {
9179 				return (0);
9180 			}
9181 		} else {
9182 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9183 			    tiwin, nxt_pkt)) {
9184 				return (0);
9185 			}
9186 		}
9187 	}
9188 	ctf_calc_rwin(so, tp);
9189 
9190 	if ((thflags & TH_RST) ||
9191 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9192 		return (ctf_process_rst(m, th, so, tp));
9193 	/*
9194 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9195 	 * synchronized state.
9196 	 */
9197 	if (thflags & TH_SYN) {
9198 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9199 		return (ret_val);
9200 	}
9201 	/*
9202 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9203 	 * it's less than ts_recent, drop it.
9204 	 */
9205 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9206 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9207 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9208 			return (ret_val);
9209 	}
9210 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9211 		return (ret_val);
9212 	}
9213 	/*
9214 	 * If last ACK falls within this segment's sequence numbers, record
9215 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9216 	 * from the latest proposal of the tcplw@cray.com list (Braden
9217 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9218 	 * with our earlier PAWS tests, so this check should be solely
9219 	 * predicated on the sequence space of this segment. 3) That we
9220 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9221 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9222 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9223 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9224 	 * p.869. In such cases, we can still calculate the RTT correctly
9225 	 * when RCV.NXT == Last.ACK.Sent.
9226 	 */
9227 	if ((to->to_flags & TOF_TS) != 0 &&
9228 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9229 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9230 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9231 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9232 		tp->ts_recent = to->to_tsval;
9233 	}
9234 	/*
9235 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9236 	 * is on (half-synchronized state), then queue data for later
9237 	 * processing; else drop segment and return.
9238 	 */
9239 	if ((thflags & TH_ACK) == 0) {
9240 		if (tp->t_flags & TF_NEEDSYN) {
9241 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9242 			    tiwin, thflags, nxt_pkt));
9243 		} else if (tp->t_flags & TF_ACKNOW) {
9244 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9245 			bbr->r_wanted_output = 1;
9246 			return (ret_val);
9247 		} else {
9248 			ctf_do_drop(m, NULL);
9249 			return (0);
9250 		}
9251 	}
9252 	/*
9253 	 * Ack processing.
9254 	 */
9255 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9256 		return (ret_val);
9257 	}
9258 	if (sbavail(&so->so_snd)) {
9259 		if (ctf_progress_timeout_check(tp, true)) {
9260 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9261 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9262 			return (1);
9263 		}
9264 	}
9265 	/* State changes only happen in bbr_process_data() */
9266 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9267 	    tiwin, thflags, nxt_pkt));
9268 }
9269 
9270 /*
9271  * Return value of 1, the TCB is unlocked and most
9272  * likely gone, return value of 0, the TCB is still
9273  * locked.
9274  */
9275 static int
9276 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9277     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9278     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9279 {
9280 	struct tcp_bbr *bbr;
9281 	int32_t ret_val;
9282 
9283 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9284 
9285 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9286 	ctf_calc_rwin(so, tp);
9287 	if ((thflags & TH_RST) ||
9288 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9289 		return (ctf_process_rst(m, th, so, tp));
9290 	/*
9291 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9292 	 * synchronized state.
9293 	 */
9294 	if (thflags & TH_SYN) {
9295 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9296 		return (ret_val);
9297 	}
9298 	/*
9299 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9300 	 * it's less than ts_recent, drop it.
9301 	 */
9302 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9303 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9304 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9305 			return (ret_val);
9306 	}
9307 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9308 		return (ret_val);
9309 	}
9310 	/*
9311 	 * If last ACK falls within this segment's sequence numbers, record
9312 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9313 	 * from the latest proposal of the tcplw@cray.com list (Braden
9314 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9315 	 * with our earlier PAWS tests, so this check should be solely
9316 	 * predicated on the sequence space of this segment. 3) That we
9317 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9318 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9319 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9320 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9321 	 * p.869. In such cases, we can still calculate the RTT correctly
9322 	 * when RCV.NXT == Last.ACK.Sent.
9323 	 */
9324 	if ((to->to_flags & TOF_TS) != 0 &&
9325 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9326 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9327 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9328 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9329 		tp->ts_recent = to->to_tsval;
9330 	}
9331 	/*
9332 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9333 	 * is on (half-synchronized state), then queue data for later
9334 	 * processing; else drop segment and return.
9335 	 */
9336 	if ((thflags & TH_ACK) == 0) {
9337 		if (tp->t_flags & TF_NEEDSYN) {
9338 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9339 			    tiwin, thflags, nxt_pkt));
9340 		} else if (tp->t_flags & TF_ACKNOW) {
9341 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9342 			bbr->r_wanted_output = 1;
9343 			return (ret_val);
9344 		} else {
9345 			ctf_do_drop(m, NULL);
9346 			return (0);
9347 		}
9348 	}
9349 	/*
9350 	 * Ack processing.
9351 	 */
9352 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9353 		return (ret_val);
9354 	}
9355 	if (sbavail(&so->so_snd)) {
9356 		if (ctf_progress_timeout_check(tp, true)) {
9357 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9358 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9359 			return (1);
9360 		}
9361 	}
9362 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9363 	    tiwin, thflags, nxt_pkt));
9364 }
9365 
9366 static int
9367 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9368     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9369 {
9370 
9371 	if (bbr->rc_allow_data_af_clo == 0) {
9372 close_now:
9373 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9374 		/* tcp_close will kill the inp pre-log the Reset */
9375 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9376 		tp = tcp_close(tp);
9377 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9378 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9379 		return (1);
9380 	}
9381 	if (sbavail(&so->so_snd) == 0)
9382 		goto close_now;
9383 	/* Ok we allow data that is ignored and a followup reset */
9384 	tp->rcv_nxt = th->th_seq + *tlen;
9385 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9386 	bbr->r_wanted_output = 1;
9387 	*tlen = 0;
9388 	return (0);
9389 }
9390 
9391 /*
9392  * Return value of 1, the TCB is unlocked and most
9393  * likely gone, return value of 0, the TCB is still
9394  * locked.
9395  */
9396 static int
9397 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9398     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9399     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9400 {
9401 	int32_t ourfinisacked = 0;
9402 	int32_t ret_val;
9403 	struct tcp_bbr *bbr;
9404 
9405 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9406 
9407 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9408 	ctf_calc_rwin(so, tp);
9409 	if ((thflags & TH_RST) ||
9410 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9411 		return (ctf_process_rst(m, th, so, tp));
9412 	/*
9413 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9414 	 * synchronized state.
9415 	 */
9416 	if (thflags & TH_SYN) {
9417 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9418 		return (ret_val);
9419 	}
9420 	/*
9421 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9422 	 * it's less than ts_recent, drop it.
9423 	 */
9424 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9425 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9426 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9427 			return (ret_val);
9428 	}
9429 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9430 		return (ret_val);
9431 	}
9432 	/*
9433 	 * If new data are received on a connection after the user processes
9434 	 * are gone, then RST the other end.
9435 	 * We call a new function now so we might continue and setup
9436 	 * to reset at all data being ack'd.
9437 	 */
9438 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9439 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9440 		return (1);
9441 	/*
9442 	 * If last ACK falls within this segment's sequence numbers, record
9443 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9444 	 * from the latest proposal of the tcplw@cray.com list (Braden
9445 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9446 	 * with our earlier PAWS tests, so this check should be solely
9447 	 * predicated on the sequence space of this segment. 3) That we
9448 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9449 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9450 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9451 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9452 	 * p.869. In such cases, we can still calculate the RTT correctly
9453 	 * when RCV.NXT == Last.ACK.Sent.
9454 	 */
9455 	if ((to->to_flags & TOF_TS) != 0 &&
9456 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9457 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9458 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9459 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9460 		tp->ts_recent = to->to_tsval;
9461 	}
9462 	/*
9463 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9464 	 * is on (half-synchronized state), then queue data for later
9465 	 * processing; else drop segment and return.
9466 	 */
9467 	if ((thflags & TH_ACK) == 0) {
9468 		if (tp->t_flags & TF_NEEDSYN) {
9469 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9470 			    tiwin, thflags, nxt_pkt));
9471 		} else if (tp->t_flags & TF_ACKNOW) {
9472 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9473 			bbr->r_wanted_output = 1;
9474 			return (ret_val);
9475 		} else {
9476 			ctf_do_drop(m, NULL);
9477 			return (0);
9478 		}
9479 	}
9480 	/*
9481 	 * Ack processing.
9482 	 */
9483 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9484 		return (ret_val);
9485 	}
9486 	if (ourfinisacked) {
9487 		/*
9488 		 * If we can't receive any more data, then closing user can
9489 		 * proceed. Starting the timer is contrary to the
9490 		 * specification, but if we don't get a FIN we'll hang
9491 		 * forever.
9492 		 *
9493 		 * XXXjl: we should release the tp also, and use a
9494 		 * compressed state.
9495 		 */
9496 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9497 			soisdisconnected(so);
9498 			tcp_timer_activate(tp, TT_2MSL,
9499 			    (tcp_fast_finwait2_recycle ?
9500 			    tcp_finwait2_timeout :
9501 			    TP_MAXIDLE(tp)));
9502 		}
9503 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9504 	}
9505 	if (sbavail(&so->so_snd)) {
9506 		if (ctf_progress_timeout_check(tp, true)) {
9507 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9508 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9509 			return (1);
9510 		}
9511 	}
9512 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9513 	    tiwin, thflags, nxt_pkt));
9514 }
9515 
9516 /*
9517  * Return value of 1, the TCB is unlocked and most
9518  * likely gone, return value of 0, the TCB is still
9519  * locked.
9520  */
9521 static int
9522 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9523     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9524     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9525 {
9526 	int32_t ourfinisacked = 0;
9527 	int32_t ret_val;
9528 	struct tcp_bbr *bbr;
9529 
9530 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9531 
9532 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9533 	ctf_calc_rwin(so, tp);
9534 	if ((thflags & TH_RST) ||
9535 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9536 		return (ctf_process_rst(m, th, so, tp));
9537 	/*
9538 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9539 	 * synchronized state.
9540 	 */
9541 	if (thflags & TH_SYN) {
9542 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9543 		return (ret_val);
9544 	}
9545 	/*
9546 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9547 	 * it's less than ts_recent, drop it.
9548 	 */
9549 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9550 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9551 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9552 			return (ret_val);
9553 	}
9554 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9555 		return (ret_val);
9556 	}
9557 	/*
9558 	 * If new data are received on a connection after the user processes
9559 	 * are gone, then RST the other end.
9560 	 * We call a new function now so we might continue and setup
9561 	 * to reset at all data being ack'd.
9562 	 */
9563 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9564 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9565 		return (1);
9566 	/*
9567 	 * If last ACK falls within this segment's sequence numbers, record
9568 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9569 	 * from the latest proposal of the tcplw@cray.com list (Braden
9570 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9571 	 * with our earlier PAWS tests, so this check should be solely
9572 	 * predicated on the sequence space of this segment. 3) That we
9573 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9574 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9575 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9576 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9577 	 * p.869. In such cases, we can still calculate the RTT correctly
9578 	 * when RCV.NXT == Last.ACK.Sent.
9579 	 */
9580 	if ((to->to_flags & TOF_TS) != 0 &&
9581 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9582 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9583 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9584 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9585 		tp->ts_recent = to->to_tsval;
9586 	}
9587 	/*
9588 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9589 	 * is on (half-synchronized state), then queue data for later
9590 	 * processing; else drop segment and return.
9591 	 */
9592 	if ((thflags & TH_ACK) == 0) {
9593 		if (tp->t_flags & TF_NEEDSYN) {
9594 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9595 			    tiwin, thflags, nxt_pkt));
9596 		} else if (tp->t_flags & TF_ACKNOW) {
9597 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9598 			bbr->r_wanted_output = 1;
9599 			return (ret_val);
9600 		} else {
9601 			ctf_do_drop(m, NULL);
9602 			return (0);
9603 		}
9604 	}
9605 	/*
9606 	 * Ack processing.
9607 	 */
9608 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9609 		return (ret_val);
9610 	}
9611 	if (ourfinisacked) {
9612 		tcp_twstart(tp);
9613 		m_freem(m);
9614 		return (1);
9615 	}
9616 	if (sbavail(&so->so_snd)) {
9617 		if (ctf_progress_timeout_check(tp, true)) {
9618 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9619 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9620 			return (1);
9621 		}
9622 	}
9623 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9624 	    tiwin, thflags, nxt_pkt));
9625 }
9626 
9627 /*
9628  * Return value of 1, the TCB is unlocked and most
9629  * likely gone, return value of 0, the TCB is still
9630  * locked.
9631  */
9632 static int
9633 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9634     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9635     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9636 {
9637 	int32_t ourfinisacked = 0;
9638 	int32_t ret_val;
9639 	struct tcp_bbr *bbr;
9640 
9641 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9642 
9643 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9644 	ctf_calc_rwin(so, tp);
9645 	if ((thflags & TH_RST) ||
9646 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9647 		return (ctf_process_rst(m, th, so, tp));
9648 	/*
9649 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9650 	 * synchronized state.
9651 	 */
9652 	if (thflags & TH_SYN) {
9653 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9654 		return (ret_val);
9655 	}
9656 	/*
9657 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9658 	 * it's less than ts_recent, drop it.
9659 	 */
9660 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9661 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9662 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9663 			return (ret_val);
9664 	}
9665 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9666 		return (ret_val);
9667 	}
9668 	/*
9669 	 * If new data are received on a connection after the user processes
9670 	 * are gone, then RST the other end.
9671 	 * We call a new function now so we might continue and setup
9672 	 * to reset at all data being ack'd.
9673 	 */
9674 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9675 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9676 		return (1);
9677 	/*
9678 	 * If last ACK falls within this segment's sequence numbers, record
9679 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9680 	 * from the latest proposal of the tcplw@cray.com list (Braden
9681 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9682 	 * with our earlier PAWS tests, so this check should be solely
9683 	 * predicated on the sequence space of this segment. 3) That we
9684 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9685 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9686 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9687 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9688 	 * p.869. In such cases, we can still calculate the RTT correctly
9689 	 * when RCV.NXT == Last.ACK.Sent.
9690 	 */
9691 	if ((to->to_flags & TOF_TS) != 0 &&
9692 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9693 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9694 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9695 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9696 		tp->ts_recent = to->to_tsval;
9697 	}
9698 	/*
9699 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9700 	 * is on (half-synchronized state), then queue data for later
9701 	 * processing; else drop segment and return.
9702 	 */
9703 	if ((thflags & TH_ACK) == 0) {
9704 		if (tp->t_flags & TF_NEEDSYN) {
9705 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9706 			    tiwin, thflags, nxt_pkt));
9707 		} else if (tp->t_flags & TF_ACKNOW) {
9708 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9709 			bbr->r_wanted_output = 1;
9710 			return (ret_val);
9711 		} else {
9712 			ctf_do_drop(m, NULL);
9713 			return (0);
9714 		}
9715 	}
9716 	/*
9717 	 * case TCPS_LAST_ACK: Ack processing.
9718 	 */
9719 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9720 		return (ret_val);
9721 	}
9722 	if (ourfinisacked) {
9723 		tp = tcp_close(tp);
9724 		ctf_do_drop(m, tp);
9725 		return (1);
9726 	}
9727 	if (sbavail(&so->so_snd)) {
9728 		if (ctf_progress_timeout_check(tp, true)) {
9729 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9730 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9731 			return (1);
9732 		}
9733 	}
9734 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9735 	    tiwin, thflags, nxt_pkt));
9736 }
9737 
9738 /*
9739  * Return value of 1, the TCB is unlocked and most
9740  * likely gone, return value of 0, the TCB is still
9741  * locked.
9742  */
9743 static int
9744 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9745     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9746     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9747 {
9748 	int32_t ourfinisacked = 0;
9749 	int32_t ret_val;
9750 	struct tcp_bbr *bbr;
9751 
9752 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9753 
9754 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9755 	ctf_calc_rwin(so, tp);
9756 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9757 	if ((thflags & TH_RST) ||
9758 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9759 		return (ctf_process_rst(m, th, so, tp));
9760 
9761 	/*
9762 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9763 	 * synchronized state.
9764 	 */
9765 	if (thflags & TH_SYN) {
9766 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9767 		return (ret_val);
9768 	}
9769 	/*
9770 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9771 	 * it's less than ts_recent, drop it.
9772 	 */
9773 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9774 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9775 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9776 			return (ret_val);
9777 	}
9778 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9779 		return (ret_val);
9780 	}
9781 	/*
9782 	 * If new data are received on a connection after the user processes
9783 	 * are gone, then we may RST the other end depending on the outcome
9784 	 * of bbr_check_data_after_close.
9785 	 * We call a new function now so we might continue and setup
9786 	 * to reset at all data being ack'd.
9787 	 */
9788 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9789 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9790 		return (1);
9791 	/*
9792 	 * If last ACK falls within this segment's sequence numbers, record
9793 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9794 	 * from the latest proposal of the tcplw@cray.com list (Braden
9795 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9796 	 * with our earlier PAWS tests, so this check should be solely
9797 	 * predicated on the sequence space of this segment. 3) That we
9798 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9799 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9800 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9801 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9802 	 * p.869. In such cases, we can still calculate the RTT correctly
9803 	 * when RCV.NXT == Last.ACK.Sent.
9804 	 */
9805 	if ((to->to_flags & TOF_TS) != 0 &&
9806 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9807 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9808 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9809 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9810 		tp->ts_recent = to->to_tsval;
9811 	}
9812 	/*
9813 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9814 	 * is on (half-synchronized state), then queue data for later
9815 	 * processing; else drop segment and return.
9816 	 */
9817 	if ((thflags & TH_ACK) == 0) {
9818 		if (tp->t_flags & TF_NEEDSYN) {
9819 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9820 			    tiwin, thflags, nxt_pkt));
9821 		} else if (tp->t_flags & TF_ACKNOW) {
9822 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9823 			bbr->r_wanted_output = 1;
9824 			return (ret_val);
9825 		} else {
9826 			ctf_do_drop(m, NULL);
9827 			return (0);
9828 		}
9829 	}
9830 	/*
9831 	 * Ack processing.
9832 	 */
9833 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9834 		return (ret_val);
9835 	}
9836 	if (sbavail(&so->so_snd)) {
9837 		if (ctf_progress_timeout_check(tp, true)) {
9838 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9839 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9840 			return (1);
9841 		}
9842 	}
9843 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9844 	    tiwin, thflags, nxt_pkt));
9845 }
9846 
9847 static void
9848 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr)
9849 {
9850 	/*
9851 	 * Assure no timers are running.
9852 	 */
9853 	if (tcp_timer_active(tp, TT_PERSIST)) {
9854 		/* We enter in persists, set the flag appropriately */
9855 		bbr->rc_in_persist = 1;
9856 	}
9857 	if (tcp_in_hpts(bbr->rc_tp)) {
9858 		tcp_hpts_remove(bbr->rc_tp);
9859 	}
9860 }
9861 
9862 static void
9863 bbr_google_mode_on(struct tcp_bbr *bbr)
9864 {
9865 	bbr->rc_use_google = 1;
9866 	bbr->rc_no_pacing = 0;
9867 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9868 	bbr->r_use_policer = bbr_policer_detection_enabled;
9869 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9870 	bbr->bbr_use_rack_cheat = 0;
9871 	bbr->r_ctl.rc_incr_tmrs = 0;
9872 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9873 	bbr->r_ctl.rc_inc_ip_oh = 0;
9874 	bbr->r_ctl.rc_inc_enet_oh = 0;
9875 	reset_time(&bbr->r_ctl.rc_delrate,
9876 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9877 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9878 			 (11 * USECS_IN_SECOND));
9879 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9880 }
9881 
9882 static void
9883 bbr_google_mode_off(struct tcp_bbr *bbr)
9884 {
9885 	bbr->rc_use_google = 0;
9886 	bbr->r_ctl.bbr_google_discount = 0;
9887 	bbr->no_pacing_until = bbr_no_pacing_until;
9888 	bbr->r_use_policer = 0;
9889 	if (bbr->no_pacing_until)
9890 		bbr->rc_no_pacing = 1;
9891 	else
9892 		bbr->rc_no_pacing = 0;
9893 	if (bbr_use_rack_resend_cheat)
9894 		bbr->bbr_use_rack_cheat = 1;
9895 	else
9896 		bbr->bbr_use_rack_cheat = 0;
9897 	if (bbr_incr_timers)
9898 		bbr->r_ctl.rc_incr_tmrs = 1;
9899 	else
9900 		bbr->r_ctl.rc_incr_tmrs = 0;
9901 	if (bbr_include_tcp_oh)
9902 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9903 	else
9904 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9905 	if (bbr_include_ip_oh)
9906 		bbr->r_ctl.rc_inc_ip_oh = 1;
9907 	else
9908 		bbr->r_ctl.rc_inc_ip_oh = 0;
9909 	if (bbr_include_enet_oh)
9910 		bbr->r_ctl.rc_inc_enet_oh = 1;
9911 	else
9912 		bbr->r_ctl.rc_inc_enet_oh = 0;
9913 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9914 	reset_time(&bbr->r_ctl.rc_delrate,
9915 		   bbr_num_pktepo_for_del_limit);
9916 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9917 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9918 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9919 }
9920 /*
9921  * Return 0 on success, non-zero on failure
9922  * which indicates the error (usually no memory).
9923  */
9924 static int
9925 bbr_init(struct tcpcb *tp, void **ptr)
9926 {
9927 	struct inpcb *inp = tptoinpcb(tp);
9928 	struct tcp_bbr *bbr = NULL;
9929 	uint32_t cts;
9930 
9931 	*ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
9932 	if (*ptr == NULL) {
9933 		/*
9934 		 * We need to allocate memory but cant. The INP and INP_INFO
9935 		 * locks and they are recursive (happens during setup. So a
9936 		 * scheme to drop the locks fails :(
9937 		 *
9938 		 */
9939 		return (ENOMEM);
9940 	}
9941 	bbr = (struct tcp_bbr *)*ptr;
9942 	bbr->rtt_valid = 0;
9943 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
9944 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
9945 	/* Take off any undesired flags */
9946 	tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
9947 	tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
9948 	tp->t_flags2 &= ~TF2_MBUF_ACKCMP;
9949 	tp->t_flags2 &= ~TF2_MBUF_L_ACKS;
9950 
9951 	TAILQ_INIT(&bbr->r_ctl.rc_map);
9952 	TAILQ_INIT(&bbr->r_ctl.rc_free);
9953 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
9954 	bbr->rc_tp = tp;
9955 	bbr->rc_inp = inp;
9956 	cts = tcp_get_usecs(&bbr->rc_tv);
9957 	tp->t_acktime = 0;
9958 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
9959 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
9960 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
9961 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
9962 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
9963 	bbr->r_ctl.rc_min_to = bbr_min_to;
9964 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
9965 	bbr->r_ctl.bbr_lost_at_state = 0;
9966 	bbr->r_ctl.rc_lost_at_startup = 0;
9967 	bbr->rc_all_timers_stopped = 0;
9968 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
9969 	bbr->r_ctl.rc_pkt_epoch_del = 0;
9970 	bbr->r_ctl.rc_pkt_epoch = 0;
9971 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
9972 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
9973 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
9974 	bbr->r_ctl.rc_went_idle_time = cts;
9975 	bbr->rc_pacer_started = cts;
9976 	bbr->r_ctl.rc_pkt_epoch_time = cts;
9977 	bbr->r_ctl.rc_rcvtime = cts;
9978 	bbr->r_ctl.rc_bbr_state_time = cts;
9979 	bbr->r_ctl.rc_del_time = cts;
9980 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
9981 	bbr->r_ctl.last_in_probertt = cts;
9982 	bbr->skip_gain = 0;
9983 	bbr->gain_is_limited = 0;
9984 	bbr->no_pacing_until = bbr_no_pacing_until;
9985 	if (bbr->no_pacing_until)
9986 		bbr->rc_no_pacing = 1;
9987 	if (bbr_use_google_algo) {
9988 		bbr->rc_no_pacing = 0;
9989 		bbr->rc_use_google = 1;
9990 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9991 		bbr->r_use_policer = bbr_policer_detection_enabled;
9992 	} else {
9993 		bbr->rc_use_google = 0;
9994 		bbr->r_ctl.bbr_google_discount = 0;
9995 		bbr->r_use_policer = 0;
9996 	}
9997 	if (bbr_ts_limiting)
9998 		bbr->rc_use_ts_limit = 1;
9999 	else
10000 		bbr->rc_use_ts_limit = 0;
10001 	if (bbr_ts_can_raise)
10002 		bbr->ts_can_raise = 1;
10003 	else
10004 		bbr->ts_can_raise = 0;
10005 	if (V_tcp_delack_enabled == 1)
10006 		tp->t_delayed_ack = 2;
10007 	else if (V_tcp_delack_enabled == 0)
10008 		tp->t_delayed_ack = 0;
10009 	else if (V_tcp_delack_enabled < 100)
10010 		tp->t_delayed_ack = V_tcp_delack_enabled;
10011 	else
10012 		tp->t_delayed_ack = 2;
10013 	if (bbr->rc_use_google == 0)
10014 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10015 	else
10016 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10017 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10018 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10019 	bbr->rc_init_win = bbr_def_init_win;
10020 	if (tp->t_flags & TF_REQ_TSTMP)
10021 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10022 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10023 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10024 	bbr->r_init_rtt = 1;
10025 
10026 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10027 	if (bbr_allow_hdwr_pacing)
10028 		bbr->bbr_hdw_pace_ena = 1;
10029 	else
10030 		bbr->bbr_hdw_pace_ena = 0;
10031 	if (bbr_sends_full_iwnd)
10032 		bbr->bbr_init_win_cheat = 1;
10033 	else
10034 		bbr->bbr_init_win_cheat = 0;
10035 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10036 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10037 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10038 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10039 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10040 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10041 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10042 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10043 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10044 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10045 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10046 	bbr->r_ctl.rc_rtt_shrinks = cts;
10047 	if (bbr->rc_use_google) {
10048 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10049 				  FILTER_TYPE_MAX,
10050 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10051 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10052 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10053 	} else {
10054 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10055 				  FILTER_TYPE_MAX,
10056 				  bbr_num_pktepo_for_del_limit);
10057 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10058 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10059 	}
10060 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10061 	if (bbr_uses_idle_restart)
10062 		bbr->rc_use_idle_restart = 1;
10063 	else
10064 		bbr->rc_use_idle_restart = 0;
10065 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10066 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10067 	if (bbr_resends_use_tso)
10068 		bbr->rc_resends_use_tso = 1;
10069 	if (tp->snd_una != tp->snd_max) {
10070 		/* Create a send map for the current outstanding data */
10071 		struct bbr_sendmap *rsm;
10072 
10073 		rsm = bbr_alloc(bbr);
10074 		if (rsm == NULL) {
10075 			uma_zfree(bbr_pcb_zone, *ptr);
10076 			*ptr = NULL;
10077 			return (ENOMEM);
10078 		}
10079 		rsm->r_rtt_not_allowed = 1;
10080 		rsm->r_tim_lastsent[0] = cts;
10081 		rsm->r_rtr_cnt = 1;
10082 		rsm->r_rtr_bytes = 0;
10083 		rsm->r_start = tp->snd_una;
10084 		rsm->r_end = tp->snd_max;
10085 		rsm->r_dupack = 0;
10086 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10087 		rsm->r_ts_valid = 0;
10088 		rsm->r_del_ack_ts = tp->ts_recent;
10089 		rsm->r_del_time = cts;
10090 		if (bbr->r_ctl.r_app_limited_until)
10091 			rsm->r_app_limited = 1;
10092 		else
10093 			rsm->r_app_limited = 0;
10094 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10095 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10096 		rsm->r_in_tmap = 1;
10097 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10098 			rsm->r_bbr_state = bbr_state_val(bbr);
10099 		else
10100 			rsm->r_bbr_state = 8;
10101 	}
10102 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10103 		bbr->bbr_use_rack_cheat = 1;
10104 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10105 		bbr->r_ctl.rc_incr_tmrs = 1;
10106 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10107 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10108 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10109 		bbr->r_ctl.rc_inc_ip_oh = 1;
10110 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10111 		bbr->r_ctl.rc_inc_enet_oh = 1;
10112 
10113 	bbr_log_type_statechange(bbr, cts, __LINE__);
10114 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10115 	    (tp->t_srtt)) {
10116 		uint32_t rtt;
10117 
10118 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10119 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10120 	}
10121 	/* announce the settings and state */
10122 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10123 	tcp_bbr_tso_size_check(bbr, cts);
10124 	/*
10125 	 * Now call the generic function to start a timer. This will place
10126 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10127 	 * flags.
10128 	 */
10129 	bbr_stop_all_timers(tp, bbr);
10130 	/*
10131 	 * Validate the timers are not in usec, if they are convert.
10132 	 * BBR should in theory move to USEC and get rid of a
10133 	 * lot of the TICKS_2 calls.. but for now we stay
10134 	 * with tick timers.
10135 	 */
10136 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
10137 	TCPT_RANGESET(tp->t_rxtcur,
10138 	    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
10139 	    tp->t_rttmin, TCPTV_REXMTMAX);
10140 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10141 	return (0);
10142 }
10143 
10144 /*
10145  * Return 0 if we can accept the connection. Return
10146  * non-zero if we can't handle the connection. A EAGAIN
10147  * means you need to wait until the connection is up.
10148  * a EADDRNOTAVAIL means we can never handle the connection
10149  * (no SACK).
10150  */
10151 static int
10152 bbr_handoff_ok(struct tcpcb *tp)
10153 {
10154 	if ((tp->t_state == TCPS_CLOSED) ||
10155 	    (tp->t_state == TCPS_LISTEN)) {
10156 		/* Sure no problem though it may not stick */
10157 		return (0);
10158 	}
10159 	if ((tp->t_state == TCPS_SYN_SENT) ||
10160 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10161 		/*
10162 		 * We really don't know you have to get to ESTAB or beyond
10163 		 * to tell.
10164 		 */
10165 		return (EAGAIN);
10166 	}
10167 	if (tp->t_flags & TF_SENTFIN)
10168 		return (EINVAL);
10169 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10170 		return (0);
10171 	}
10172 	/*
10173 	 * If we reach here we don't do SACK on this connection so we can
10174 	 * never do rack.
10175 	 */
10176 	return (EINVAL);
10177 }
10178 
10179 static void
10180 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10181 {
10182 	if (tp->t_fb_ptr) {
10183 		uint32_t calc;
10184 		struct tcp_bbr *bbr;
10185 		struct bbr_sendmap *rsm;
10186 
10187 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10188 		if (bbr->r_ctl.crte)
10189 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10190 		bbr_log_flowend(bbr);
10191 		bbr->rc_tp = NULL;
10192 		if (bbr->bbr_hdrw_pacing)
10193 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10194 		else
10195 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10196 		if (bbr->r_ctl.crte != NULL) {
10197 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10198 			bbr->r_ctl.crte = NULL;
10199 		}
10200 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10201 		while (rsm) {
10202 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10203 			uma_zfree(bbr_zone, rsm);
10204 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10205 		}
10206 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10207 		while (rsm) {
10208 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10209 			uma_zfree(bbr_zone, rsm);
10210 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10211 		}
10212 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10213 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10214 			BBR_STAT_INC(bbr_dynamic_rwnd);
10215 		else
10216 			BBR_STAT_INC(bbr_static_rwnd);
10217 		bbr->r_ctl.rc_free_cnt = 0;
10218 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10219 		tp->t_fb_ptr = NULL;
10220 	}
10221 	/* Make sure snd_nxt is correctly set */
10222 	tp->snd_nxt = tp->snd_max;
10223 }
10224 
10225 static void
10226 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10227 {
10228 	switch (tp->t_state) {
10229 	case TCPS_SYN_SENT:
10230 		bbr->r_state = TCPS_SYN_SENT;
10231 		bbr->r_substate = bbr_do_syn_sent;
10232 		break;
10233 	case TCPS_SYN_RECEIVED:
10234 		bbr->r_state = TCPS_SYN_RECEIVED;
10235 		bbr->r_substate = bbr_do_syn_recv;
10236 		break;
10237 	case TCPS_ESTABLISHED:
10238 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10239 		bbr->r_state = TCPS_ESTABLISHED;
10240 		bbr->r_substate = bbr_do_established;
10241 		break;
10242 	case TCPS_CLOSE_WAIT:
10243 		bbr->r_state = TCPS_CLOSE_WAIT;
10244 		bbr->r_substate = bbr_do_close_wait;
10245 		break;
10246 	case TCPS_FIN_WAIT_1:
10247 		bbr->r_state = TCPS_FIN_WAIT_1;
10248 		bbr->r_substate = bbr_do_fin_wait_1;
10249 		break;
10250 	case TCPS_CLOSING:
10251 		bbr->r_state = TCPS_CLOSING;
10252 		bbr->r_substate = bbr_do_closing;
10253 		break;
10254 	case TCPS_LAST_ACK:
10255 		bbr->r_state = TCPS_LAST_ACK;
10256 		bbr->r_substate = bbr_do_lastack;
10257 		break;
10258 	case TCPS_FIN_WAIT_2:
10259 		bbr->r_state = TCPS_FIN_WAIT_2;
10260 		bbr->r_substate = bbr_do_fin_wait_2;
10261 		break;
10262 	case TCPS_LISTEN:
10263 	case TCPS_CLOSED:
10264 	case TCPS_TIME_WAIT:
10265 	default:
10266 		break;
10267 	};
10268 }
10269 
10270 static void
10271 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10272 {
10273 	/*
10274 	 * Now what state are we going into now? Is there adjustments
10275 	 * needed?
10276 	 */
10277 	int32_t old_state;
10278 
10279 	old_state = bbr_state_val(bbr);
10280 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10281 		/* Save the lowest srtt we saw in our end of the sub-state */
10282 		bbr->rc_hit_state_1 = 0;
10283 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10284 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10285 	}
10286 	bbr->rc_bbr_substate++;
10287 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10288 		/* Cycle back to first state-> gain */
10289 		bbr->rc_bbr_substate = 0;
10290 	}
10291 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10292 		/*
10293 		 * We enter the gain(5/4) cycle (possibly less if
10294 		 * shallow buffer detection is enabled)
10295 		 */
10296 		if (bbr->skip_gain) {
10297 			/*
10298 			 * Hardware pacing has set our rate to
10299 			 * the max and limited our b/w just
10300 			 * do level i.e. no gain.
10301 			 */
10302 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10303 		} else if (bbr->gain_is_limited &&
10304 			   bbr->bbr_hdrw_pacing &&
10305 			   bbr->r_ctl.crte) {
10306 			/*
10307 			 * We can't gain above the hardware pacing
10308 			 * rate which is less than our rate + the gain
10309 			 * calculate the gain needed to reach the hardware
10310 			 * pacing rate..
10311 			 */
10312 			uint64_t bw, rate, gain_calc;
10313 
10314 			bw = bbr_get_bw(bbr);
10315 			rate = bbr->r_ctl.crte->rate;
10316 			if ((rate > bw) &&
10317 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10318 				gain_calc = (rate * BBR_UNIT) / bw;
10319 				if (gain_calc < BBR_UNIT)
10320 					gain_calc = BBR_UNIT;
10321 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10322 			} else {
10323 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10324 			}
10325 		} else
10326 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10327 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10328 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10329 		} else
10330 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10331 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10332 		bbr->rc_hit_state_1 = 1;
10333 		bbr->r_ctl.rc_exta_time_gd = 0;
10334 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10335 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10336 		if (bbr_state_drain_2_tar) {
10337 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10338 		} else
10339 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10340 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10341 	} else {
10342 		/* All other cycles hit here 2-7 */
10343 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10344 			if (bbr_sub_drain_slam_cwnd &&
10345 			    (bbr->rc_use_google == 0) &&
10346 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10347 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10348 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10349 			}
10350 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10351 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10352 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10353 			else
10354 				bbr->r_ctl.rc_exta_time_gd = 0;
10355 			if (bbr->r_ctl.rc_exta_time_gd) {
10356 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10357 				/* Now chop up the time for each state (div by 7) */
10358 				bbr->r_ctl.rc_level_state_extra /= 7;
10359 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10360 					/* Add a randomization */
10361 					bbr_randomize_extra_state_time(bbr);
10362 				}
10363 			}
10364 		}
10365 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10366 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10367 	}
10368 	if (bbr->rc_use_google) {
10369 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10370 	}
10371 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10372 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10373 	if (dolog)
10374 		bbr_log_type_statechange(bbr, cts, line);
10375 
10376 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10377 		uint32_t time_in;
10378 
10379 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10380 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10381 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10382 		} else {
10383 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10384 		}
10385 	}
10386 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10387 	bbr_set_state_target(bbr, __LINE__);
10388 	if (bbr_sub_drain_slam_cwnd &&
10389 	    (bbr->rc_use_google == 0) &&
10390 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10391 		/* Slam down the cwnd */
10392 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10393 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10394 		if (bbr_sub_drain_app_limit) {
10395 			/* Go app limited if we are on a long drain */
10396 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10397 							  ctf_flight_size(bbr->rc_tp,
10398 							      (bbr->r_ctl.rc_sacked +
10399 							       bbr->r_ctl.rc_lost_bytes)));
10400 		}
10401 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10402 	}
10403 	if (bbr->rc_lt_use_bw) {
10404 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10405 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10406 	}
10407 	/* Google changes TSO size every cycle */
10408 	if (bbr->rc_use_google)
10409 		tcp_bbr_tso_size_check(bbr, cts);
10410 	bbr->r_ctl.gain_epoch = cts;
10411 	bbr->r_ctl.rc_bbr_state_time = cts;
10412 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10413 }
10414 
10415 static void
10416 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10417 {
10418 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10419 	    (google_allow_early_out == 1) &&
10420 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10421 		/* We have reached out target flight size possibly early */
10422 		goto change_state;
10423 	}
10424 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10425 		return;
10426 	}
10427 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10428 		/*
10429 		 * Must be a rttProp movement forward before
10430 		 * we can change states.
10431 		 */
10432 		return;
10433 	}
10434 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10435 		/*
10436 		 * The needed time has passed but for
10437 		 * the gain cycle extra rules apply:
10438 		 * 1) If we have seen loss, we exit
10439 		 * 2) If we have not reached the target
10440 		 *    we stay in GAIN (gain-to-target).
10441 		 */
10442 		if (google_consider_lost && losses)
10443 			goto change_state;
10444 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10445 			return;
10446 		}
10447 	}
10448 change_state:
10449 	/* For gain we must reach our target, all others last 1 rttProp */
10450 	bbr_substate_change(bbr, cts, __LINE__, 1);
10451 }
10452 
10453 static void
10454 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10455 {
10456 	uint32_t flight, bbr_cur_cycle_time;
10457 
10458 	if (bbr->rc_use_google) {
10459 		bbr_set_probebw_google_gains(bbr, cts, losses);
10460 		return;
10461 	}
10462 	if (cts == 0) {
10463 		/*
10464 		 * Never alow cts to be 0 we
10465 		 * do this so we can judge if
10466 		 * we have set a timestamp.
10467 		 */
10468 		cts = 1;
10469 	}
10470 	if (bbr_state_is_pkt_epoch)
10471 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10472 	else
10473 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10474 
10475 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10476 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10477 			flight = ctf_flight_size(bbr->rc_tp,
10478 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10479 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10480 				/* Keep it slam down */
10481 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10482 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10483 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10484 				}
10485 				if (bbr_sub_drain_app_limit) {
10486 					/* Go app limited if we are on a long drain */
10487 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10488 				}
10489 			}
10490 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10491 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10492 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10493 				/*
10494 				 * Still here after the same time as
10495 				 * the gain. We need to drain harder
10496 				 * for the next srtt. Reduce by a set amount
10497 				 * the gain drop is capped at DRAIN states
10498 				 * value (88).
10499 				 */
10500 				bbr->r_ctl.flightsize_at_drain = flight;
10501 				if (bbr_drain_drop_mul &&
10502 				    bbr_drain_drop_div &&
10503 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10504 					/* Use your specific drop value (def 4/5 = 20%) */
10505 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10506 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10507 				} else {
10508 					/* You get drop of 20% */
10509 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10510 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10511 				}
10512 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10513 					/* Reduce our gain again to the bottom  */
10514 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10515 				}
10516 				bbr_log_exit_gain(bbr, cts, 4);
10517 				/*
10518 				 * Extend out so we wait another
10519 				 * epoch before dropping again.
10520 				 */
10521 				bbr->r_ctl.gain_epoch = cts;
10522 			}
10523 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10524 				if (bbr_sub_drain_slam_cwnd &&
10525 				    (bbr->rc_use_google == 0) &&
10526 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10527 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10528 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10529 				}
10530 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10531 				bbr_log_exit_gain(bbr, cts, 3);
10532 			}
10533 		} else {
10534 			/* Its a gain  */
10535 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10536 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10537 				goto change_state;
10538 			}
10539 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10540 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10541 			     bbr->rc_tp->snd_wnd)) {
10542 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10543 				bbr_log_exit_gain(bbr, cts, 2);
10544 			}
10545 		}
10546 		/**
10547 		 * We fall through and return always one of two things has
10548 		 * occurred.
10549 		 * 1) We are still not at target
10550 		 *    <or>
10551 		 * 2) We reached the target and set rc_bbr_state_atflight
10552 		 *    which means we no longer hit this block
10553 		 *    next time we are called.
10554 		 */
10555 		return;
10556 	}
10557 change_state:
10558 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10559 		return;
10560 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10561 		/* Less than a full time-period has passed */
10562 		return;
10563 	}
10564 	if (bbr->r_ctl.rc_level_state_extra &&
10565 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10566 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10567 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10568 		/* Less than a full time-period + extra has passed */
10569 		return;
10570 	}
10571 	if (bbr_gain_gets_extra_too &&
10572 	    bbr->r_ctl.rc_level_state_extra &&
10573 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10574 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10575 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10576 		/* Less than a full time-period + extra has passed */
10577 		return;
10578 	}
10579 	bbr_substate_change(bbr, cts, __LINE__, 1);
10580 }
10581 
10582 static uint32_t
10583 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10584 {
10585 	uint32_t mss, tar;
10586 
10587 	if (bbr->rc_use_google) {
10588 		/* Google just uses the cwnd target */
10589 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10590 	} else {
10591 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10592 			  bbr->r_ctl.rc_pace_max_segs);
10593 		/* Get the base cwnd with gain rounded to a mss */
10594 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10595 						      gain), mss);
10596 		/* Make sure it is within our min */
10597 		if (tar < get_min_cwnd(bbr))
10598 			return (get_min_cwnd(bbr));
10599 	}
10600 	return (tar);
10601 }
10602 
10603 static void
10604 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10605 {
10606 	uint32_t tar, meth;
10607 
10608 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10609 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10610 		/* Special case using old probe-rtt method */
10611 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10612 		meth = 1;
10613 	} else {
10614 		/* Non-probe-rtt case and reduced probe-rtt  */
10615 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10616 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10617 			/* For gain cycle we use the hptsi gain */
10618 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10619 			meth = 2;
10620 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10621 			/*
10622 			 * If configured, or for google all other states
10623 			 * get BBR_UNIT.
10624 			 */
10625 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10626 			meth = 3;
10627 		} else {
10628 			/*
10629 			 * Or we set a target based on the pacing gain
10630 			 * for non-google mode and default (non-configured).
10631 			 * Note we don't set a target goal below drain (192).
10632 			 */
10633 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10634 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10635 				meth = 4;
10636 			} else {
10637 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10638 				meth = 5;
10639 			}
10640 		}
10641 	}
10642 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10643 	bbr->r_ctl.rc_target_at_state = tar;
10644 }
10645 
10646 static void
10647 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10648 {
10649 	/* Change to probe_rtt */
10650 	uint32_t time_in;
10651 
10652 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10653 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10654 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10655 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10656 					  + bbr->r_ctl.rc_delivered);
10657 	/* Setup so we force feed the filter */
10658 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10659 		bbr->rc_prtt_set_ts = 1;
10660 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10661 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10662 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10663 	}
10664 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10665 	bbr->r_ctl.rc_rtt_shrinks = cts;
10666 	bbr->r_ctl.last_in_probertt = cts;
10667 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10668 	bbr->r_ctl.rc_bbr_state_time = cts;
10669 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10670 	/* We need to force the filter to update */
10671 
10672 	if ((bbr_sub_drain_slam_cwnd) &&
10673 	    bbr->rc_hit_state_1 &&
10674 	    (bbr->rc_use_google == 0) &&
10675 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10676 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10677 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10678 	} else
10679 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10680 	/* Update the lost */
10681 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10682 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10683 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10684 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10685 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10686 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10687 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10688 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10689 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10690 	} else {
10691 		/*
10692 		 * We bring it down slowly by using a hptsi gain that is
10693 		 * probably 75%. This will slowly float down our outstanding
10694 		 * without tampering with the cwnd.
10695 		 */
10696 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10697 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10698 		bbr_set_state_target(bbr, __LINE__);
10699 		if (bbr_prtt_slam_cwnd &&
10700 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10701 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10702 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10703 		}
10704 	}
10705 	if (ctf_flight_size(bbr->rc_tp,
10706 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10707 	    bbr->r_ctl.rc_target_at_state) {
10708 		/* We are at target */
10709 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10710 	} else {
10711 		/* We need to come down to reach target before our time begins */
10712 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10713 	}
10714 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10715 	BBR_STAT_INC(bbr_enter_probertt);
10716 	bbr_log_exit_gain(bbr, cts, 0);
10717 	bbr_log_type_statechange(bbr, cts, line);
10718 }
10719 
10720 static void
10721 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10722 {
10723 	/*
10724 	 * Sanity check on probe-rtt intervals.
10725 	 * In crazy situations where we are competing
10726 	 * against new-reno flows with huge buffers
10727 	 * our rtt-prop interval could come to dominate
10728 	 * things if we can't get through a full set
10729 	 * of cycles, we need to adjust it.
10730 	 */
10731 	if (bbr_can_adjust_probertt &&
10732 	    (bbr->rc_use_google == 0)) {
10733 		uint16_t val = 0;
10734 		uint32_t cur_rttp, fval, newval, baseval;
10735 
10736 		/* Are we to small and go into probe-rtt to often? */
10737 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10738 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10739 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10740 		if (bbr_is_ratio == 0) {
10741 			if (fval > bbr_rtt_probe_limit)
10742 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10743 			else
10744 				newval = cur_rttp;
10745 		} else {
10746 			int mul;
10747 
10748 			mul = fval / bbr_rtt_probe_limit;
10749 			newval = cur_rttp * mul;
10750 		}
10751 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10752 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10753 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10754 			val = 1;
10755 		} else {
10756 			/*
10757 			 * No adjustments were made
10758 			 * do we need to shrink it?
10759 			 */
10760 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10761 				if (cur_rttp <= bbr_rtt_probe_limit) {
10762 					/*
10763 					 * Things have calmed down lets
10764 					 * shrink all the way to default
10765 					 */
10766 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10767 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10768 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10769 					cur_rttp = bbr_rtt_probe_limit;
10770 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10771 					val = 2;
10772 				} else {
10773 					/*
10774 					 * Well does some adjustment make sense?
10775 					 */
10776 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10777 						/* We can reduce interval time some */
10778 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10779 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10780 						val = 3;
10781 					}
10782 				}
10783 			}
10784 		}
10785 		if (val)
10786 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10787 	}
10788 }
10789 
10790 static void
10791 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10792 {
10793 	/* Exit probe-rtt */
10794 
10795 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10796 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10797 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10798 	}
10799 	bbr_log_exit_gain(bbr, cts, 1);
10800 	bbr->rc_hit_state_1 = 0;
10801 	bbr->r_ctl.rc_rtt_shrinks = cts;
10802 	bbr->r_ctl.last_in_probertt = cts;
10803 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10804 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10805 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10806 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10807 					  bbr->r_ctl.rc_delivered);
10808 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10809 		uint32_t time_in;
10810 
10811 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10812 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10813 	}
10814 	if (bbr->rc_filled_pipe) {
10815 		/* Switch to probe_bw */
10816 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10817 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10818 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10819 		bbr_substate_change(bbr, cts, __LINE__, 0);
10820 		bbr_log_type_statechange(bbr, cts, __LINE__);
10821 	} else {
10822 		/* Back to startup */
10823 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10824 		bbr->r_ctl.rc_bbr_state_time = cts;
10825 		/*
10826 		 * We don't want to give a complete free 3
10827 		 * measurements until we exit, so we use
10828 		 * the number of pe's we were in probe-rtt
10829 		 * to add to the startup_epoch. That way
10830 		 * we will still retain the old state.
10831 		 */
10832 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10833 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10834 		/* Make sure to use the lower pg when shifting back in */
10835 		if (bbr->r_ctl.rc_lost &&
10836 		    bbr_use_lower_gain_in_startup &&
10837 		    (bbr->rc_use_google == 0))
10838 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10839 		else
10840 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10841 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10842 		/* Probably not needed but set it anyway */
10843 		bbr_set_state_target(bbr, __LINE__);
10844 		bbr_log_type_statechange(bbr, cts, __LINE__);
10845 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10846 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10847 	}
10848 	bbr_check_probe_rtt_limits(bbr, cts);
10849 }
10850 
10851 static int32_t inline
10852 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10853 {
10854 	if ((bbr->rc_past_init_win == 1) &&
10855 	    (bbr->rc_in_persist == 0) &&
10856 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10857 		return (1);
10858 	}
10859 	if (bbr_can_force_probertt &&
10860 	    (bbr->rc_in_persist == 0) &&
10861 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10862 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10863 		return (1);
10864 	}
10865 	return (0);
10866 }
10867 
10868 static int32_t
10869 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10870 {
10871 	uint64_t btlbw, gain;
10872 	if (pkt_epoch == 0) {
10873 		/*
10874 		 * Need to be on a pkt-epoch to continue.
10875 		 */
10876 		return (0);
10877 	}
10878 	btlbw = bbr_get_full_bw(bbr);
10879 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10880 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10881 	if (btlbw >= gain) {
10882 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10883 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10884 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10885 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10886 	}
10887 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10888 		return (1);
10889 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10890 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10891 	return(0);
10892 }
10893 
10894 static int32_t inline
10895 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10896 {
10897 	/* Have we gained 25% in the last 3 packet based epoch's? */
10898 	uint64_t btlbw, gain;
10899 	int do_exit;
10900 	int delta, rtt_gain;
10901 
10902 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10903 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10904 		/*
10905 		 * This qualifies as a RTT_PROBE session since we drop the
10906 		 * data outstanding to nothing and waited more than
10907 		 * bbr_rtt_probe_time.
10908 		 */
10909 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10910 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10911 	}
10912 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10913 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10914 		return (0);
10915 	}
10916 	if (bbr->rc_use_google)
10917 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10918 
10919 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10920 	    (bbr_use_lower_gain_in_startup)) {
10921 		/* Drop to a lower gain 1.5 x since we saw loss */
10922 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10923 	}
10924 	if (pkt_epoch == 0) {
10925 		/*
10926 		 * Need to be on a pkt-epoch to continue.
10927 		 */
10928 		return (0);
10929 	}
10930 	if (bbr_rtt_gain_thresh) {
10931 		/*
10932 		 * Do we allow a flow to stay
10933 		 * in startup with no loss and no
10934 		 * gain in rtt over a set threshold?
10935 		 */
10936 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
10937 		    bbr->r_ctl.startup_last_srtt &&
10938 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
10939 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
10940 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
10941 		} else
10942 			rtt_gain = 0;
10943 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
10944 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
10945 			/* First time or new lower value */
10946 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
10947 
10948 		if ((bbr->r_ctl.rc_lost == 0) &&
10949 		    (rtt_gain < bbr_rtt_gain_thresh)) {
10950 			/*
10951 			 * No loss, and we are under
10952 			 * our gain threhold for
10953 			 * increasing RTT.
10954 			 */
10955 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10956 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
10957 			bbr_log_startup_event(bbr, cts, rtt_gain,
10958 					      delta, bbr->r_ctl.startup_last_srtt, 10);
10959 			return (0);
10960 		}
10961 	}
10962 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
10963 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
10964 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
10965 		/*
10966 		 * We only assess if we have a new measurement when
10967 		 * we have no loss and are not in recovery.
10968 		 * Drag up by one our last_startup epoch so we will hold
10969 		 * the number of non-gain we have already accumulated.
10970 		 */
10971 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10972 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
10973 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10974 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
10975 		return (0);
10976 	}
10977 	/* Case where we reduced the lost (bad retransmit) */
10978 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
10979 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10980 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
10981 	btlbw = bbr_get_full_bw(bbr);
10982 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
10983 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10984 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10985 	else
10986 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10987 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10988 	do_exit = 0;
10989 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
10990 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10991 	if (btlbw >= gain) {
10992 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10993 		/* Update the lost so we won't exit in next set of tests */
10994 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10995 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10996 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10997 	}
10998 	if ((bbr->rc_loss_exit &&
10999 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11000 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11001 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11002 		/*
11003 		 * If we had no gain,  we had loss and that loss was above
11004 		 * our threshould, the rwnd is not constrained, and we have
11005 		 * had at least 3 packet epochs exit. Note that this is
11006 		 * switched off by sysctl. Google does not do this by the
11007 		 * way.
11008 		 */
11009 		if ((ctf_flight_size(bbr->rc_tp,
11010 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11011 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11012 			do_exit = 1;
11013 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11014 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11015 		} else {
11016 			/* Just record an updated loss value */
11017 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11018 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11019 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11020 		}
11021 	} else
11022 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11023 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11024 	    do_exit) {
11025 		/* Return 1 to exit the startup state. */
11026 		return (1);
11027 	}
11028 	/* Stay in startup */
11029 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11030 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11031 	return (0);
11032 }
11033 
11034 static void
11035 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11036 {
11037 	/*
11038 	 * A tick occurred in the rtt epoch do we need to do anything?
11039 	 */
11040 #ifdef BBR_INVARIANTS
11041 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11042 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11043 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11044 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11045 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11046 		/* Debug code? */
11047 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11048 	}
11049 #endif
11050 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11051 		/* Do we exit the startup state? */
11052 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11053 			uint32_t time_in;
11054 
11055 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11056 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11057 			bbr->rc_filled_pipe = 1;
11058 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11059 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11060 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11061 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11062 			} else
11063 				time_in = 0;
11064 			if (bbr->rc_no_pacing)
11065 				bbr->rc_no_pacing = 0;
11066 			bbr->r_ctl.rc_bbr_state_time = cts;
11067 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11068 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11069 			bbr_set_state_target(bbr, __LINE__);
11070 			if ((bbr->rc_use_google == 0) &&
11071 			    bbr_slam_cwnd_in_main_drain) {
11072 				/* Here we don't have to worry about probe-rtt */
11073 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11074 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11075 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11076 			}
11077 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11078 			bbr_log_type_statechange(bbr, cts, __LINE__);
11079 			if (ctf_flight_size(bbr->rc_tp,
11080 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11081 			    bbr->r_ctl.rc_target_at_state) {
11082 				/*
11083 				 * Switch to probe_bw if we are already
11084 				 * there
11085 				 */
11086 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11087 				bbr_substate_change(bbr, cts, __LINE__, 0);
11088 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11089 				bbr_log_type_statechange(bbr, cts, __LINE__);
11090 			}
11091 		}
11092 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11093 		uint32_t inflight;
11094 		struct tcpcb *tp;
11095 
11096 		tp = bbr->rc_tp;
11097 		inflight = ctf_flight_size(tp,
11098 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11099 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11100 			/* We have reached a flight of the cwnd target */
11101 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11102 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11103 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11104 			bbr_set_state_target(bbr, __LINE__);
11105 			/*
11106 			 * Rig it so we don't do anything crazy and
11107 			 * start fresh with a new randomization.
11108 			 */
11109 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11110 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11111 			bbr_substate_change(bbr, cts, __LINE__, 1);
11112 		}
11113 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11114 		/* Has in-flight reached the bdp (or less)? */
11115 		uint32_t inflight;
11116 		struct tcpcb *tp;
11117 
11118 		tp = bbr->rc_tp;
11119 		inflight = ctf_flight_size(tp,
11120 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11121 		if ((bbr->rc_use_google == 0) &&
11122 		    bbr_slam_cwnd_in_main_drain &&
11123 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11124 			/*
11125 			 * Here we don't have to worry about probe-rtt
11126 			 * re-slam it, but keep it slammed down.
11127 			 */
11128 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11129 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11130 		}
11131 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11132 			/* We have drained */
11133 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11134 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11135 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11136 				uint32_t time_in;
11137 
11138 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11139 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11140 			}
11141 			if ((bbr->rc_use_google == 0) &&
11142 			    bbr_slam_cwnd_in_main_drain &&
11143 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11144 				/* Restore the cwnd */
11145 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11146 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11147 			}
11148 			/* Setup probe-rtt has being done now RRS-HERE */
11149 			bbr->r_ctl.rc_rtt_shrinks = cts;
11150 			bbr->r_ctl.last_in_probertt = cts;
11151 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11152 			/* Randomly pick a sub-state */
11153 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11154 			bbr_substate_change(bbr, cts, __LINE__, 0);
11155 			bbr_log_type_statechange(bbr, cts, __LINE__);
11156 		}
11157 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11158 		uint32_t flight;
11159 
11160 		flight = ctf_flight_size(bbr->rc_tp,
11161 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11162 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11163 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11164 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11165 			/*
11166 			 * We must keep cwnd at the desired MSS.
11167 			 */
11168 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11169 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11170 		} else if ((bbr_prtt_slam_cwnd) &&
11171 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11172 			/* Re-slam it */
11173 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11174 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11175 		}
11176 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11177 			/* Has outstanding reached our target? */
11178 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11179 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11180 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11181 				/* If time is exactly 0, be 1usec off */
11182 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11183 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11184 				if (bbr->rc_use_google == 0) {
11185 					/*
11186 					 * Restore any lowering that as occurred to
11187 					 * reach here
11188 					 */
11189 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11190 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11191 					else
11192 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11193 				}
11194 			}
11195 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11196 			    (bbr->rc_use_google == 0) &&
11197 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11198 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11199 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11200 				/*
11201 				 * We have doddled with our current hptsi
11202 				 * gain an srtt and have still not made it
11203 				 * to target, or we have increased our flight.
11204 				 * Lets reduce the gain by xx%
11205 				 * flooring the reduce at DRAIN (based on
11206 				 * mul/div)
11207 				 */
11208 				int red;
11209 
11210 				bbr->r_ctl.flightsize_at_drain = flight;
11211 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11212 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11213 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11214 					/* Reduce our gain again */
11215 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11216 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11217 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11218 					/* one more chance before we give up */
11219 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11220 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11221 				} else {
11222 					/* At the very bottom */
11223 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11224 				}
11225 			}
11226 		}
11227 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11228 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11229 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11230 			/* Time to exit probe RTT normally */
11231 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11232 		}
11233 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11234 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11235 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11236 			/*
11237 			 * This qualifies as a RTT_PROBE session since we
11238 			 * drop the data outstanding to nothing and waited
11239 			 * more than bbr_rtt_probe_time.
11240 			 */
11241 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11242 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11243 		}
11244 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11245 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11246 		} else {
11247 			bbr_set_probebw_gains(bbr, cts, losses);
11248 		}
11249 	}
11250 }
11251 
11252 static void
11253 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11254 {
11255 	int32_t epoch = 0;
11256 
11257 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11258 		bbr_set_epoch(bbr, cts, line);
11259 		/* At each epoch doe lt bw sampling */
11260 		epoch = 1;
11261 	}
11262 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11263 }
11264 
11265 static int
11266 bbr_do_segment_nounlock(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11267     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos, int32_t nxt_pkt,
11268     struct timeval *tv)
11269 {
11270 	struct inpcb *inp = tptoinpcb(tp);
11271 	struct socket *so = tptosocket(tp);
11272 	int32_t thflags, retval;
11273 	uint32_t cts, lcts;
11274 	uint32_t tiwin;
11275 	struct tcpopt to;
11276 	struct tcp_bbr *bbr;
11277 	struct bbr_sendmap *rsm;
11278 	struct timeval ltv;
11279 	int32_t did_out = 0;
11280 	uint16_t nsegs;
11281 	int32_t prev_state;
11282 	uint32_t lost;
11283 
11284 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11285 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11286 	/* add in our stats */
11287 	kern_prefetch(bbr, &prev_state);
11288 	prev_state = 0;
11289 	thflags = tcp_get_flags(th);
11290 	/*
11291 	 * If this is either a state-changing packet or current state isn't
11292 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11293 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11294 	 * caller may have unnecessarily acquired a write lock due to a
11295 	 * race.
11296 	 */
11297 	INP_WLOCK_ASSERT(tptoinpcb(tp));
11298 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11299 	    __func__));
11300 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11301 	    __func__));
11302 
11303 	tp->t_rcvtime = ticks;
11304 	/*
11305 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11306 	 * the scale is zero.
11307 	 */
11308 	tiwin = th->th_win << tp->snd_scale;
11309 #ifdef STATS
11310 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11311 #endif
11312 
11313 	if (m->m_flags & M_TSTMP) {
11314 		/* Prefer the hardware timestamp if present */
11315 		struct timespec ts;
11316 
11317 		mbuf_tstmp2timespec(m, &ts);
11318 		bbr->rc_tv.tv_sec = ts.tv_sec;
11319 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11320 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11321 	} else if (m->m_flags & M_TSTMP_LRO) {
11322 		/* Next the arrival timestamp */
11323 		struct timespec ts;
11324 
11325 		mbuf_tstmp2timespec(m, &ts);
11326 		bbr->rc_tv.tv_sec = ts.tv_sec;
11327 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11328 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11329 	} else {
11330 		/*
11331 		 * Ok just get the current time.
11332 		 */
11333 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11334 	}
11335 	/*
11336 	 * Parse options on any incoming segment.
11337 	 */
11338 	tcp_dooptions(&to, (u_char *)(th + 1),
11339 	    (th->th_off << 2) - sizeof(struct tcphdr),
11340 	    (thflags & TH_SYN) ? TO_SYN : 0);
11341 
11342 	/*
11343 	 * If timestamps were negotiated during SYN/ACK and a
11344 	 * segment without a timestamp is received, silently drop
11345 	 * the segment, unless it is a RST segment or missing timestamps are
11346 	 * tolerated.
11347 	 * See section 3.2 of RFC 7323.
11348 	 */
11349 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11350 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11351 		retval = 0;
11352 		m_freem(m);
11353 		goto done_with_input;
11354 	}
11355 	/*
11356 	 * If echoed timestamp is later than the current time, fall back to
11357 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11358 	 * were used when this connection was established.
11359 	 */
11360 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11361 		to.to_tsecr -= tp->ts_offset;
11362 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11363 			to.to_tsecr = 0;
11364 	}
11365 	/*
11366 	 * If its the first time in we need to take care of options and
11367 	 * verify we can do SACK for rack!
11368 	 */
11369 	if (bbr->r_state == 0) {
11370 		/*
11371 		 * Process options only when we get SYN/ACK back. The SYN
11372 		 * case for incoming connections is handled in tcp_syncache.
11373 		 * According to RFC1323 the window field in a SYN (i.e., a
11374 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11375 		 * this is traditional behavior, may need to be cleaned up.
11376 		 */
11377 		if (bbr->rc_inp == NULL) {
11378 			bbr->rc_inp = inp;
11379 		}
11380 		/*
11381 		 * We need to init rc_inp here since its not init'd when
11382 		 * bbr_init is called
11383 		 */
11384 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11385 			if ((to.to_flags & TOF_SCALE) &&
11386 			    (tp->t_flags & TF_REQ_SCALE)) {
11387 				tp->t_flags |= TF_RCVD_SCALE;
11388 				tp->snd_scale = to.to_wscale;
11389 			} else
11390 				tp->t_flags &= ~TF_REQ_SCALE;
11391 			/*
11392 			 * Initial send window.  It will be updated with the
11393 			 * next incoming segment to the scaled value.
11394 			 */
11395 			tp->snd_wnd = th->th_win;
11396 			if ((to.to_flags & TOF_TS) &&
11397 			    (tp->t_flags & TF_REQ_TSTMP)) {
11398 				tp->t_flags |= TF_RCVD_TSTMP;
11399 				tp->ts_recent = to.to_tsval;
11400 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11401 			} else
11402 			    tp->t_flags &= ~TF_REQ_TSTMP;
11403 			if (to.to_flags & TOF_MSS)
11404 				tcp_mss(tp, to.to_mss);
11405 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11406 			    (to.to_flags & TOF_SACKPERM) == 0)
11407 				tp->t_flags &= ~TF_SACK_PERMIT;
11408 			if (IS_FASTOPEN(tp->t_flags)) {
11409 				if (to.to_flags & TOF_FASTOPEN) {
11410 					uint16_t mss;
11411 
11412 					if (to.to_flags & TOF_MSS)
11413 						mss = to.to_mss;
11414 					else
11415 						if ((inp->inp_vflag & INP_IPV6) != 0)
11416 							mss = TCP6_MSS;
11417 						else
11418 							mss = TCP_MSS;
11419 					tcp_fastopen_update_cache(tp, mss,
11420 					    to.to_tfo_len, to.to_tfo_cookie);
11421 				} else
11422 					tcp_fastopen_disable_path(tp);
11423 			}
11424 		}
11425 		/*
11426 		 * At this point we are at the initial call. Here we decide
11427 		 * if we are doing RACK or not. We do this by seeing if
11428 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11429 		 * we switch to the default code.
11430 		 */
11431 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11432 			/* Bail */
11433 			tcp_switch_back_to_default(tp);
11434 			(*tp->t_fb->tfb_tcp_do_segment)(tp, m, th, drop_hdrlen,
11435 			    tlen, iptos);
11436 			return (1);
11437 		}
11438 		/* Set the flag */
11439 		bbr->r_is_v6 = (inp->inp_vflag & INP_IPV6) != 0;
11440 		tcp_set_hpts(tp);
11441 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11442 	}
11443 	if (thflags & TH_ACK) {
11444 		/* Track ack types */
11445 		if (to.to_flags & TOF_SACK)
11446 			BBR_STAT_INC(bbr_acks_with_sacks);
11447 		else
11448 			BBR_STAT_INC(bbr_plain_acks);
11449 	}
11450 	/*
11451 	 * This is the one exception case where we set the rack state
11452 	 * always. All other times (timers etc) we must have a rack-state
11453 	 * set (so we assure we have done the checks above for SACK).
11454 	 */
11455 	if (thflags & TH_FIN)
11456 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11457 	if (bbr->r_state != tp->t_state)
11458 		bbr_set_state(tp, bbr, tiwin);
11459 
11460 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11461 		kern_prefetch(rsm, &prev_state);
11462 	prev_state = bbr->r_state;
11463 	bbr->rc_ack_was_delayed = 0;
11464 	lost = bbr->r_ctl.rc_lost;
11465 	bbr->rc_is_pkt_epoch_now = 0;
11466 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11467 		/* Get the real time into lcts and figure the real delay */
11468 		lcts = tcp_get_usecs(&ltv);
11469 		if (TSTMP_GT(lcts, cts)) {
11470 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11471 			bbr->rc_ack_was_delayed = 1;
11472 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11473 				     bbr->r_ctl.highest_hdwr_delay))
11474 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11475 		} else {
11476 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11477 			bbr->rc_ack_was_delayed = 0;
11478 		}
11479 	} else {
11480 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11481 		bbr->rc_ack_was_delayed = 0;
11482 	}
11483 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11484 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11485 		retval = 0;
11486 		m_freem(m);
11487 		goto done_with_input;
11488 	}
11489 	/*
11490 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11491 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11492 	 */
11493 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11494 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11495 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11496 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11497 		return (1);
11498 	}
11499 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11500 		bbr->r_ctl.rc_high_rwnd = tiwin;
11501 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11502 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11503 	bbr->rtt_valid = 0;
11504 	if (to.to_flags & TOF_TS) {
11505 		bbr->rc_ts_valid = 1;
11506 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11507 	} else {
11508 		bbr->rc_ts_valid = 0;
11509 		bbr->r_ctl.last_inbound_ts = 0;
11510 	}
11511 	retval = (*bbr->r_substate) (m, th, so,
11512 	    tp, &to, drop_hdrlen,
11513 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11514 	if (nxt_pkt == 0)
11515 		BBR_STAT_INC(bbr_rlock_left_ret0);
11516 	else
11517 		BBR_STAT_INC(bbr_rlock_left_ret1);
11518 	if (retval == 0) {
11519 		/*
11520 		 * If retval is 1 the tcb is unlocked and most likely the tp
11521 		 * is gone.
11522 		 */
11523 		INP_WLOCK_ASSERT(inp);
11524 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11525 		if (bbr->rc_is_pkt_epoch_now)
11526 			bbr_set_pktepoch(bbr, cts, __LINE__);
11527 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11528 		if (nxt_pkt == 0) {
11529 			if (bbr->r_wanted_output != 0) {
11530 				bbr->rc_output_starts_timer = 0;
11531 				did_out = 1;
11532 				if (tcp_output(tp) < 0)
11533 					return (1);
11534 			} else
11535 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11536 		}
11537 		if ((nxt_pkt == 0) &&
11538 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11539 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11540 		     (tp->t_flags & TF_DELACK) ||
11541 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11542 		      (tp->t_state <= TCPS_CLOSING)))) {
11543 			/*
11544 			 * We could not send (probably in the hpts but
11545 			 * stopped the timer)?
11546 			 */
11547 			if ((tp->snd_max == tp->snd_una) &&
11548 			    ((tp->t_flags & TF_DELACK) == 0) &&
11549 			    (tcp_in_hpts(tp)) &&
11550 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11551 				/*
11552 				 * keep alive not needed if we are hptsi
11553 				 * output yet
11554 				 */
11555 				;
11556 			} else {
11557 				if (tcp_in_hpts(tp)) {
11558 					tcp_hpts_remove(tp);
11559 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11560 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11561 						uint32_t del;
11562 
11563 						del = lcts - bbr->rc_pacer_started;
11564 						if (bbr->r_ctl.rc_last_delay_val > del) {
11565 							BBR_STAT_INC(bbr_force_timer_start);
11566 							bbr->r_ctl.rc_last_delay_val -= del;
11567 							bbr->rc_pacer_started = lcts;
11568 						} else {
11569 							/* We are late */
11570 							bbr->r_ctl.rc_last_delay_val = 0;
11571 							BBR_STAT_INC(bbr_force_output);
11572 							if (tcp_output(tp) < 0)
11573 								return (1);
11574 						}
11575 					}
11576 				}
11577 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11578 				    0);
11579 			}
11580 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11581 			/* Do we have the correct timer running? */
11582 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11583 		}
11584 		/* Clear the flag, it may have been cleared by output but we may not have  */
11585 		if ((nxt_pkt == 0) && (tp->t_flags2 & TF2_HPTS_CALLS))
11586 			tp->t_flags2 &= ~TF2_HPTS_CALLS;
11587 		/* Do we have a new state */
11588 		if (bbr->r_state != tp->t_state)
11589 			bbr_set_state(tp, bbr, tiwin);
11590 done_with_input:
11591 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11592 		if (did_out)
11593 			bbr->r_wanted_output = 0;
11594 	}
11595 	return (retval);
11596 }
11597 
11598 static void
11599 bbr_do_segment(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11600     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11601 {
11602 	struct timeval tv;
11603 	int retval;
11604 
11605 	/* First lets see if we have old packets */
11606 	if (!STAILQ_EMPTY(&tp->t_inqueue)) {
11607 		if (ctf_do_queued_segments(tp, 1)) {
11608 			m_freem(m);
11609 			return;
11610 		}
11611 	}
11612 	if (m->m_flags & M_TSTMP_LRO) {
11613 		mbuf_tstmp2timeval(m, &tv);
11614 	} else {
11615 		/* Should not be should we kassert instead? */
11616 		tcp_get_usecs(&tv);
11617 	}
11618 	retval = bbr_do_segment_nounlock(tp, m, th, drop_hdrlen, tlen, iptos,
11619 	    0, &tv);
11620 	if (retval == 0) {
11621 		INP_WUNLOCK(tptoinpcb(tp));
11622 	}
11623 }
11624 
11625 /*
11626  * Return how much data can be sent without violating the
11627  * cwnd or rwnd.
11628  */
11629 
11630 static inline uint32_t
11631 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11632     uint32_t avail, int32_t sb_offset, uint32_t cts)
11633 {
11634 	uint32_t len;
11635 
11636 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11637 		/* We never want to go over our peers rcv-window */
11638 		len = 0;
11639 	} else {
11640 		uint32_t flight;
11641 
11642 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11643 		if (flight >= sendwin) {
11644 			/*
11645 			 * We have in flight what we are allowed by cwnd (if
11646 			 * it was rwnd blocking it would have hit above out
11647 			 * >= tp->snd_wnd).
11648 			 */
11649 			return (0);
11650 		}
11651 		len = sendwin - flight;
11652 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11653 			/* We would send too much (beyond the rwnd) */
11654 			len = tp->snd_wnd - ctf_outstanding(tp);
11655 		}
11656 		if ((len + sb_offset) > avail) {
11657 			/*
11658 			 * We don't have that much in the SB, how much is
11659 			 * there?
11660 			 */
11661 			len = avail - sb_offset;
11662 		}
11663 	}
11664 	return (len);
11665 }
11666 
11667 static inline void
11668 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11669 {
11670 	if (error) {
11671 		return;
11672 	}
11673 	if (rsm) {
11674 		if (rsm->r_flags & BBR_TLP) {
11675 			/*
11676 			 * TLP should not count in retran count, but in its
11677 			 * own bin
11678 			 */
11679 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11680 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11681 		} else {
11682 			/* Retransmit */
11683 			tp->t_sndrexmitpack++;
11684 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11685 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11686 #ifdef STATS
11687 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11688 			    len);
11689 #endif
11690 		}
11691 		/*
11692 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11693 		 * sub-state
11694 		 */
11695 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11696 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11697 			/* Non probe_bw log in 1, 2, or 4. */
11698 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11699 		} else {
11700 			/*
11701 			 * Log our probe state 3, and log also 5-13 to show
11702 			 * us the recovery sub-state for the send. This
11703 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11704 			 */
11705 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11706 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11707 		}
11708 		/* Place in both 16's the totals of retransmitted */
11709 		counter_u64_add(bbr_state_lost[16], len);
11710 		counter_u64_add(bbr_state_resend[16], len);
11711 		/* Place in 17's the total sent */
11712 		counter_u64_add(bbr_state_resend[17], len);
11713 		counter_u64_add(bbr_state_lost[17], len);
11714 
11715 	} else {
11716 		/* New sends */
11717 		KMOD_TCPSTAT_INC(tcps_sndpack);
11718 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11719 		/* Place in 17's the total sent */
11720 		counter_u64_add(bbr_state_resend[17], len);
11721 		counter_u64_add(bbr_state_lost[17], len);
11722 #ifdef STATS
11723 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11724 		    len);
11725 #endif
11726 	}
11727 }
11728 
11729 static void
11730 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11731 {
11732 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11733 		/*
11734 		 * Limit the cwnd to not be above N x the target plus whats
11735 		 * is outstanding. The target is based on the current b/w
11736 		 * estimate.
11737 		 */
11738 		uint32_t target;
11739 
11740 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11741 		target += ctf_outstanding(tp);
11742 		target *= bbr_target_cwnd_mult_limit;
11743 		if (tp->snd_cwnd > target)
11744 			tp->snd_cwnd = target;
11745 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11746 	}
11747 }
11748 
11749 static int
11750 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11751 {
11752 	/*
11753 	 * "adv" is the amount we could increase the window, taking into
11754 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11755 	 */
11756 	int32_t adv;
11757 	int32_t oldwin;
11758 
11759 	adv = recwin;
11760 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11761 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11762 		if (adv > oldwin)
11763 			adv -= oldwin;
11764 		else {
11765 			/* We can't increase the window */
11766 			adv = 0;
11767 		}
11768 	} else
11769 		oldwin = 0;
11770 
11771 	/*
11772 	 * If the new window size ends up being the same as or less
11773 	 * than the old size when it is scaled, then don't force
11774 	 * a window update.
11775 	 */
11776 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11777 		return (0);
11778 
11779 	if (adv >= (2 * maxseg) &&
11780 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11781 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11782 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11783 		return (1);
11784 	}
11785 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11786 		return (1);
11787 	return (0);
11788 }
11789 
11790 /*
11791  * Return 0 on success and a errno on failure to send.
11792  * Note that a 0 return may not mean we sent anything
11793  * if the TCB was on the hpts. A non-zero return
11794  * does indicate the error we got from ip[6]_output.
11795  */
11796 static int
11797 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11798 {
11799 	struct socket *so;
11800 	int32_t len;
11801 	uint32_t cts;
11802 	uint32_t recwin, sendwin;
11803 	int32_t sb_offset;
11804 	int32_t flags, abandon, error = 0;
11805 	struct tcp_log_buffer *lgb = NULL;
11806 	struct mbuf *m;
11807 	struct mbuf *mb;
11808 	uint32_t if_hw_tsomaxsegcount = 0;
11809 	uint32_t if_hw_tsomaxsegsize = 0;
11810 	uint32_t if_hw_tsomax = 0;
11811 	struct ip *ip = NULL;
11812 	struct tcp_bbr *bbr;
11813 	struct tcphdr *th;
11814 	struct udphdr *udp = NULL;
11815 	u_char opt[TCP_MAXOLEN];
11816 	unsigned ipoptlen, optlen, hdrlen;
11817 	unsigned ulen;
11818 	uint32_t bbr_seq;
11819 	uint32_t delay_calc=0;
11820 	uint8_t doing_tlp = 0;
11821 	uint8_t local_options;
11822 #ifdef BBR_INVARIANTS
11823 	uint8_t doing_retran_from = 0;
11824 	uint8_t picked_up_retran = 0;
11825 #endif
11826 	uint8_t wanted_cookie = 0;
11827 	uint8_t more_to_rxt=0;
11828 	int32_t prefetch_so_done = 0;
11829 	int32_t prefetch_rsm = 0;
11830 	uint32_t tot_len = 0;
11831 	uint32_t maxseg, pace_max_segs, p_maxseg;
11832 	int32_t csum_flags = 0;
11833  	int32_t hw_tls;
11834 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11835 	unsigned ipsec_optlen = 0;
11836 
11837 #endif
11838 	volatile int32_t sack_rxmit;
11839 	struct bbr_sendmap *rsm = NULL;
11840 	int32_t tso, mtu;
11841 	struct tcpopt to;
11842 	int32_t slot = 0;
11843 	struct inpcb *inp;
11844 	struct sockbuf *sb;
11845 	bool hpts_calling;
11846 #ifdef INET6
11847 	struct ip6_hdr *ip6 = NULL;
11848 	int32_t isipv6;
11849 #endif
11850 	uint8_t app_limited = BBR_JR_SENT_DATA;
11851 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11852 	/* We take a cache hit here */
11853 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11854 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11855 	inp = bbr->rc_inp;
11856 	hpts_calling = !!(tp->t_flags2 & TF2_HPTS_CALLS);
11857 	tp->t_flags2 &= ~TF2_HPTS_CALLS;
11858 	so = inp->inp_socket;
11859 	sb = &so->so_snd;
11860 	if (tp->t_nic_ktls_xmit)
11861  		hw_tls = 1;
11862  	else
11863  		hw_tls = 0;
11864 	kern_prefetch(sb, &maxseg);
11865 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11866 	if (bbr_minseg(bbr) < maxseg) {
11867 		tcp_bbr_tso_size_check(bbr, cts);
11868 	}
11869 	/* Remove any flags that indicate we are pacing on the inp  */
11870 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11871 	p_maxseg = min(maxseg, pace_max_segs);
11872 	INP_WLOCK_ASSERT(inp);
11873 #ifdef TCP_OFFLOAD
11874 	if (tp->t_flags & TF_TOE)
11875 		return (tcp_offload_output(tp));
11876 #endif
11877 
11878 #ifdef INET6
11879 	if (bbr->r_state) {
11880 		/* Use the cache line loaded if possible */
11881 		isipv6 = bbr->r_is_v6;
11882 	} else {
11883 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11884 	}
11885 #endif
11886 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11887 	    tcp_in_hpts(tp)) {
11888 		/*
11889 		 * We are on the hpts for some timer but not hptsi output.
11890 		 * Possibly remove from the hpts so we can send/recv etc.
11891 		 */
11892 		if ((tp->t_flags & TF_ACKNOW) == 0) {
11893 			/*
11894 			 * No immediate demand right now to send an ack, but
11895 			 * the user may have read, making room for new data
11896 			 * (a window update). If so we may want to cancel
11897 			 * whatever timer is running (KEEP/DEL-ACK?) and
11898 			 * continue to send out a window update. Or we may
11899 			 * have gotten more data into the socket buffer to
11900 			 * send.
11901 			 */
11902 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
11903 				      (long)TCP_MAXWIN << tp->rcv_scale);
11904 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
11905 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
11906 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
11907 			    (tp->snd_max - tp->snd_una))) {
11908 				/*
11909 				 * Nothing new to send and no window update
11910 				 * is needed to send. Lets just return and
11911 				 * let the timer-run off.
11912 				 */
11913 				return (0);
11914 			}
11915 		}
11916 		tcp_hpts_remove(tp);
11917 		bbr_timer_cancel(bbr, __LINE__, cts);
11918 	}
11919 	if (bbr->r_ctl.rc_last_delay_val) {
11920 		/* Calculate a rough delay for early escape to sending  */
11921 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11922 			delay_calc = cts - bbr->rc_pacer_started;
11923 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11924 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11925 		else
11926 			delay_calc = 0;
11927 	}
11928 	/* Mark that we have called bbr_output(). */
11929 	if ((bbr->r_timer_override) ||
11930 	    (tp->t_state < TCPS_ESTABLISHED)) {
11931 		/* Timeouts or early states are exempt */
11932 		if (tcp_in_hpts(tp))
11933 			tcp_hpts_remove(tp);
11934 	} else if (tcp_in_hpts(tp)) {
11935 		if ((bbr->r_ctl.rc_last_delay_val) &&
11936 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11937 		    delay_calc) {
11938 			/*
11939 			 * We were being paced for output and the delay has
11940 			 * already exceeded when we were supposed to be
11941 			 * called, lets go ahead and pull out of the hpts
11942 			 * and call output.
11943 			 */
11944 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
11945 			bbr->r_ctl.rc_last_delay_val = 0;
11946 			tcp_hpts_remove(tp);
11947 		} else if (tp->t_state == TCPS_CLOSED) {
11948 			bbr->r_ctl.rc_last_delay_val = 0;
11949 			tcp_hpts_remove(tp);
11950 		} else {
11951 			/*
11952 			 * On the hpts, you shall not pass! even if ACKNOW
11953 			 * is on, we will when the hpts fires, unless of
11954 			 * course we are overdue.
11955 			 */
11956 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
11957 			return (0);
11958 		}
11959 	}
11960 	bbr->rc_cwnd_limited = 0;
11961 	if (bbr->r_ctl.rc_last_delay_val) {
11962 		/* recalculate the real delay and deal with over/under  */
11963 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11964 			delay_calc = cts - bbr->rc_pacer_started;
11965 		else
11966 			delay_calc = 0;
11967 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11968 			/* Setup the delay which will be added in */
11969 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11970 		else {
11971 			/*
11972 			 * We are early setup to adjust
11973 			 * our slot time.
11974 			 */
11975 			uint64_t merged_val;
11976 
11977 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
11978 			bbr->r_agg_early_set = 1;
11979 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
11980 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
11981 					/* Nope our previous late cancels out the early */
11982 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
11983 					bbr->r_agg_early_set = 0;
11984 					bbr->r_ctl.rc_agg_early = 0;
11985 				} else {
11986 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
11987 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
11988 				}
11989 			}
11990 			merged_val = bbr->rc_pacer_started;
11991 			merged_val <<= 32;
11992 			merged_val |= bbr->r_ctl.rc_last_delay_val;
11993 			bbr_log_pacing_delay_calc(bbr, hpts_calling,
11994 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
11995 						 bbr->r_agg_early_set, 3);
11996 			bbr->r_ctl.rc_last_delay_val = 0;
11997 			BBR_STAT_INC(bbr_early);
11998 			delay_calc = 0;
11999 		}
12000 	} else {
12001 		/* We were not delayed due to hptsi */
12002 		if (bbr->r_agg_early_set)
12003 			bbr->r_ctl.rc_agg_early = 0;
12004 		bbr->r_agg_early_set = 0;
12005 		delay_calc = 0;
12006 	}
12007 	if (delay_calc) {
12008 		/*
12009 		 * We had a hptsi delay which means we are falling behind on
12010 		 * sending at the expected rate. Calculate an extra amount
12011 		 * of data we can send, if any, to put us back on track.
12012 		 */
12013 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12014 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12015 		else
12016 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12017 	}
12018 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12019 	if ((tp->snd_una == tp->snd_max) &&
12020 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12021 	    (sbavail(sb))) {
12022 		/*
12023 		 * Ok we have been idle with nothing outstanding
12024 		 * we possibly need to start fresh with either a new
12025 		 * suite of states or a fast-ramp up.
12026 		 */
12027 		bbr_restart_after_idle(bbr,
12028 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12029 	}
12030 	/*
12031 	 * Now was there a hptsi delay where we are behind? We only count
12032 	 * being behind if: a) We are not in recovery. b) There was a delay.
12033 	 * <and> c) We had room to send something.
12034 	 *
12035 	 */
12036 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12037 		int retval;
12038 
12039 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12040 		if (retval != 0) {
12041 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12042 			/*
12043 			 * If timers want tcp_drop(), then pass error out,
12044 			 * otherwise suppress it.
12045 			 */
12046 			return (retval < 0 ? retval : 0);
12047 		}
12048 	}
12049 	bbr->rc_tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
12050 	if (hpts_calling &&
12051 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12052 		bbr->r_ctl.rc_last_delay_val = 0;
12053 	}
12054 	bbr->r_timer_override = 0;
12055 	bbr->r_wanted_output = 0;
12056 	/*
12057 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12058 	 * SYN|ACK and those sent by the retransmit timer.
12059 	 */
12060 	if (IS_FASTOPEN(tp->t_flags) &&
12061 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12062 	     (tp->t_state == TCPS_SYN_SENT)) &&
12063 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12064 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12065 		len = 0;
12066 		goto just_return_nolock;
12067 	}
12068 	/*
12069 	 * Before sending anything check for a state update. For hpts
12070 	 * calling without input this is important. If its input calling
12071 	 * then this was already done.
12072 	 */
12073 	if (bbr->rc_use_google == 0)
12074 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12075 again:
12076 	/*
12077 	 * If we've recently taken a timeout, snd_max will be greater than
12078 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12079 	 * for historic reasons the persist timer still uses it. This means
12080 	 * we have to look at it. All retransmissions that are not persits
12081 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12082 	 * end of this routine we pull snd_nxt always up to snd_max.
12083 	 */
12084 	doing_tlp = 0;
12085 #ifdef BBR_INVARIANTS
12086 	doing_retran_from = picked_up_retran = 0;
12087 #endif
12088 	error = 0;
12089 	tso = 0;
12090 	slot = 0;
12091 	mtu = 0;
12092 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12093 	sb_offset = tp->snd_max - tp->snd_una;
12094 	flags = tcp_outflags[tp->t_state];
12095 	sack_rxmit = 0;
12096 	len = 0;
12097 	rsm = NULL;
12098 	if (flags & TH_RST) {
12099 		SOCKBUF_LOCK(sb);
12100 		goto send;
12101 	}
12102 recheck_resend:
12103 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12104 		/* We need to always have one in reserve */
12105 		rsm = bbr_alloc(bbr);
12106 		if (rsm == NULL) {
12107 			error = ENOMEM;
12108 			/* Lie to get on the hpts */
12109 			tot_len = tp->t_maxseg;
12110 			if (hpts_calling)
12111 				/* Retry in a ms */
12112 				slot = 1001;
12113 			goto just_return_nolock;
12114 		}
12115 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12116 		bbr->r_ctl.rc_free_cnt++;
12117 		rsm = NULL;
12118 	}
12119 	/* What do we send, a resend? */
12120 	if (bbr->r_ctl.rc_resend == NULL) {
12121 		/* Check for rack timeout */
12122 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12123 		if (bbr->r_ctl.rc_resend) {
12124 #ifdef BBR_INVARIANTS
12125 			picked_up_retran = 1;
12126 #endif
12127 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12128 		}
12129 	}
12130 	if (bbr->r_ctl.rc_resend) {
12131 		rsm = bbr->r_ctl.rc_resend;
12132 #ifdef BBR_INVARIANTS
12133 		doing_retran_from = 1;
12134 #endif
12135 		/* Remove any TLP flags its a RACK or T-O */
12136 		rsm->r_flags &= ~BBR_TLP;
12137 		bbr->r_ctl.rc_resend = NULL;
12138 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12139 #ifdef BBR_INVARIANTS
12140 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12141 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12142 			goto recheck_resend;
12143 #else
12144 			/* TSNH */
12145 			rsm = NULL;
12146 			goto recheck_resend;
12147 #endif
12148 		}
12149 		if (rsm->r_flags & BBR_HAS_SYN) {
12150 			/* Only retransmit a SYN by itself */
12151 			len = 0;
12152 			if ((flags & TH_SYN) == 0) {
12153 				/* Huh something is wrong */
12154 				rsm->r_start++;
12155 				if (rsm->r_start == rsm->r_end) {
12156 					/* Clean it up, somehow we missed the ack? */
12157 					bbr_log_syn(tp, NULL);
12158 				} else {
12159 					/* TFO with data? */
12160 					rsm->r_flags &= ~BBR_HAS_SYN;
12161 					len = rsm->r_end - rsm->r_start;
12162 				}
12163 			} else {
12164 				/* Retransmitting SYN */
12165 				rsm = NULL;
12166 				SOCKBUF_LOCK(sb);
12167 				goto send;
12168 			}
12169 		} else
12170 			len = rsm->r_end - rsm->r_start;
12171 		if ((bbr->rc_resends_use_tso == 0) &&
12172 		    (len > maxseg)) {
12173 			len = maxseg;
12174 			more_to_rxt = 1;
12175 		}
12176 		sb_offset = rsm->r_start - tp->snd_una;
12177 		if (len > 0) {
12178 			sack_rxmit = 1;
12179 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12180 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12181 			    min(len, maxseg));
12182 		} else {
12183 			/* I dont think this can happen */
12184 			rsm = NULL;
12185 			goto recheck_resend;
12186 		}
12187 		BBR_STAT_INC(bbr_resends_set);
12188 	} else if (bbr->r_ctl.rc_tlp_send) {
12189 		/*
12190 		 * Tail loss probe
12191 		 */
12192 		doing_tlp = 1;
12193 		rsm = bbr->r_ctl.rc_tlp_send;
12194 		bbr->r_ctl.rc_tlp_send = NULL;
12195 		sack_rxmit = 1;
12196 		len = rsm->r_end - rsm->r_start;
12197 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12198 			len = maxseg;
12199 
12200 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12201 #ifdef BBR_INVARIANTS
12202 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12203 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12204 #else
12205 			/* TSNH */
12206 			rsm = NULL;
12207 			goto recheck_resend;
12208 #endif
12209 		}
12210 		sb_offset = rsm->r_start - tp->snd_una;
12211 		BBR_STAT_INC(bbr_tlp_set);
12212 	}
12213 	/*
12214 	 * Enforce a connection sendmap count limit if set
12215 	 * as long as we are not retransmiting.
12216 	 */
12217 	if ((rsm == NULL) &&
12218 	    (V_tcp_map_entries_limit > 0) &&
12219 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12220 		BBR_STAT_INC(bbr_alloc_limited);
12221 		if (!bbr->alloc_limit_reported) {
12222 			bbr->alloc_limit_reported = 1;
12223 			BBR_STAT_INC(bbr_alloc_limited_conns);
12224 		}
12225 		goto just_return_nolock;
12226 	}
12227 #ifdef BBR_INVARIANTS
12228 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12229 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12230 		    tp, bbr, rsm, sb_offset, len);
12231 	}
12232 #endif
12233 	/*
12234 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12235 	 * state flags.
12236 	 */
12237 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12238 		flags |= TH_FIN;
12239 	if (tp->t_flags & TF_NEEDSYN)
12240 		flags |= TH_SYN;
12241 
12242 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12243 		/* we are retransmitting the fin */
12244 		len--;
12245 		if (len) {
12246 			/*
12247 			 * When retransmitting data do *not* include the
12248 			 * FIN. This could happen from a TLP probe if we
12249 			 * allowed data with a FIN.
12250 			 */
12251 			flags &= ~TH_FIN;
12252 		}
12253 	} else if (rsm) {
12254 		if (flags & TH_FIN)
12255 			flags &= ~TH_FIN;
12256 	}
12257 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12258 		void *end_rsm;
12259 
12260 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12261 		if (end_rsm)
12262 			kern_prefetch(end_rsm, &prefetch_rsm);
12263 		prefetch_rsm = 1;
12264 	}
12265 	SOCKBUF_LOCK(sb);
12266 	/*
12267 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12268 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12269 	 * negative length.  This can also occur when TCP opens up its
12270 	 * congestion window while receiving additional duplicate acks after
12271 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12272 	 * the fast-retransmit.
12273 	 *
12274 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12275 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12276 	 * up 0.
12277 	 *
12278 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12279 	 * in which case len is already set.
12280 	 */
12281 	if (sack_rxmit == 0) {
12282 		uint32_t avail;
12283 
12284 		avail = sbavail(sb);
12285 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12286 			sb_offset = tp->snd_max - tp->snd_una;
12287 		else
12288 			sb_offset = 0;
12289 		if (bbr->rc_tlp_new_data) {
12290 			/* TLP is forcing out new data */
12291 			uint32_t tlplen;
12292 
12293 			doing_tlp = 1;
12294 			tlplen = maxseg;
12295 
12296 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12297 				tlplen = (uint32_t)(avail - sb_offset);
12298 			}
12299 			if (tlplen > tp->snd_wnd) {
12300 				len = tp->snd_wnd;
12301 			} else {
12302 				len = tlplen;
12303 			}
12304 			bbr->rc_tlp_new_data = 0;
12305 		} else {
12306 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12307 			if ((len < p_maxseg) &&
12308 			    (bbr->rc_in_persist == 0) &&
12309 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12310 			    ((avail - sb_offset) >= p_maxseg)) {
12311 				/*
12312 				 * We are not completing whats in the socket
12313 				 * buffer (i.e. there is at least a segment
12314 				 * waiting to send) and we have 2 or more
12315 				 * segments outstanding. There is no sense
12316 				 * of sending a little piece. Lets defer and
12317 				 * and wait until we can send a whole
12318 				 * segment.
12319 				 */
12320 				len = 0;
12321 			}
12322 			if (bbr->rc_in_persist) {
12323 				/*
12324 				 * We are in persists, figure out if
12325 				 * a retransmit is available (maybe the previous
12326 				 * persists we sent) or if we have to send new
12327 				 * data.
12328 				 */
12329 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12330 				if (rsm) {
12331 					len = rsm->r_end - rsm->r_start;
12332 					if (rsm->r_flags & BBR_HAS_FIN)
12333 						len--;
12334 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12335 						len = maxseg;
12336 					if (len > 1)
12337 						BBR_STAT_INC(bbr_persist_reneg);
12338 					/*
12339 					 * XXXrrs we could force the len to
12340 					 * 1 byte here to cause the chunk to
12341 					 * split apart.. but that would then
12342 					 * mean we always retransmit it as
12343 					 * one byte even after the window
12344 					 * opens.
12345 					 */
12346 					sack_rxmit = 1;
12347 					sb_offset = rsm->r_start - tp->snd_una;
12348 				} else {
12349 					/*
12350 					 * First time through in persists or peer
12351 					 * acked our one byte. Though we do have
12352 					 * to have something in the sb.
12353 					 */
12354 					len = 1;
12355 					sb_offset = 0;
12356 					if (avail == 0)
12357 					    len = 0;
12358 				}
12359 			}
12360 		}
12361 	}
12362 	if (prefetch_so_done == 0) {
12363 		kern_prefetch(so, &prefetch_so_done);
12364 		prefetch_so_done = 1;
12365 	}
12366 	/*
12367 	 * Lop off SYN bit if it has already been sent.  However, if this is
12368 	 * SYN-SENT state and if segment contains data and if we don't know
12369 	 * that foreign host supports TAO, suppress sending segment.
12370 	 */
12371 	if ((flags & TH_SYN) && (rsm == NULL) &&
12372 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12373 		if (tp->t_state != TCPS_SYN_RECEIVED)
12374 			flags &= ~TH_SYN;
12375 		/*
12376 		 * When sending additional segments following a TFO SYN|ACK,
12377 		 * do not include the SYN bit.
12378 		 */
12379 		if (IS_FASTOPEN(tp->t_flags) &&
12380 		    (tp->t_state == TCPS_SYN_RECEIVED))
12381 			flags &= ~TH_SYN;
12382 		sb_offset--, len++;
12383 		if (sbavail(sb) == 0)
12384 			len = 0;
12385 	} else if ((flags & TH_SYN) && rsm) {
12386 		/*
12387 		 * Subtract one from the len for the SYN being
12388 		 * retransmitted.
12389 		 */
12390 		len--;
12391 	}
12392 	/*
12393 	 * Be careful not to send data and/or FIN on SYN segments. This
12394 	 * measure is needed to prevent interoperability problems with not
12395 	 * fully conformant TCP implementations.
12396 	 */
12397 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12398 		len = 0;
12399 		flags &= ~TH_FIN;
12400 	}
12401 	/*
12402 	 * On TFO sockets, ensure no data is sent in the following cases:
12403 	 *
12404 	 *  - When retransmitting SYN|ACK on a passively-created socket
12405 	 *  - When retransmitting SYN on an actively created socket
12406 	 *  - When sending a zero-length cookie (cookie request) on an
12407 	 *    actively created socket
12408 	 *  - When the socket is in the CLOSED state (RST is being sent)
12409 	 */
12410 	if (IS_FASTOPEN(tp->t_flags) &&
12411 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12412 	     ((tp->t_state == TCPS_SYN_SENT) &&
12413 	      (tp->t_tfo_client_cookie_len == 0)) ||
12414 	     (flags & TH_RST))) {
12415 		len = 0;
12416 		sack_rxmit = 0;
12417 		rsm = NULL;
12418 	}
12419 	/* Without fast-open there should never be data sent on a SYN */
12420 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12421 		len = 0;
12422 	if (len <= 0) {
12423 		/*
12424 		 * If FIN has been sent but not acked, but we haven't been
12425 		 * called to retransmit, len will be < 0.  Otherwise, window
12426 		 * shrank after we sent into it.  If window shrank to 0,
12427 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12428 		 * window, and set the persist timer if it isn't already
12429 		 * going.  If the window didn't close completely, just wait
12430 		 * for an ACK.
12431 		 *
12432 		 * We also do a general check here to ensure that we will
12433 		 * set the persist timer when we have data to send, but a
12434 		 * 0-byte window. This makes sure the persist timer is set
12435 		 * even if the packet hits one of the "goto send" lines
12436 		 * below.
12437 		 */
12438 		len = 0;
12439 		if ((tp->snd_wnd == 0) &&
12440 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12441 		    (tp->snd_una == tp->snd_max) &&
12442 		    (sb_offset < (int)sbavail(sb))) {
12443 			/*
12444 			 * Not enough room in the rwnd to send
12445 			 * a paced segment out.
12446 			 */
12447 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12448 		}
12449 	} else if ((rsm == NULL) &&
12450 		   (doing_tlp == 0) &&
12451 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12452 		/*
12453 		 * We are not sending a full segment for
12454 		 * some reason. Should we not send anything (think
12455 		 * sws or persists)?
12456 		 */
12457 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12458 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12459 		    (len < (int)(sbavail(sb) - sb_offset))) {
12460 			/*
12461 			 * Here the rwnd is less than
12462 			 * the pacing size, this is not a retransmit,
12463 			 * we are established and
12464 			 * the send is not the last in the socket buffer
12465 			 * lets not send, and possibly enter persists.
12466 			 */
12467 			len = 0;
12468 			if (tp->snd_max == tp->snd_una)
12469 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12470 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12471 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12472 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12473 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12474 			   (len < bbr_minseg(bbr))) {
12475 			/*
12476 			 * Here we are not retransmitting, and
12477 			 * the cwnd is not so small that we could
12478 			 * not send at least a min size (rxt timer
12479 			 * not having gone off), We have 2 segments or
12480 			 * more already in flight, its not the tail end
12481 			 * of the socket buffer  and the cwnd is blocking
12482 			 * us from sending out minimum pacing segment size.
12483 			 * Lets not send anything.
12484 			 */
12485 			bbr->rc_cwnd_limited = 1;
12486 			len = 0;
12487 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12488 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12489 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12490 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12491 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12492 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12493 			/*
12494 			 * Here we have a send window but we have
12495 			 * filled it up and we can't send another pacing segment.
12496 			 * We also have in flight more than 2 segments
12497 			 * and we are not completing the sb i.e. we allow
12498 			 * the last bytes of the sb to go out even if
12499 			 * its not a full pacing segment.
12500 			 */
12501 			len = 0;
12502 		}
12503 	}
12504 	/* len will be >= 0 after this point. */
12505 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12506 	tcp_sndbuf_autoscale(tp, so, sendwin);
12507 	/*
12508 	 *
12509 	 */
12510 	if (bbr->rc_in_persist &&
12511 	    len &&
12512 	    (rsm == NULL) &&
12513 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12514 		/*
12515 		 * We are in persist, not doing a retransmit and don't have enough space
12516 		 * yet to send a full TSO. So is it at the end of the sb
12517 		 * if so we need to send else nuke to 0 and don't send.
12518 		 */
12519 		int sbleft;
12520 		if (sbavail(sb) > sb_offset)
12521 			sbleft = sbavail(sb) - sb_offset;
12522 		else
12523 			sbleft = 0;
12524 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12525 			/* not at end of sb lets not send */
12526 			len = 0;
12527 		}
12528 	}
12529 	/*
12530 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12531 	 * hardware).
12532 	 *
12533 	 * TSO may only be used if we are in a pure bulk sending state.  The
12534 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12535 	 * options prevent using TSO.  With TSO the TCP header is the same
12536 	 * (except for the sequence number) for all generated packets.  This
12537 	 * makes it impossible to transmit any options which vary per
12538 	 * generated segment or packet.
12539 	 *
12540 	 * IPv4 handling has a clear separation of ip options and ip header
12541 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12542 	 * does the right thing below to provide length of just ip options
12543 	 * and thus checking for ipoptlen is enough to decide if ip options
12544 	 * are present.
12545 	 */
12546 #ifdef INET6
12547 	if (isipv6)
12548 		ipoptlen = ip6_optlen(inp);
12549 	else
12550 #endif
12551 	if (inp->inp_options)
12552 		ipoptlen = inp->inp_options->m_len -
12553 		    offsetof(struct ipoption, ipopt_list);
12554 	else
12555 		ipoptlen = 0;
12556 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12557 	/*
12558 	 * Pre-calculate here as we save another lookup into the darknesses
12559 	 * of IPsec that way and can actually decide if TSO is ok.
12560 	 */
12561 #ifdef INET6
12562 	if (isipv6 && IPSEC_ENABLED(ipv6))
12563 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12564 #ifdef INET
12565 	else
12566 #endif
12567 #endif				/* INET6 */
12568 #ifdef INET
12569 	if (IPSEC_ENABLED(ipv4))
12570 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12571 #endif				/* INET */
12572 #endif				/* IPSEC */
12573 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12574 	ipoptlen += ipsec_optlen;
12575 #endif
12576 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12577 	    (len > maxseg) &&
12578 	    (tp->t_port == 0) &&
12579 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12580 	    tp->rcv_numsacks == 0 &&
12581 	    ipoptlen == 0)
12582 		tso = 1;
12583 
12584 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12585 	    (long)TCP_MAXWIN << tp->rcv_scale);
12586 	/*
12587 	 * Sender silly window avoidance.   We transmit under the following
12588 	 * conditions when len is non-zero:
12589 	 *
12590 	 * - We have a full segment (or more with TSO) - This is the last
12591 	 * buffer in a write()/send() and we are either idle or running
12592 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12593 	 * then 1/2 the maximum send window's worth of data (receiver may be
12594 	 * limited the window size) - we need to retransmit
12595 	 */
12596 	if (rsm)
12597 		goto send;
12598 	if (len) {
12599 		if (sack_rxmit)
12600 			goto send;
12601 		if (len >= p_maxseg)
12602 			goto send;
12603 		/*
12604 		 * NOTE! on localhost connections an 'ack' from the remote
12605 		 * end may occur synchronously with the output and cause us
12606 		 * to flush a buffer queued with moretocome.  XXX
12607 		 *
12608 		 */
12609 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12610 		    ((tp->t_flags & TF_NODELAY) ||
12611 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12612 		    (tp->t_flags & TF_NOPUSH) == 0) {
12613 			goto send;
12614 		}
12615 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12616 			goto send;
12617 		}
12618 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12619 			goto send;
12620 		}
12621 	}
12622 	/*
12623 	 * Sending of standalone window updates.
12624 	 *
12625 	 * Window updates are important when we close our window due to a
12626 	 * full socket buffer and are opening it again after the application
12627 	 * reads data from it.  Once the window has opened again and the
12628 	 * remote end starts to send again the ACK clock takes over and
12629 	 * provides the most current window information.
12630 	 *
12631 	 * We must avoid the silly window syndrome whereas every read from
12632 	 * the receive buffer, no matter how small, causes a window update
12633 	 * to be sent.  We also should avoid sending a flurry of window
12634 	 * updates when the socket buffer had queued a lot of data and the
12635 	 * application is doing small reads.
12636 	 *
12637 	 * Prevent a flurry of pointless window updates by only sending an
12638 	 * update when we can increase the advertized window by more than
12639 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12640 	 * full or is very small be more aggressive and send an update
12641 	 * whenever we can increase by two mss sized segments. In all other
12642 	 * situations the ACK's to new incoming data will carry further
12643 	 * window increases.
12644 	 *
12645 	 * Don't send an independent window update if a delayed ACK is
12646 	 * pending (it will get piggy-backed on it) or the remote side
12647 	 * already has done a half-close and won't send more data.  Skip
12648 	 * this if the connection is in T/TCP half-open state.
12649 	 */
12650 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12651 	    !(tp->t_flags & TF_DELACK) &&
12652 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12653 		/* Check to see if we should do a window update */
12654 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12655 			goto send;
12656 	}
12657 	/*
12658 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12659 	 * is also a catch-all for the retransmit timer timeout case.
12660 	 */
12661 	if (tp->t_flags & TF_ACKNOW) {
12662 		goto send;
12663 	}
12664 	if (flags & TH_RST) {
12665 		/* Always send a RST if one is due */
12666 		goto send;
12667 	}
12668 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12669 		goto send;
12670 	}
12671 	/*
12672 	 * If our state indicates that FIN should be sent and we have not
12673 	 * yet done so, then we need to send.
12674 	 */
12675 	if (flags & TH_FIN &&
12676 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12677 		goto send;
12678 	}
12679 	/*
12680 	 * No reason to send a segment, just return.
12681 	 */
12682 just_return:
12683 	SOCKBUF_UNLOCK(sb);
12684 just_return_nolock:
12685 	if (tot_len)
12686 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12687 	if (bbr->rc_no_pacing)
12688 		slot = 0;
12689 	if (tot_len == 0) {
12690 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12691 		    tp->snd_wnd) {
12692 			BBR_STAT_INC(bbr_rwnd_limited);
12693 			app_limited = BBR_JR_RWND_LIMITED;
12694 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12695 			if ((bbr->rc_in_persist == 0) &&
12696 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12697 			    (tp->snd_max == tp->snd_una) &&
12698 			    sbavail(&so->so_snd)) {
12699 				/* No send window.. we must enter persist */
12700 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12701 			}
12702 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12703 			BBR_STAT_INC(bbr_app_limited);
12704 			app_limited = BBR_JR_APP_LIMITED;
12705 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12706 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12707 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12708 			BBR_STAT_INC(bbr_cwnd_limited);
12709  			app_limited = BBR_JR_CWND_LIMITED;
12710 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12711 									bbr->r_ctl.rc_lost_bytes)));
12712 			bbr->rc_cwnd_limited = 1;
12713 		} else {
12714 			BBR_STAT_INC(bbr_app_limited);
12715 			app_limited = BBR_JR_APP_LIMITED;
12716 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12717 		}
12718 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12719 		bbr->r_agg_early_set = 0;
12720 		bbr->r_ctl.rc_agg_early = 0;
12721 		bbr->r_ctl.rc_last_delay_val = 0;
12722 	} else if (bbr->rc_use_google == 0)
12723 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12724 	/* Are we app limited? */
12725 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12726 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12727 		/**
12728 		 * We are application limited.
12729 		 */
12730 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12731 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12732 	}
12733 	if (tot_len == 0)
12734 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12735 	/* Dont update the time if we did not send */
12736 	bbr->r_ctl.rc_last_delay_val = 0;
12737 	bbr->rc_output_starts_timer = 1;
12738 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12739 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12740 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12741 		/* Make sure snd_nxt is drug up */
12742 		tp->snd_nxt = tp->snd_max;
12743 	}
12744 	return (error);
12745 
12746 send:
12747 	if (doing_tlp == 0) {
12748 		/*
12749 		 * Data not a TLP, and its not the rxt firing. If it is the
12750 		 * rxt firing, we want to leave the tlp_in_progress flag on
12751 		 * so we don't send another TLP. It has to be a rack timer
12752 		 * or normal send (response to acked data) to clear the tlp
12753 		 * in progress flag.
12754 		 */
12755 		bbr->rc_tlp_in_progress = 0;
12756 		bbr->rc_tlp_rtx_out = 0;
12757 	} else {
12758 		/*
12759 		 * Its a TLP.
12760 		 */
12761 		bbr->rc_tlp_in_progress = 1;
12762 	}
12763 	bbr_timer_cancel(bbr, __LINE__, cts);
12764 	if (rsm == NULL) {
12765 		if (sbused(sb) > 0) {
12766 			/*
12767 			 * This is sub-optimal. We only send a stand alone
12768 			 * FIN on its own segment.
12769 			 */
12770 			if (flags & TH_FIN) {
12771 				flags &= ~TH_FIN;
12772 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12773 					/* Lets not send this */
12774 					slot = 0;
12775 					goto just_return;
12776 				}
12777 			}
12778 		}
12779 	} else {
12780 		/*
12781 		 * We do *not* send a FIN on a retransmit if it has data.
12782 		 * The if clause here where len > 1 should never come true.
12783 		 */
12784 		if ((len > 0) &&
12785 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12786 		    (flags & TH_FIN))) {
12787 			flags &= ~TH_FIN;
12788 			len--;
12789 		}
12790 	}
12791 	SOCKBUF_LOCK_ASSERT(sb);
12792 	if (len > 0) {
12793 		if ((tp->snd_una == tp->snd_max) &&
12794 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12795 			/*
12796 			 * This qualifies as a RTT_PROBE session since we
12797 			 * drop the data outstanding to nothing and waited
12798 			 * more than bbr_rtt_probe_time.
12799 			 */
12800 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12801 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12802 		}
12803 		if (len >= maxseg)
12804 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12805 		else
12806 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12807 	}
12808 	/*
12809 	 * Before ESTABLISHED, force sending of initial options unless TCP
12810 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12811 	 * plus TCP options always fit in a single mbuf, leaving room for a
12812 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12813 	 * + optlen <= MCLBYTES
12814 	 */
12815 	optlen = 0;
12816 #ifdef INET6
12817 	if (isipv6)
12818 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12819 	else
12820 #endif
12821 		hdrlen = sizeof(struct tcpiphdr);
12822 
12823 	/*
12824 	 * Compute options for segment. We only have to care about SYN and
12825 	 * established connection segments.  Options for SYN-ACK segments
12826 	 * are handled in TCP syncache.
12827 	 */
12828 	to.to_flags = 0;
12829 	local_options = 0;
12830 	if ((tp->t_flags & TF_NOOPT) == 0) {
12831 		/* Maximum segment size. */
12832 		if (flags & TH_SYN) {
12833 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12834 			if (tp->t_port)
12835 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12836 			to.to_flags |= TOF_MSS;
12837 			/*
12838 			 * On SYN or SYN|ACK transmits on TFO connections,
12839 			 * only include the TFO option if it is not a
12840 			 * retransmit, as the presence of the TFO option may
12841 			 * have caused the original SYN or SYN|ACK to have
12842 			 * been dropped by a middlebox.
12843 			 */
12844 			if (IS_FASTOPEN(tp->t_flags) &&
12845 			    (tp->t_rxtshift == 0)) {
12846 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12847 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12848 					to.to_tfo_cookie =
12849 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12850 					to.to_flags |= TOF_FASTOPEN;
12851 					wanted_cookie = 1;
12852 				} else if (tp->t_state == TCPS_SYN_SENT) {
12853 					to.to_tfo_len =
12854 					    tp->t_tfo_client_cookie_len;
12855 					to.to_tfo_cookie =
12856 					    tp->t_tfo_cookie.client;
12857 					to.to_flags |= TOF_FASTOPEN;
12858 					wanted_cookie = 1;
12859 				}
12860 			}
12861 		}
12862 		/* Window scaling. */
12863 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12864 			to.to_wscale = tp->request_r_scale;
12865 			to.to_flags |= TOF_SCALE;
12866 		}
12867 		/* Timestamps. */
12868 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12869 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12870 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12871 			to.to_tsecr = tp->ts_recent;
12872 			to.to_flags |= TOF_TS;
12873 			local_options += TCPOLEN_TIMESTAMP + 2;
12874 		}
12875 		/* Set receive buffer autosizing timestamp. */
12876 		if (tp->rfbuf_ts == 0 &&
12877 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12878 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12879 		/* Selective ACK's. */
12880 		if (flags & TH_SYN)
12881 			to.to_flags |= TOF_SACKPERM;
12882 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12883 		    tp->rcv_numsacks > 0) {
12884 			to.to_flags |= TOF_SACK;
12885 			to.to_nsacks = tp->rcv_numsacks;
12886 			to.to_sacks = (u_char *)tp->sackblks;
12887 		}
12888 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
12889 		/* TCP-MD5 (RFC2385). */
12890 		if (tp->t_flags & TF_SIGNATURE)
12891 			to.to_flags |= TOF_SIGNATURE;
12892 #endif				/* TCP_SIGNATURE */
12893 
12894 		/* Processing the options. */
12895 		hdrlen += (optlen = tcp_addoptions(&to, opt));
12896 		/*
12897 		 * If we wanted a TFO option to be added, but it was unable
12898 		 * to fit, ensure no data is sent.
12899 		 */
12900 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
12901 		    !(to.to_flags & TOF_FASTOPEN))
12902 			len = 0;
12903 	}
12904 	if (tp->t_port) {
12905 		if (V_tcp_udp_tunneling_port == 0) {
12906 			/* The port was removed?? */
12907 			SOCKBUF_UNLOCK(&so->so_snd);
12908 			return (EHOSTUNREACH);
12909 		}
12910 		hdrlen += sizeof(struct udphdr);
12911 	}
12912 #ifdef INET6
12913 	if (isipv6)
12914 		ipoptlen = ip6_optlen(inp);
12915 	else
12916 #endif
12917 	if (inp->inp_options)
12918 		ipoptlen = inp->inp_options->m_len -
12919 		    offsetof(struct ipoption, ipopt_list);
12920 	else
12921 		ipoptlen = 0;
12922 	ipoptlen = 0;
12923 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12924 	ipoptlen += ipsec_optlen;
12925 #endif
12926 	if (bbr->rc_last_options != local_options) {
12927 		/*
12928 		 * Cache the options length this generally does not change
12929 		 * on a connection. We use this to calculate TSO.
12930 		 */
12931 		bbr->rc_last_options = local_options;
12932 	}
12933 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
12934 	p_maxseg = min(maxseg, pace_max_segs);
12935 	/*
12936 	 * Adjust data length if insertion of options will bump the packet
12937 	 * length beyond the t_maxseg length. Clear the FIN bit because we
12938 	 * cut off the tail of the segment.
12939 	 */
12940 	if (len > maxseg) {
12941 		if (len != 0 && (flags & TH_FIN)) {
12942 			flags &= ~TH_FIN;
12943 		}
12944 		if (tso) {
12945 			uint32_t moff;
12946 			int32_t max_len;
12947 
12948 			/* extract TSO information */
12949 			if_hw_tsomax = tp->t_tsomax;
12950 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
12951 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
12952 			KASSERT(ipoptlen == 0,
12953 			    ("%s: TSO can't do IP options", __func__));
12954 
12955 			/*
12956 			 * Check if we should limit by maximum payload
12957 			 * length:
12958 			 */
12959 			if (if_hw_tsomax != 0) {
12960 				/* compute maximum TSO length */
12961 				max_len = (if_hw_tsomax - hdrlen -
12962 				    max_linkhdr);
12963 				if (max_len <= 0) {
12964 					len = 0;
12965 				} else if (len > max_len) {
12966 					len = max_len;
12967 				}
12968 			}
12969 			/*
12970 			 * Prevent the last segment from being fractional
12971 			 * unless the send sockbuf can be emptied:
12972 			 */
12973 			if ((sb_offset + len) < sbavail(sb)) {
12974 				moff = len % (uint32_t)maxseg;
12975 				if (moff != 0) {
12976 					len -= moff;
12977 				}
12978 			}
12979 			/*
12980 			 * In case there are too many small fragments don't
12981 			 * use TSO:
12982 			 */
12983 			if (len <= maxseg) {
12984 				len = maxseg;
12985 				tso = 0;
12986 			}
12987 		} else {
12988 			/* Not doing TSO */
12989 			if (optlen + ipoptlen >= tp->t_maxseg) {
12990 				/*
12991 				 * Since we don't have enough space to put
12992 				 * the IP header chain and the TCP header in
12993 				 * one packet as required by RFC 7112, don't
12994 				 * send it. Also ensure that at least one
12995 				 * byte of the payload can be put into the
12996 				 * TCP segment.
12997 				 */
12998 				SOCKBUF_UNLOCK(&so->so_snd);
12999 				error = EMSGSIZE;
13000 				sack_rxmit = 0;
13001 				goto out;
13002 			}
13003 			len = maxseg;
13004 		}
13005 	} else {
13006 		/* Not doing TSO */
13007 		if_hw_tsomaxsegcount = 0;
13008 		tso = 0;
13009 	}
13010 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13011 	    ("%s: len > IP_MAXPACKET", __func__));
13012 #ifdef DIAGNOSTIC
13013 #ifdef INET6
13014 	if (max_linkhdr + hdrlen > MCLBYTES)
13015 #else
13016 	if (max_linkhdr + hdrlen > MHLEN)
13017 #endif
13018 		panic("tcphdr too big");
13019 #endif
13020 	/*
13021 	 * This KASSERT is here to catch edge cases at a well defined place.
13022 	 * Before, those had triggered (random) panic conditions further
13023 	 * down.
13024 	 */
13025 #ifdef BBR_INVARIANTS
13026 	if (sack_rxmit) {
13027 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13028 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13029 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13030 		}
13031 	}
13032 #endif
13033 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13034 	if ((len == 0) &&
13035 	    (flags & TH_FIN) &&
13036 	    (sbused(sb))) {
13037 		/*
13038 		 * We have outstanding data, don't send a fin by itself!.
13039 		 */
13040 		slot = 0;
13041 		goto just_return;
13042 	}
13043 	/*
13044 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13045 	 * and initialize the header from the template for sends on this
13046 	 * connection.
13047 	 */
13048 	if (len) {
13049 		uint32_t moff;
13050 
13051 		/*
13052 		 * We place a limit on sending with hptsi.
13053 		 */
13054 		if ((rsm == NULL) && len > pace_max_segs)
13055 			len = pace_max_segs;
13056 		if (len <= maxseg)
13057 			tso = 0;
13058 #ifdef INET6
13059 		if (MHLEN < hdrlen + max_linkhdr)
13060 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13061 		else
13062 #endif
13063 			m = m_gethdr(M_NOWAIT, MT_DATA);
13064 
13065 		if (m == NULL) {
13066 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13067 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13068 			SOCKBUF_UNLOCK(sb);
13069 			error = ENOBUFS;
13070 			sack_rxmit = 0;
13071 			goto out;
13072 		}
13073 		m->m_data += max_linkhdr;
13074 		m->m_len = hdrlen;
13075 		/*
13076 		 * Start the m_copy functions from the closest mbuf to the
13077 		 * sb_offset in the socket buffer chain.
13078 		 */
13079 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13080 #ifdef BBR_INVARIANTS
13081 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13082 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13083 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13084 				    doing_retran_from,
13085 				    picked_up_retran,
13086 				    doing_tlp);
13087 
13088 #endif
13089 			/*
13090 			 * In this messed up situation we have two choices,
13091 			 * a) pretend the send worked, and just start timers
13092 			 * and what not (not good since that may lead us
13093 			 * back here a lot). <or> b) Send the lowest segment
13094 			 * in the map. <or> c) Drop the connection. Lets do
13095 			 * <b> which if it continues to happen will lead to
13096 			 * <c> via timeouts.
13097 			 */
13098 			BBR_STAT_INC(bbr_offset_recovery);
13099 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13100 			sb_offset = 0;
13101 			if (rsm == NULL) {
13102 				sack_rxmit = 0;
13103 				len = sbavail(sb);
13104 			} else {
13105 				sack_rxmit = 1;
13106 				if (rsm->r_start != tp->snd_una) {
13107 					/*
13108 					 * Things are really messed up, <c>
13109 					 * is the only thing to do.
13110 					 */
13111 					BBR_STAT_INC(bbr_offset_drop);
13112 					SOCKBUF_UNLOCK(sb);
13113 					(void)m_free(m);
13114 					return (-EFAULT); /* tcp_drop() */
13115 				}
13116 				len = rsm->r_end - rsm->r_start;
13117 			}
13118 			if (len > sbavail(sb))
13119 				len = sbavail(sb);
13120 			if (len > maxseg)
13121 				len = maxseg;
13122 		}
13123 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13124 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13125 			m_copydata(mb, moff, (int)len,
13126 			    mtod(m, caddr_t)+hdrlen);
13127 			if (rsm == NULL)
13128 				sbsndptr_adv(sb, mb, len);
13129 			m->m_len += len;
13130 		} else {
13131 			struct sockbuf *msb;
13132 
13133 			if (rsm)
13134 				msb = NULL;
13135 			else
13136 				msb = sb;
13137 #ifdef BBR_INVARIANTS
13138 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13139 				if (rsm) {
13140 					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 ",
13141 					    tp, bbr, len, moff,
13142 					    sbavail(sb), rsm,
13143 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13144 					    doing_retran_from,
13145 					    picked_up_retran,
13146 					    doing_tlp, sack_rxmit);
13147 				} else {
13148 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13149 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13150 				}
13151 			}
13152 #endif
13153 			m->m_next = tcp_m_copym(
13154 				mb, moff, &len,
13155 				if_hw_tsomaxsegcount,
13156 				if_hw_tsomaxsegsize, msb,
13157 				((rsm == NULL) ? hw_tls : 0)
13158 #ifdef NETFLIX_COPY_ARGS
13159 				, NULL, NULL
13160 #endif
13161 				);
13162 			if (len <= maxseg) {
13163 				/*
13164 				 * Must have ran out of mbufs for the copy
13165 				 * shorten it to no longer need tso. Lets
13166 				 * not put on sendalot since we are low on
13167 				 * mbufs.
13168 				 */
13169 				tso = 0;
13170 			}
13171 			if (m->m_next == NULL) {
13172 				SOCKBUF_UNLOCK(sb);
13173 				(void)m_free(m);
13174 				error = ENOBUFS;
13175 				sack_rxmit = 0;
13176 				goto out;
13177 			}
13178 		}
13179 #ifdef BBR_INVARIANTS
13180 		if (tso && len < maxseg) {
13181 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13182 			    tp, len, maxseg);
13183 		}
13184 		if (tso && if_hw_tsomaxsegcount) {
13185 			int32_t seg_cnt = 0;
13186 			struct mbuf *foo;
13187 
13188 			foo = m;
13189 			while (foo) {
13190 				seg_cnt++;
13191 				foo = foo->m_next;
13192 			}
13193 			if (seg_cnt > if_hw_tsomaxsegcount) {
13194 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13195 			}
13196 		}
13197 #endif
13198 		/*
13199 		 * If we're sending everything we've got, set PUSH. (This
13200 		 * will keep happy those implementations which only give
13201 		 * data to the user when a buffer fills or a PUSH comes in.)
13202 		 */
13203 		if (sb_offset + len == sbused(sb) &&
13204 		    sbused(sb) &&
13205 		    !(flags & TH_SYN)) {
13206 			flags |= TH_PUSH;
13207 		}
13208 		SOCKBUF_UNLOCK(sb);
13209 	} else {
13210 		SOCKBUF_UNLOCK(sb);
13211 		if (tp->t_flags & TF_ACKNOW)
13212 			KMOD_TCPSTAT_INC(tcps_sndacks);
13213 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13214 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13215 		else
13216 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13217 
13218 		m = m_gethdr(M_NOWAIT, MT_DATA);
13219 		if (m == NULL) {
13220 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13221 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13222 			error = ENOBUFS;
13223 			/* Fudge the send time since we could not send */
13224 			sack_rxmit = 0;
13225 			goto out;
13226 		}
13227 #ifdef INET6
13228 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13229 		    MHLEN >= hdrlen) {
13230 			M_ALIGN(m, hdrlen);
13231 		} else
13232 #endif
13233 			m->m_data += max_linkhdr;
13234 		m->m_len = hdrlen;
13235 	}
13236 	SOCKBUF_UNLOCK_ASSERT(sb);
13237 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13238 #ifdef MAC
13239 	mac_inpcb_create_mbuf(inp, m);
13240 #endif
13241 #ifdef INET6
13242 	if (isipv6) {
13243 		ip6 = mtod(m, struct ip6_hdr *);
13244 		if (tp->t_port) {
13245 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13246 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13247 			udp->uh_dport = tp->t_port;
13248 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13249 			udp->uh_ulen = htons(ulen);
13250 			th = (struct tcphdr *)(udp + 1);
13251 		} else {
13252 			th = (struct tcphdr *)(ip6 + 1);
13253 		}
13254 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13255 	} else
13256 #endif				/* INET6 */
13257 	{
13258 		ip = mtod(m, struct ip *);
13259 		if (tp->t_port) {
13260 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13261 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13262 			udp->uh_dport = tp->t_port;
13263 			ulen = hdrlen + len - sizeof(struct ip);
13264 			udp->uh_ulen = htons(ulen);
13265 			th = (struct tcphdr *)(udp + 1);
13266 		} else {
13267 			th = (struct tcphdr *)(ip + 1);
13268 		}
13269 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13270 	}
13271 	/*
13272 	 * If we are doing retransmissions, then snd_nxt will not reflect
13273 	 * the first unsent octet.  For ACK only packets, we do not want the
13274 	 * sequence number of the retransmitted packet, we want the sequence
13275 	 * number of the next unsent octet.  So, if there is no data (and no
13276 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13277 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13278 	 * one byte beyond the right edge of the window, so use snd_nxt in
13279 	 * that case, since we know we aren't doing a retransmission.
13280 	 * (retransmit and persist are mutually exclusive...)
13281 	 */
13282 	if (sack_rxmit == 0) {
13283 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13284 			/* New data (including new persists) */
13285 			th->th_seq = htonl(tp->snd_max);
13286 			bbr_seq = tp->snd_max;
13287 		} else if (flags & TH_SYN) {
13288 			/* Syn's always send from iss */
13289 			th->th_seq = htonl(tp->iss);
13290 			bbr_seq = tp->iss;
13291 		} else if (flags & TH_FIN) {
13292 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13293 				/*
13294 				 * If we sent the fin already its 1 minus
13295 				 * snd_max
13296 				 */
13297 				th->th_seq = (htonl(tp->snd_max - 1));
13298 				bbr_seq = (tp->snd_max - 1);
13299 			} else {
13300 				/* First time FIN use snd_max */
13301 				th->th_seq = htonl(tp->snd_max);
13302 				bbr_seq = tp->snd_max;
13303 			}
13304 		} else {
13305 			/*
13306 			 * len == 0 and not persist we use snd_max, sending
13307 			 * an ack unless we have sent the fin then its 1
13308 			 * minus.
13309 			 */
13310 			/*
13311 			 * XXXRRS Question if we are in persists and we have
13312 			 * nothing outstanding to send and we have not sent
13313 			 * a FIN, we will send an ACK. In such a case it
13314 			 * might be better to send (tp->snd_una - 1) which
13315 			 * would force the peer to ack.
13316 			 */
13317 			if (tp->t_flags & TF_SENTFIN) {
13318 				th->th_seq = htonl(tp->snd_max - 1);
13319 				bbr_seq = (tp->snd_max - 1);
13320 			} else {
13321 				th->th_seq = htonl(tp->snd_max);
13322 				bbr_seq = tp->snd_max;
13323 			}
13324 		}
13325 	} else {
13326 		/* All retransmits use the rsm to guide the send */
13327 		th->th_seq = htonl(rsm->r_start);
13328 		bbr_seq = rsm->r_start;
13329 	}
13330 	th->th_ack = htonl(tp->rcv_nxt);
13331 	if (optlen) {
13332 		bcopy(opt, th + 1, optlen);
13333 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13334 	}
13335 	tcp_set_flags(th, flags);
13336 	/*
13337 	 * Calculate receive window.  Don't shrink window, but avoid silly
13338 	 * window syndrome.
13339 	 */
13340 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13341 				  recwin < maxseg)))
13342 		recwin = 0;
13343 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13344 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13345 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13346 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13347 		recwin = TCP_MAXWIN << tp->rcv_scale;
13348 
13349 	/*
13350 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13351 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13352 	 * handled in syncache.
13353 	 */
13354 	if (flags & TH_SYN)
13355 		th->th_win = htons((u_short)
13356 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13357 	else {
13358 		/* Avoid shrinking window with window scaling. */
13359 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13360 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13361 	}
13362 	/*
13363 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13364 	 * window.  This may cause the remote transmitter to stall.  This
13365 	 * flag tells soreceive() to disable delayed acknowledgements when
13366 	 * draining the buffer.  This can occur if the receiver is
13367 	 * attempting to read more data than can be buffered prior to
13368 	 * transmitting on the connection.
13369 	 */
13370 	if (th->th_win == 0) {
13371 		tp->t_sndzerowin++;
13372 		tp->t_flags |= TF_RXWIN0SENT;
13373 	} else
13374 		tp->t_flags &= ~TF_RXWIN0SENT;
13375 	/*
13376 	 * We don't support urgent data, but drag along
13377 	 * the pointer in case of a stack switch.
13378 	 */
13379 	tp->snd_up = tp->snd_una;
13380 	/*
13381 	 * Put TCP length in extended header, and then checksum extended
13382 	 * header and data.
13383 	 */
13384 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13385 
13386 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13387 	if (to.to_flags & TOF_SIGNATURE) {
13388 		/*
13389 		 * Calculate MD5 signature and put it into the place
13390 		 * determined before. NOTE: since TCP options buffer doesn't
13391 		 * point into mbuf's data, calculate offset and use it.
13392 		 */
13393 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13394 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13395 			/*
13396 			 * Do not send segment if the calculation of MD5
13397 			 * digest has failed.
13398 			 */
13399 			goto out;
13400 		}
13401 	}
13402 #endif
13403 
13404 #ifdef INET6
13405 	if (isipv6) {
13406 		/*
13407 		 * ip6_plen is not need to be filled now, and will be filled
13408 		 * in ip6_output.
13409 		 */
13410 		if (tp->t_port) {
13411 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13412 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13413 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13414 			th->th_sum = htons(0);
13415 			UDPSTAT_INC(udps_opackets);
13416 		} else {
13417 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13418 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13419 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13420 			    optlen + len, IPPROTO_TCP, 0);
13421 		}
13422 	}
13423 #endif
13424 #if defined(INET6) && defined(INET)
13425 	else
13426 #endif
13427 #ifdef INET
13428 	{
13429 		if (tp->t_port) {
13430 			m->m_pkthdr.csum_flags = CSUM_UDP;
13431 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13432 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13433 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13434 			th->th_sum = htons(0);
13435 			UDPSTAT_INC(udps_opackets);
13436 		} else {
13437 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13438 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13439 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13440 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13441 			    IPPROTO_TCP + len + optlen));
13442 		}
13443 		/* IP version must be set here for ipv4/ipv6 checking later */
13444 		KASSERT(ip->ip_v == IPVERSION,
13445 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13446 	}
13447 #endif
13448 
13449 	/*
13450 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13451 	 * header checksum is always provided. XXX: Fixme: This is currently
13452 	 * not the case for IPv6.
13453 	 */
13454 	if (tso) {
13455 		KASSERT(len > maxseg,
13456 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13457 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13458 		csum_flags |= CSUM_TSO;
13459 		m->m_pkthdr.tso_segsz = maxseg;
13460 	}
13461 	KASSERT(len + hdrlen == m_length(m, NULL),
13462 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13463 	    __func__, len, hdrlen, m_length(m, NULL)));
13464 
13465 #ifdef TCP_HHOOK
13466 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13467 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13468 #endif
13469 
13470 	/* Log to the black box */
13471 	if (tcp_bblogging_on(tp)) {
13472 		union tcp_log_stackspecific log;
13473 
13474 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13475 		/* Record info on type of transmission */
13476 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13477 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13478 		log.u_bbr.flex3 = maxseg;
13479 		log.u_bbr.flex4 = delay_calc;
13480 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13481 		log.u_bbr.flex5 <<= 1;
13482 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13483 		log.u_bbr.flex5 <<= 29;
13484 		log.u_bbr.flex5 |= tp->t_maxseg;
13485 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13486 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13487 		/* lets poke in the low and the high here for debugging */
13488 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13489 		if (rsm || sack_rxmit) {
13490 			if (doing_tlp)
13491 				log.u_bbr.flex8 = 2;
13492 			else
13493 				log.u_bbr.flex8 = 1;
13494 		} else {
13495 			log.u_bbr.flex8 = 0;
13496 		}
13497 		lgb = tcp_log_event(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13498 		    len, &log, false, NULL, NULL, 0, tv);
13499 	} else {
13500 		lgb = NULL;
13501 	}
13502 	/*
13503 	 * Fill in IP length and desired time to live and send to IP level.
13504 	 * There should be a better way to handle ttl and tos; we could keep
13505 	 * them in the template, but need a way to checksum without them.
13506 	 */
13507 	/*
13508 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13509 	 * because in6_cksum() need it.
13510 	 */
13511 #ifdef INET6
13512 	if (isipv6) {
13513 		/*
13514 		 * we separately set hoplimit for every segment, since the
13515 		 * user might want to change the value via setsockopt. Also,
13516 		 * desired default hop limit might be changed via Neighbor
13517 		 * Discovery.
13518 		 */
13519 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13520 
13521 		/*
13522 		 * Set the packet size here for the benefit of DTrace
13523 		 * probes. ip6_output() will set it properly; it's supposed
13524 		 * to include the option header lengths as well.
13525 		 */
13526 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13527 
13528 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13529 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13530 		else
13531 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13532 
13533 		if (tp->t_state == TCPS_SYN_SENT)
13534 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13535 
13536 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13537 		/* TODO: IPv6 IP6TOS_ECT bit on */
13538 		error = ip6_output(m, inp->in6p_outputopts,
13539 		    &inp->inp_route6,
13540 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13541 		    NULL, NULL, inp);
13542 
13543 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13544 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13545 	}
13546 #endif				/* INET6 */
13547 #if defined(INET) && defined(INET6)
13548 	else
13549 #endif
13550 #ifdef INET
13551 	{
13552 		ip->ip_len = htons(m->m_pkthdr.len);
13553 #ifdef INET6
13554 		if (isipv6)
13555 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13556 #endif				/* INET6 */
13557 		/*
13558 		 * If we do path MTU discovery, then we set DF on every
13559 		 * packet. This might not be the best thing to do according
13560 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13561 		 * the problem so it affects only the first tcp connection
13562 		 * with a host.
13563 		 *
13564 		 * NB: Don't set DF on small MTU/MSS to have a safe
13565 		 * fallback.
13566 		 */
13567 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13568 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13569 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13570 				ip->ip_off |= htons(IP_DF);
13571 			}
13572 		} else {
13573 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13574 		}
13575 
13576 		if (tp->t_state == TCPS_SYN_SENT)
13577 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13578 
13579 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13580 
13581 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13582 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13583 		    inp);
13584 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13585 			mtu = inp->inp_route.ro_nh->nh_mtu;
13586 	}
13587 #endif				/* INET */
13588 out:
13589 
13590 	if (lgb) {
13591 		lgb->tlb_errno = error;
13592 		lgb = NULL;
13593 	}
13594 	/*
13595 	 * In transmit state, time the transmission and arrange for the
13596 	 * retransmit.  In persist state, just set snd_max.
13597 	 */
13598 	if (error == 0) {
13599 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13600 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13601 		    (tp->t_flags & TF_SACK_PERMIT) &&
13602 		    tp->rcv_numsacks > 0)
13603 			tcp_clean_dsack_blocks(tp);
13604 		/* We sent an ack clear the bbr_segs_rcvd count */
13605 		bbr->output_error_seen = 0;
13606 		bbr->oerror_cnt = 0;
13607 		bbr->bbr_segs_rcvd = 0;
13608 		if (len == 0)
13609 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13610 		/* Do accounting for new sends */
13611 		if ((len > 0) && (rsm == NULL)) {
13612 			int idx;
13613 			if (tp->snd_una == tp->snd_max) {
13614 				/*
13615 				 * Special case to match google, when
13616 				 * nothing is in flight the delivered
13617 				 * time does get updated to the current
13618 				 * time (see tcp_rate_bsd.c).
13619 				 */
13620 				bbr->r_ctl.rc_del_time = cts;
13621 			}
13622 			if (len >= maxseg) {
13623 				idx = (len / maxseg) + 3;
13624 				if (idx >= TCP_MSS_ACCT_ATIMER)
13625 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13626 				else
13627 					counter_u64_add(bbr_out_size[idx], 1);
13628 			} else {
13629 				/* smaller than a MSS */
13630 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13631 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13632 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13633 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13634 			}
13635 		}
13636 	}
13637 	abandon = 0;
13638 	/*
13639 	 * We must do the send accounting before we log the output,
13640 	 * otherwise the state of the rsm could change and we account to the
13641 	 * wrong bucket.
13642 	 */
13643 	if (len > 0) {
13644 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13645 		if (error == 0) {
13646 			if (tp->snd_una == tp->snd_max)
13647 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13648 		}
13649 	}
13650 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13651 	    cts, mb, &abandon, rsm, 0, sb);
13652 	if (abandon) {
13653 		/*
13654 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13655 		 * sent we should hit this condition.
13656 		 */
13657 		return (0);
13658 	}
13659 	if (bbr->rc_in_persist == 0) {
13660 		/*
13661 		 * Advance snd_nxt over sequence space of this segment.
13662 		 */
13663 		if (error)
13664 			/* We don't log or do anything with errors */
13665 			goto skip_upd;
13666 
13667 		if (tp->snd_una == tp->snd_max &&
13668 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13669 			/*
13670 			 * Update the time we just added data since none was
13671 			 * outstanding.
13672 			 */
13673 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13674 			bbr->rc_tp->t_acktime  = ticks;
13675 		}
13676 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13677 			if (flags & TH_SYN) {
13678 				/*
13679 				 * Smack the snd_max to iss + 1
13680 				 * if its a FO we will add len below.
13681 				 */
13682 				tp->snd_max = tp->iss + 1;
13683 			}
13684 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13685 				tp->snd_max++;
13686 				tp->t_flags |= TF_SENTFIN;
13687 			}
13688 		}
13689 		if (sack_rxmit == 0)
13690 			tp->snd_max += len;
13691 skip_upd:
13692 		if ((error == 0) && len)
13693 			tot_len += len;
13694 	} else {
13695 		/* Persists case */
13696 		int32_t xlen = len;
13697 
13698 		if (error)
13699 			goto nomore;
13700 
13701 		if (flags & TH_SYN)
13702 			++xlen;
13703 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13704 			++xlen;
13705 			tp->t_flags |= TF_SENTFIN;
13706 		}
13707 		if (xlen && (tp->snd_una == tp->snd_max)) {
13708 			/*
13709 			 * Update the time we just added data since none was
13710 			 * outstanding.
13711 			 */
13712 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13713 			bbr->rc_tp->t_acktime = ticks;
13714 		}
13715 		if (sack_rxmit == 0)
13716 			tp->snd_max += xlen;
13717 		tot_len += (len + optlen + ipoptlen);
13718 	}
13719 nomore:
13720 	if (error) {
13721 		/*
13722 		 * Failures do not advance the seq counter above. For the
13723 		 * case of ENOBUFS we will fall out and become ack-clocked.
13724 		 * capping the cwnd at the current flight.
13725 		 * Everything else will just have to retransmit with the timer
13726 		 * (no pacer).
13727 		 */
13728 		SOCKBUF_UNLOCK_ASSERT(sb);
13729 		BBR_STAT_INC(bbr_saw_oerr);
13730 		/* Clear all delay/early tracks */
13731 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13732 		bbr->r_ctl.rc_agg_early = 0;
13733 		bbr->r_agg_early_set = 0;
13734 		bbr->output_error_seen = 1;
13735 		if (bbr->oerror_cnt < 0xf)
13736 			bbr->oerror_cnt++;
13737 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13738 			/* drop the session */
13739 			return (-ENETDOWN);
13740 		}
13741 		switch (error) {
13742 		case ENOBUFS:
13743 			/*
13744 			 * Make this guy have to get ack's to send
13745 			 * more but lets make sure we don't
13746 			 * slam him below a T-O (1MSS).
13747 			 */
13748 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13749 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13750 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13751 				if (tp->snd_cwnd < maxseg)
13752 					tp->snd_cwnd = maxseg;
13753 			}
13754 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13755 			BBR_STAT_INC(bbr_saw_enobuf);
13756 			if (bbr->bbr_hdrw_pacing)
13757 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13758 			else
13759 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13760 			/*
13761 			 * Here even in the enobuf's case we want to do our
13762 			 * state update. The reason being we may have been
13763 			 * called by the input function. If so we have had
13764 			 * things change.
13765 			 */
13766 			error = 0;
13767 			goto enobufs;
13768 		case EMSGSIZE:
13769 			/*
13770 			 * For some reason the interface we used initially
13771 			 * to send segments changed to another or lowered
13772 			 * its MTU. If TSO was active we either got an
13773 			 * interface without TSO capabilits or TSO was
13774 			 * turned off. If we obtained mtu from ip_output()
13775 			 * then update it and try again.
13776 			 */
13777 			/* Turn on tracing (or try to) */
13778 			{
13779 				int old_maxseg;
13780 
13781 				old_maxseg = tp->t_maxseg;
13782 				BBR_STAT_INC(bbr_saw_emsgsiz);
13783 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13784 				if (mtu != 0)
13785 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13786 				if (old_maxseg <= tp->t_maxseg) {
13787 					/* Huh it did not shrink? */
13788 					tp->t_maxseg = old_maxseg - 40;
13789 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13790 				}
13791 				/*
13792 				 * Nuke all other things that can interfere
13793 				 * with slot
13794 				 */
13795 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13796 					slot = bbr_get_pacing_delay(bbr,
13797 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13798 					    (tot_len + len), cts, 0);
13799 					if (slot < bbr_error_base_paceout)
13800 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13801 				} else
13802 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13803 				bbr->rc_output_starts_timer = 1;
13804 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13805 				    tot_len);
13806 				return (error);
13807 			}
13808 		case EPERM:
13809 			tp->t_softerror = error;
13810 			/* FALLTHROUGH */
13811 		case EHOSTDOWN:
13812 		case EHOSTUNREACH:
13813 		case ENETDOWN:
13814 		case ENETUNREACH:
13815 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13816 				tp->t_softerror = error;
13817 			}
13818 			/* FALLTHROUGH */
13819 		default:
13820 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13821 			bbr->rc_output_starts_timer = 1;
13822 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13823 			return (error);
13824 		}
13825 #ifdef STATS
13826 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13827 		    len &&
13828 		    (rsm == NULL) &&
13829 	    (bbr->rc_in_persist == 0)) {
13830 		tp->gput_seq = bbr_seq;
13831 		tp->gput_ack = bbr_seq +
13832 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13833 		tp->gput_ts = cts;
13834 		tp->t_flags |= TF_GPUTINPROG;
13835 #endif
13836 	}
13837 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13838 	if ((bbr->bbr_hdw_pace_ena) &&
13839 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13840 	    (bbr->rc_past_init_win) &&
13841 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13842 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13843 	    (inp->inp_route.ro_nh &&
13844 	     inp->inp_route.ro_nh->nh_ifp)) {
13845 		/*
13846 		 * We are past the initial window and
13847 		 * have at least one measurement so we
13848 		 * could use hardware pacing if its available.
13849 		 * We have an interface and we have not attempted
13850 		 * to setup hardware pacing, lets try to now.
13851 		 */
13852 		uint64_t rate_wanted;
13853 		int err = 0;
13854 
13855 		rate_wanted = bbr_get_hardware_rate(bbr);
13856 		bbr->bbr_attempt_hdwr_pace = 1;
13857 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13858 						      inp->inp_route.ro_nh->nh_ifp,
13859 						      rate_wanted,
13860 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
13861 						      &err, NULL);
13862 		if (bbr->r_ctl.crte) {
13863 			bbr_type_log_hdwr_pacing(bbr,
13864 						 bbr->r_ctl.crte->ptbl->rs_ifp,
13865 						 rate_wanted,
13866 						 bbr->r_ctl.crte->rate,
13867 						 __LINE__, cts, err);
13868 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
13869 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
13870 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
13871 			bbr->bbr_hdrw_pacing = 1;
13872 			/* Now what is our gain status? */
13873 			if (bbr->r_ctl.crte->rate < rate_wanted) {
13874 				/* We have a problem */
13875 				bbr_setup_less_of_rate(bbr, cts,
13876 						       bbr->r_ctl.crte->rate, rate_wanted);
13877 			} else {
13878 				/* We are good */
13879 				bbr->gain_is_limited = 0;
13880 				bbr->skip_gain = 0;
13881 			}
13882 			tcp_bbr_tso_size_check(bbr, cts);
13883 		} else {
13884 			bbr_type_log_hdwr_pacing(bbr,
13885 						 inp->inp_route.ro_nh->nh_ifp,
13886 						 rate_wanted,
13887 						 0,
13888 						 __LINE__, cts, err);
13889 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
13890 		}
13891 	}
13892 	if (bbr->bbr_hdrw_pacing) {
13893 		/*
13894 		 * Worry about cases where the route
13895 		 * changes or something happened that we
13896 		 * lost our hardware pacing possibly during
13897 		 * the last ip_output call.
13898 		 */
13899 		if (inp->inp_snd_tag == NULL) {
13900 			/* A change during ip output disabled hw pacing? */
13901 			bbr->bbr_hdrw_pacing = 0;
13902 		} else if ((inp->inp_route.ro_nh == NULL) ||
13903 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
13904 			/*
13905 			 * We had an interface or route change,
13906 			 * detach from the current hdwr pacing
13907 			 * and setup to re-attempt next go
13908 			 * round.
13909 			 */
13910 			bbr->bbr_hdrw_pacing = 0;
13911 			bbr->bbr_attempt_hdwr_pace = 0;
13912 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
13913 			tcp_bbr_tso_size_check(bbr, cts);
13914 		}
13915 	}
13916 	/*
13917 	 * Data sent (as far as we can tell). If this advertises a larger
13918 	 * window than any other segment, then remember the size of the
13919 	 * advertised window. Any pending ACK has now been sent.
13920 	 */
13921 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
13922 		tp->rcv_adv = tp->rcv_nxt + recwin;
13923 
13924 	tp->last_ack_sent = tp->rcv_nxt;
13925 	if ((error == 0) &&
13926 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
13927 	    (doing_tlp == 0) &&
13928 	    (tso == 0) &&
13929 	    (len > 0) &&
13930 	    ((flags & TH_RST) == 0) &&
13931 	    ((flags & TH_SYN) == 0) &&
13932 	    (IN_RECOVERY(tp->t_flags) == 0) &&
13933 	    (bbr->rc_in_persist == 0) &&
13934 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
13935 		/*
13936 		 * For non-tso we need to goto again until we have sent out
13937 		 * enough data to match what we are hptsi out every hptsi
13938 		 * interval.
13939 		 */
13940 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13941 			/* Make sure snd_nxt is drug up */
13942 			tp->snd_nxt = tp->snd_max;
13943 		}
13944 		if (rsm != NULL) {
13945 			rsm = NULL;
13946 			goto skip_again;
13947 		}
13948 		rsm = NULL;
13949 		sack_rxmit = 0;
13950 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13951 		goto again;
13952 	}
13953 skip_again:
13954 	if ((error == 0) && (flags & TH_FIN))
13955 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
13956 	if ((error == 0) && (flags & TH_RST))
13957 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13958 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
13959 		/*
13960 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
13961 		 * what we have sent so far
13962 		 */
13963 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
13964 		if (bbr->rc_no_pacing)
13965 			slot = 0;
13966 	}
13967 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13968 enobufs:
13969 	if (bbr->rc_use_google == 0)
13970 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
13971 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13972 							bbr->r_ctl.rc_lost_bytes)));
13973 	bbr->rc_output_starts_timer = 1;
13974 	if (bbr->bbr_use_rack_cheat &&
13975 	    (more_to_rxt ||
13976 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
13977 		/* Rack cheats and shotguns out all rxt's 1ms apart */
13978 		if (slot > 1000)
13979 			slot = 1000;
13980 	}
13981 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
13982 		/*
13983 		 * We don't change the tso size until some number of sends
13984 		 * to give the hardware commands time to get down
13985 		 * to the interface.
13986 		 */
13987 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
13988 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
13989 			bbr->hw_pacing_set = 1;
13990 			tcp_bbr_tso_size_check(bbr, cts);
13991 		}
13992 	}
13993 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
13994 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13995 		/* Make sure snd_nxt is drug up */
13996 		tp->snd_nxt = tp->snd_max;
13997 	}
13998 	return (error);
13999 
14000 }
14001 
14002 /*
14003  * See bbr_output_wtime() for return values.
14004  */
14005 static int
14006 bbr_output(struct tcpcb *tp)
14007 {
14008 	int32_t ret;
14009 	struct timeval tv;
14010 
14011 	NET_EPOCH_ASSERT();
14012 
14013 	INP_WLOCK_ASSERT(tptoinpcb(tp));
14014 	(void)tcp_get_usecs(&tv);
14015 	ret = bbr_output_wtime(tp, &tv);
14016 	return (ret);
14017 }
14018 
14019 static void
14020 bbr_mtu_chg(struct tcpcb *tp)
14021 {
14022 	struct tcp_bbr *bbr;
14023 	struct bbr_sendmap *rsm, *frsm = NULL;
14024 	uint32_t maxseg;
14025 
14026 	/*
14027 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14028 	 * over the current size as SACK_PASS so a retransmit will occur.
14029 	 */
14030 
14031 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14032 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14033 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14034 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14035 		/* Don't mess with ones acked (by sack?) */
14036 		if (rsm->r_flags & BBR_ACKED)
14037 			continue;
14038 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14039 			/*
14040 			 * We mark sack-passed on all the previous large
14041 			 * sends we did. This will force them to retransmit.
14042 			 */
14043 			rsm->r_flags |= BBR_SACK_PASSED;
14044 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14045 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14046 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14047 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14048 				rsm->r_flags |= BBR_MARKED_LOST;
14049 			}
14050 			if (frsm == NULL)
14051 				frsm = rsm;
14052 		}
14053 	}
14054 	if (frsm) {
14055 		bbr->r_ctl.rc_resend = frsm;
14056 	}
14057 }
14058 
14059 static int
14060 bbr_pru_options(struct tcpcb *tp, int flags)
14061 {
14062 	if (flags & PRUS_OOB)
14063 		return (EOPNOTSUPP);
14064 	return (0);
14065 }
14066 
14067 static void
14068 bbr_switch_failed(struct tcpcb *tp)
14069 {
14070 	/*
14071 	 * If a switch fails we only need to
14072 	 * make sure mbuf_queuing is still in place.
14073 	 * We also need to make sure we are still in
14074 	 * ticks granularity (though we should probably
14075 	 * change bbr to go to USECs).
14076 	 *
14077 	 * For timers we need to see if we are still in the
14078 	 * pacer (if our flags are up) if so we are good, if
14079 	 * not we need to get back into the pacer.
14080 	 */
14081 	struct timeval tv;
14082 	uint32_t cts;
14083 	uint32_t toval;
14084 	struct tcp_bbr *bbr;
14085 	struct hpts_diag diag;
14086 
14087 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
14088 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
14089 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
14090 	if (tp->t_in_hpts > IHPTS_NONE) {
14091 		return;
14092 	}
14093 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14094 	cts = tcp_get_usecs(&tv);
14095 	if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
14096 		if (TSTMP_GT(bbr->rc_pacer_started, cts)) {
14097 			toval = bbr->rc_pacer_started - cts;
14098 		} else {
14099 			/* one slot please */
14100 			toval = HPTS_TICKS_PER_SLOT;
14101 		}
14102 	} else if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
14103 		if (TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
14104 			toval = bbr->r_ctl.rc_timer_exp - cts;
14105 		} else {
14106 			/* one slot please */
14107 			toval = HPTS_TICKS_PER_SLOT;
14108 		}
14109 	} else
14110 		toval = HPTS_TICKS_PER_SLOT;
14111 	(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(toval),
14112 				   __LINE__, &diag);
14113 	bbr_log_hpts_diag(bbr, cts, &diag);
14114 }
14115 
14116 struct tcp_function_block __tcp_bbr = {
14117 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14118 	.tfb_tcp_output = bbr_output,
14119 	.tfb_do_queued_segments = ctf_do_queued_segments,
14120 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14121 	.tfb_tcp_do_segment = bbr_do_segment,
14122 	.tfb_tcp_ctloutput = bbr_ctloutput,
14123 	.tfb_tcp_fb_init = bbr_init,
14124 	.tfb_tcp_fb_fini = bbr_fini,
14125 	.tfb_tcp_timer_stop_all = bbr_stopall,
14126 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14127 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14128 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14129 	.tfb_pru_options = bbr_pru_options,
14130 	.tfb_switch_failed = bbr_switch_failed,
14131 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14132 };
14133 
14134 /*
14135  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14136  * socket option arguments.  When it re-acquires the lock after the copy, it
14137  * has to revalidate that the connection is still valid for the socket
14138  * option.
14139  */
14140 static int
14141 bbr_set_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14142 {
14143 	struct epoch_tracker et;
14144 	struct inpcb *inp = tptoinpcb(tp);
14145 	struct tcp_bbr *bbr;
14146 	int32_t error = 0, optval;
14147 
14148 	switch (sopt->sopt_level) {
14149 	case IPPROTO_IPV6:
14150 	case IPPROTO_IP:
14151 		return (tcp_default_ctloutput(tp, sopt));
14152 	}
14153 
14154 	switch (sopt->sopt_name) {
14155 	case TCP_RACK_PACE_MAX_SEG:
14156 	case TCP_RACK_MIN_TO:
14157 	case TCP_RACK_REORD_THRESH:
14158 	case TCP_RACK_REORD_FADE:
14159 	case TCP_RACK_TLP_THRESH:
14160 	case TCP_RACK_PKT_DELAY:
14161 	case TCP_BBR_ALGORITHM:
14162 	case TCP_BBR_TSLIMITS:
14163 	case TCP_BBR_IWINTSO:
14164 	case TCP_BBR_RECFORCE:
14165 	case TCP_BBR_STARTUP_PG:
14166 	case TCP_BBR_DRAIN_PG:
14167 	case TCP_BBR_RWND_IS_APP:
14168 	case TCP_BBR_PROBE_RTT_INT:
14169 	case TCP_BBR_PROBE_RTT_GAIN:
14170 	case TCP_BBR_PROBE_RTT_LEN:
14171 	case TCP_BBR_STARTUP_LOSS_EXIT:
14172 	case TCP_BBR_USEDEL_RATE:
14173 	case TCP_BBR_MIN_RTO:
14174 	case TCP_BBR_MAX_RTO:
14175 	case TCP_BBR_PACE_PER_SEC:
14176 	case TCP_DELACK:
14177 	case TCP_BBR_PACE_DEL_TAR:
14178 	case TCP_BBR_SEND_IWND_IN_TSO:
14179 	case TCP_BBR_EXTRA_STATE:
14180 	case TCP_BBR_UTTER_MAX_TSO:
14181 	case TCP_BBR_MIN_TOPACEOUT:
14182 	case TCP_BBR_FLOOR_MIN_TSO:
14183 	case TCP_BBR_TSTMP_RAISES:
14184 	case TCP_BBR_POLICER_DETECT:
14185 	case TCP_BBR_USE_RACK_CHEAT:
14186 	case TCP_DATA_AFTER_CLOSE:
14187 	case TCP_BBR_HDWR_PACE:
14188 	case TCP_BBR_PACE_SEG_MAX:
14189 	case TCP_BBR_PACE_SEG_MIN:
14190 	case TCP_BBR_PACE_CROSS:
14191 	case TCP_BBR_PACE_OH:
14192 	case TCP_BBR_TMR_PACE_OH:
14193 	case TCP_BBR_RACK_RTT_USE:
14194 	case TCP_BBR_RETRAN_WTSO:
14195 		break;
14196 	default:
14197 		return (tcp_default_ctloutput(tp, sopt));
14198 		break;
14199 	}
14200 	INP_WUNLOCK(inp);
14201 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14202 	if (error)
14203 		return (error);
14204 	INP_WLOCK(inp);
14205 	if (inp->inp_flags & INP_DROPPED) {
14206 		INP_WUNLOCK(inp);
14207 		return (ECONNRESET);
14208 	}
14209 	if (tp->t_fb != &__tcp_bbr) {
14210 		INP_WUNLOCK(inp);
14211 		return (ENOPROTOOPT);
14212 	}
14213 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14214 	switch (sopt->sopt_name) {
14215 	case TCP_BBR_PACE_PER_SEC:
14216 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14217 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14218 		break;
14219 	case TCP_BBR_PACE_DEL_TAR:
14220 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14221 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14222 		break;
14223 	case TCP_BBR_PACE_SEG_MAX:
14224 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14225 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14226 		break;
14227 	case TCP_BBR_PACE_SEG_MIN:
14228 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14229 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14230 		break;
14231 	case TCP_BBR_PACE_CROSS:
14232 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14233 		bbr->r_ctl.bbr_cross_over = optval;
14234 		break;
14235 	case TCP_BBR_ALGORITHM:
14236 		BBR_OPTS_INC(tcp_bbr_algorithm);
14237 		if (optval && (bbr->rc_use_google == 0)) {
14238 			/* Turn on the google mode */
14239 			bbr_google_mode_on(bbr);
14240 			if ((optval > 3) && (optval < 500)) {
14241 				/*
14242 				 * Must be at least greater than .3%
14243 				 * and must be less than 50.0%.
14244 				 */
14245 				bbr->r_ctl.bbr_google_discount = optval;
14246 			}
14247 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14248 			/* Turn off the google mode */
14249 			bbr_google_mode_off(bbr);
14250 		}
14251 		break;
14252 	case TCP_BBR_TSLIMITS:
14253 		BBR_OPTS_INC(tcp_bbr_tslimits);
14254 		if (optval == 1)
14255 			bbr->rc_use_ts_limit = 1;
14256 		else if (optval == 0)
14257 			bbr->rc_use_ts_limit = 0;
14258 		else
14259 			error = EINVAL;
14260 		break;
14261 
14262 	case TCP_BBR_IWINTSO:
14263 		BBR_OPTS_INC(tcp_bbr_iwintso);
14264 		if ((optval >= 0) && (optval < 128)) {
14265 			uint32_t twin;
14266 
14267 			bbr->rc_init_win = optval;
14268 			twin = bbr_initial_cwnd(bbr, tp);
14269 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14270 				tp->snd_cwnd = twin;
14271 			else
14272 				error = EBUSY;
14273 		} else
14274 			error = EINVAL;
14275 		break;
14276 	case TCP_BBR_STARTUP_PG:
14277 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14278 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14279 			bbr->r_ctl.rc_startup_pg = optval;
14280 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14281 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14282 			}
14283 		} else
14284 			error = EINVAL;
14285 		break;
14286 	case TCP_BBR_DRAIN_PG:
14287 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14288 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14289 			bbr->r_ctl.rc_drain_pg = optval;
14290 		else
14291 			error = EINVAL;
14292 		break;
14293 	case TCP_BBR_PROBE_RTT_LEN:
14294 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14295 		if (optval <= 1)
14296 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14297 		else
14298 			error = EINVAL;
14299 		break;
14300 	case TCP_BBR_PROBE_RTT_GAIN:
14301 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14302 		if (optval <= BBR_UNIT)
14303 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14304 		else
14305 			error = EINVAL;
14306 		break;
14307 	case TCP_BBR_PROBE_RTT_INT:
14308 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14309 		if (optval > 1000)
14310 			bbr->r_ctl.rc_probertt_int = optval;
14311 		else
14312 			error = EINVAL;
14313 		break;
14314 	case TCP_BBR_MIN_TOPACEOUT:
14315 		BBR_OPTS_INC(tcp_bbr_topaceout);
14316 		if (optval == 0) {
14317 			bbr->no_pacing_until = 0;
14318 			bbr->rc_no_pacing = 0;
14319 		} else if (optval <= 0x00ff) {
14320 			bbr->no_pacing_until = optval;
14321 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14322 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14323 				/* Turn on no pacing */
14324 				bbr->rc_no_pacing = 1;
14325 			}
14326 		} else
14327 			error = EINVAL;
14328 		break;
14329 	case TCP_BBR_STARTUP_LOSS_EXIT:
14330 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14331 		bbr->rc_loss_exit = optval;
14332 		break;
14333 	case TCP_BBR_USEDEL_RATE:
14334 		error = EINVAL;
14335 		break;
14336 	case TCP_BBR_MIN_RTO:
14337 		BBR_OPTS_INC(tcp_bbr_min_rto);
14338 		bbr->r_ctl.rc_min_rto_ms = optval;
14339 		break;
14340 	case TCP_BBR_MAX_RTO:
14341 		BBR_OPTS_INC(tcp_bbr_max_rto);
14342 		bbr->rc_max_rto_sec = optval;
14343 		break;
14344 	case TCP_RACK_MIN_TO:
14345 		/* Minimum time between rack t-o's in ms */
14346 		BBR_OPTS_INC(tcp_rack_min_to);
14347 		bbr->r_ctl.rc_min_to = optval;
14348 		break;
14349 	case TCP_RACK_REORD_THRESH:
14350 		/* RACK reorder threshold (shift amount) */
14351 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14352 		if ((optval > 0) && (optval < 31))
14353 			bbr->r_ctl.rc_reorder_shift = optval;
14354 		else
14355 			error = EINVAL;
14356 		break;
14357 	case TCP_RACK_REORD_FADE:
14358 		/* Does reordering fade after ms time */
14359 		BBR_OPTS_INC(tcp_rack_reord_fade);
14360 		bbr->r_ctl.rc_reorder_fade = optval;
14361 		break;
14362 	case TCP_RACK_TLP_THRESH:
14363 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14364 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14365 		if (optval)
14366 			bbr->rc_tlp_threshold = optval;
14367 		else
14368 			error = EINVAL;
14369 		break;
14370 	case TCP_BBR_USE_RACK_CHEAT:
14371 		BBR_OPTS_INC(tcp_use_rackcheat);
14372 		if (bbr->rc_use_google) {
14373 			error = EINVAL;
14374 			break;
14375 		}
14376 		BBR_OPTS_INC(tcp_rack_cheat);
14377 		if (optval)
14378 			bbr->bbr_use_rack_cheat = 1;
14379 		else
14380 			bbr->bbr_use_rack_cheat = 0;
14381 		break;
14382 	case TCP_BBR_FLOOR_MIN_TSO:
14383 		BBR_OPTS_INC(tcp_utter_max_tso);
14384 		if ((optval >= 0) && (optval < 40))
14385 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14386 		else
14387 			error = EINVAL;
14388 		break;
14389 	case TCP_BBR_UTTER_MAX_TSO:
14390 		BBR_OPTS_INC(tcp_utter_max_tso);
14391 		if ((optval >= 0) && (optval < 0xffff))
14392 			bbr->r_ctl.bbr_utter_max = optval;
14393 		else
14394 			error = EINVAL;
14395 		break;
14396 
14397 	case TCP_BBR_EXTRA_STATE:
14398 		BBR_OPTS_INC(tcp_extra_state);
14399 		if (optval)
14400 			bbr->rc_use_idle_restart = 1;
14401 		else
14402 			bbr->rc_use_idle_restart = 0;
14403 		break;
14404 	case TCP_BBR_SEND_IWND_IN_TSO:
14405 		BBR_OPTS_INC(tcp_iwnd_tso);
14406 		if (optval) {
14407 			bbr->bbr_init_win_cheat = 1;
14408 			if (bbr->rc_past_init_win == 0) {
14409 				uint32_t cts;
14410 				cts = tcp_get_usecs(&bbr->rc_tv);
14411 				tcp_bbr_tso_size_check(bbr, cts);
14412 			}
14413 		} else
14414 			bbr->bbr_init_win_cheat = 0;
14415 		break;
14416 	case TCP_BBR_HDWR_PACE:
14417 		BBR_OPTS_INC(tcp_hdwr_pacing);
14418 		if (optval){
14419 			bbr->bbr_hdw_pace_ena = 1;
14420 			bbr->bbr_attempt_hdwr_pace = 0;
14421 		} else {
14422 			bbr->bbr_hdw_pace_ena = 0;
14423 #ifdef RATELIMIT
14424 			if (bbr->r_ctl.crte != NULL) {
14425 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14426 				bbr->r_ctl.crte = NULL;
14427 			}
14428 #endif
14429 		}
14430 		break;
14431 
14432 	case TCP_DELACK:
14433 		BBR_OPTS_INC(tcp_delack);
14434 		if (optval < 100) {
14435 			if (optval == 0) /* off */
14436 				tp->t_delayed_ack = 0;
14437 			else if (optval == 1) /* on which is 2 */
14438 				tp->t_delayed_ack = 2;
14439 			else /* higher than 2 and less than 100 */
14440 				tp->t_delayed_ack = optval;
14441 			if (tp->t_flags & TF_DELACK) {
14442 				tp->t_flags &= ~TF_DELACK;
14443 				tp->t_flags |= TF_ACKNOW;
14444 				NET_EPOCH_ENTER(et);
14445 				bbr_output(tp);
14446 				NET_EPOCH_EXIT(et);
14447 			}
14448 		} else
14449 			error = EINVAL;
14450 		break;
14451 	case TCP_RACK_PKT_DELAY:
14452 		/* RACK added ms i.e. rack-rtt + reord + N */
14453 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14454 		bbr->r_ctl.rc_pkt_delay = optval;
14455 		break;
14456 
14457 	case TCP_BBR_RETRAN_WTSO:
14458 		BBR_OPTS_INC(tcp_retran_wtso);
14459 		if (optval)
14460 			bbr->rc_resends_use_tso = 1;
14461 		else
14462 			bbr->rc_resends_use_tso = 0;
14463 		break;
14464 	case TCP_DATA_AFTER_CLOSE:
14465 		BBR_OPTS_INC(tcp_data_ac);
14466 		if (optval)
14467 			bbr->rc_allow_data_af_clo = 1;
14468 		else
14469 			bbr->rc_allow_data_af_clo = 0;
14470 		break;
14471 	case TCP_BBR_POLICER_DETECT:
14472 		BBR_OPTS_INC(tcp_policer_det);
14473 		if (bbr->rc_use_google == 0)
14474 			error = EINVAL;
14475 		else if (optval)
14476 			bbr->r_use_policer = 1;
14477 		else
14478 			bbr->r_use_policer = 0;
14479 		break;
14480 
14481 	case TCP_BBR_TSTMP_RAISES:
14482 		BBR_OPTS_INC(tcp_ts_raises);
14483 		if (optval)
14484 			bbr->ts_can_raise = 1;
14485 		else
14486 			bbr->ts_can_raise = 0;
14487 		break;
14488 	case TCP_BBR_TMR_PACE_OH:
14489 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14490 		if (bbr->rc_use_google) {
14491 			error = EINVAL;
14492 		} else {
14493 			if (optval)
14494 				bbr->r_ctl.rc_incr_tmrs = 1;
14495 			else
14496 				bbr->r_ctl.rc_incr_tmrs = 0;
14497 		}
14498 		break;
14499 	case TCP_BBR_PACE_OH:
14500 		BBR_OPTS_INC(tcp_pacing_oh);
14501 		if (bbr->rc_use_google) {
14502 			error = EINVAL;
14503 		} else {
14504 			if (optval > (BBR_INCL_TCP_OH|
14505 				      BBR_INCL_IP_OH|
14506 				      BBR_INCL_ENET_OH)) {
14507 				error = EINVAL;
14508 				break;
14509 			}
14510 			if (optval & BBR_INCL_TCP_OH)
14511 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14512 			else
14513 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14514 			if (optval & BBR_INCL_IP_OH)
14515 				bbr->r_ctl.rc_inc_ip_oh = 1;
14516 			else
14517 				bbr->r_ctl.rc_inc_ip_oh = 0;
14518 			if (optval & BBR_INCL_ENET_OH)
14519 				bbr->r_ctl.rc_inc_enet_oh = 1;
14520 			else
14521 				bbr->r_ctl.rc_inc_enet_oh = 0;
14522 		}
14523 		break;
14524 	default:
14525 		return (tcp_default_ctloutput(tp, sopt));
14526 		break;
14527 	}
14528 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14529 	INP_WUNLOCK(inp);
14530 	return (error);
14531 }
14532 
14533 /*
14534  * return 0 on success, error-num on failure
14535  */
14536 static int
14537 bbr_get_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14538 {
14539 	struct inpcb *inp = tptoinpcb(tp);
14540 	struct tcp_bbr *bbr;
14541 	int32_t error, optval;
14542 
14543 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14544 	if (bbr == NULL) {
14545 		INP_WUNLOCK(inp);
14546 		return (EINVAL);
14547 	}
14548 	/*
14549 	 * Because all our options are either boolean or an int, we can just
14550 	 * pull everything into optval and then unlock and copy. If we ever
14551 	 * add a option that is not a int, then this will have quite an
14552 	 * impact to this routine.
14553 	 */
14554 	switch (sopt->sopt_name) {
14555 	case TCP_BBR_PACE_PER_SEC:
14556 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14557 		break;
14558 	case TCP_BBR_PACE_DEL_TAR:
14559 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14560 		break;
14561 	case TCP_BBR_PACE_SEG_MAX:
14562 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14563 		break;
14564 	case TCP_BBR_MIN_TOPACEOUT:
14565 		optval = bbr->no_pacing_until;
14566 		break;
14567 	case TCP_BBR_PACE_SEG_MIN:
14568 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14569 		break;
14570 	case TCP_BBR_PACE_CROSS:
14571 		optval = bbr->r_ctl.bbr_cross_over;
14572 		break;
14573 	case TCP_BBR_ALGORITHM:
14574 		optval = bbr->rc_use_google;
14575 		break;
14576 	case TCP_BBR_TSLIMITS:
14577 		optval = bbr->rc_use_ts_limit;
14578 		break;
14579 	case TCP_BBR_IWINTSO:
14580 		optval = bbr->rc_init_win;
14581 		break;
14582 	case TCP_BBR_STARTUP_PG:
14583 		optval = bbr->r_ctl.rc_startup_pg;
14584 		break;
14585 	case TCP_BBR_DRAIN_PG:
14586 		optval = bbr->r_ctl.rc_drain_pg;
14587 		break;
14588 	case TCP_BBR_PROBE_RTT_INT:
14589 		optval = bbr->r_ctl.rc_probertt_int;
14590 		break;
14591 	case TCP_BBR_PROBE_RTT_LEN:
14592 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14593 		break;
14594 	case TCP_BBR_PROBE_RTT_GAIN:
14595 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14596 		break;
14597 	case TCP_BBR_STARTUP_LOSS_EXIT:
14598 		optval = bbr->rc_loss_exit;
14599 		break;
14600 	case TCP_BBR_USEDEL_RATE:
14601 		error = EINVAL;
14602 		break;
14603 	case TCP_BBR_MIN_RTO:
14604 		optval = bbr->r_ctl.rc_min_rto_ms;
14605 		break;
14606 	case TCP_BBR_MAX_RTO:
14607 		optval = bbr->rc_max_rto_sec;
14608 		break;
14609 	case TCP_RACK_PACE_MAX_SEG:
14610 		/* Max segments in a pace */
14611 		optval = bbr->r_ctl.rc_pace_max_segs;
14612 		break;
14613 	case TCP_RACK_MIN_TO:
14614 		/* Minimum time between rack t-o's in ms */
14615 		optval = bbr->r_ctl.rc_min_to;
14616 		break;
14617 	case TCP_RACK_REORD_THRESH:
14618 		/* RACK reorder threshold (shift amount) */
14619 		optval = bbr->r_ctl.rc_reorder_shift;
14620 		break;
14621 	case TCP_RACK_REORD_FADE:
14622 		/* Does reordering fade after ms time */
14623 		optval = bbr->r_ctl.rc_reorder_fade;
14624 		break;
14625 	case TCP_BBR_USE_RACK_CHEAT:
14626 		/* Do we use the rack cheat for rxt */
14627 		optval = bbr->bbr_use_rack_cheat;
14628 		break;
14629 	case TCP_BBR_FLOOR_MIN_TSO:
14630 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14631 		break;
14632 	case TCP_BBR_UTTER_MAX_TSO:
14633 		optval = bbr->r_ctl.bbr_utter_max;
14634 		break;
14635 	case TCP_BBR_SEND_IWND_IN_TSO:
14636 		/* Do we send TSO size segments initially */
14637 		optval = bbr->bbr_init_win_cheat;
14638 		break;
14639 	case TCP_BBR_EXTRA_STATE:
14640 		optval = bbr->rc_use_idle_restart;
14641 		break;
14642 	case TCP_RACK_TLP_THRESH:
14643 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14644 		optval = bbr->rc_tlp_threshold;
14645 		break;
14646 	case TCP_RACK_PKT_DELAY:
14647 		/* RACK added ms i.e. rack-rtt + reord + N */
14648 		optval = bbr->r_ctl.rc_pkt_delay;
14649 		break;
14650 	case TCP_BBR_RETRAN_WTSO:
14651 		optval = bbr->rc_resends_use_tso;
14652 		break;
14653 	case TCP_DATA_AFTER_CLOSE:
14654 		optval = bbr->rc_allow_data_af_clo;
14655 		break;
14656 	case TCP_DELACK:
14657 		optval = tp->t_delayed_ack;
14658 		break;
14659 	case TCP_BBR_HDWR_PACE:
14660 		optval = bbr->bbr_hdw_pace_ena;
14661 		break;
14662 	case TCP_BBR_POLICER_DETECT:
14663 		optval = bbr->r_use_policer;
14664 		break;
14665 	case TCP_BBR_TSTMP_RAISES:
14666 		optval = bbr->ts_can_raise;
14667 		break;
14668 	case TCP_BBR_TMR_PACE_OH:
14669 		optval = bbr->r_ctl.rc_incr_tmrs;
14670 		break;
14671 	case TCP_BBR_PACE_OH:
14672 		optval = 0;
14673 		if (bbr->r_ctl.rc_inc_tcp_oh)
14674 			optval |= BBR_INCL_TCP_OH;
14675 		if (bbr->r_ctl.rc_inc_ip_oh)
14676 			optval |= BBR_INCL_IP_OH;
14677 		if (bbr->r_ctl.rc_inc_enet_oh)
14678 			optval |= BBR_INCL_ENET_OH;
14679 		break;
14680 	default:
14681 		return (tcp_default_ctloutput(tp, sopt));
14682 		break;
14683 	}
14684 	INP_WUNLOCK(inp);
14685 	error = sooptcopyout(sopt, &optval, sizeof optval);
14686 	return (error);
14687 }
14688 
14689 /*
14690  * return 0 on success, error-num on failure
14691  */
14692 static int
14693 bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt)
14694 {
14695 	if (sopt->sopt_dir == SOPT_SET) {
14696 		return (bbr_set_sockopt(tp, sopt));
14697 	} else if (sopt->sopt_dir == SOPT_GET) {
14698 		return (bbr_get_sockopt(tp, sopt));
14699 	} else {
14700 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14701 	}
14702 }
14703 
14704 static const char *bbr_stack_names[] = {
14705 	__XSTRING(STACKNAME),
14706 #ifdef STACKALIAS
14707 	__XSTRING(STACKALIAS),
14708 #endif
14709 };
14710 
14711 static bool bbr_mod_inited = false;
14712 
14713 static int
14714 tcp_addbbr(module_t mod, int32_t type, void *data)
14715 {
14716 	int32_t err = 0;
14717 	int num_stacks;
14718 
14719 	switch (type) {
14720 	case MOD_LOAD:
14721 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14722 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14723 		    sizeof(struct bbr_sendmap),
14724 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14725 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14726 		    sizeof(struct tcp_bbr),
14727 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14728 		sysctl_ctx_init(&bbr_sysctl_ctx);
14729 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14730 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14731 		    OID_AUTO,
14732 #ifdef STACKALIAS
14733 		    __XSTRING(STACKALIAS),
14734 #else
14735 		    __XSTRING(STACKNAME),
14736 #endif
14737 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14738 		    "");
14739 		if (bbr_sysctl_root == NULL) {
14740 			printf("Failed to add sysctl node\n");
14741 			err = EFAULT;
14742 			goto free_uma;
14743 		}
14744 		bbr_init_sysctls();
14745 		num_stacks = nitems(bbr_stack_names);
14746 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14747 		    bbr_stack_names, &num_stacks);
14748 		if (err) {
14749 			printf("Failed to register %s stack name for "
14750 			    "%s module\n", bbr_stack_names[num_stacks],
14751 			    __XSTRING(MODNAME));
14752 			sysctl_ctx_free(&bbr_sysctl_ctx);
14753 	free_uma:
14754 			uma_zdestroy(bbr_zone);
14755 			uma_zdestroy(bbr_pcb_zone);
14756 			bbr_counter_destroy();
14757 			printf("Failed to register " __XSTRING(MODNAME)
14758 			    " module err:%d\n", err);
14759 			return (err);
14760 		}
14761 		tcp_lro_reg_mbufq();
14762 		bbr_mod_inited = true;
14763 		printf(__XSTRING(MODNAME) " is now available\n");
14764 		break;
14765 	case MOD_QUIESCE:
14766 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14767 		break;
14768 	case MOD_UNLOAD:
14769 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14770 		if (err == EBUSY)
14771 			break;
14772 		if (bbr_mod_inited) {
14773 			uma_zdestroy(bbr_zone);
14774 			uma_zdestroy(bbr_pcb_zone);
14775 			sysctl_ctx_free(&bbr_sysctl_ctx);
14776 			bbr_counter_destroy();
14777 			printf(__XSTRING(MODNAME)
14778 			    " is now no longer available\n");
14779 			bbr_mod_inited = false;
14780 		}
14781 		tcp_lro_dereg_mbufq();
14782 		err = 0;
14783 		break;
14784 	default:
14785 		return (EOPNOTSUPP);
14786 	}
14787 	return (err);
14788 }
14789 
14790 static moduledata_t tcp_bbr = {
14791 	.name = __XSTRING(MODNAME),
14792 	    .evhand = tcp_addbbr,
14793 	    .priv = 0
14794 };
14795 
14796 MODULE_VERSION(MODNAME, 1);
14797 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14798 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14799