xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision 718519f4efc71096422fc71dab90b2a3369871ff)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_ratelimit.h"
38 #include <sys/param.h>
39 #include <sys/arb.h>
40 #include <sys/module.h>
41 #include <sys/kernel.h>
42 #include <sys/libkern.h>
43 #ifdef TCP_HHOOK
44 #include <sys/hhook.h>
45 #endif
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/proc.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #ifdef STATS
54 #include <sys/qmath.h>
55 #include <sys/tree.h>
56 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
57 #endif
58 #include <sys/refcount.h>
59 #include <sys/queue.h>
60 #include <sys/eventhandler.h>
61 #include <sys/smp.h>
62 #include <sys/kthread.h>
63 #include <sys/lock.h>
64 #include <sys/mutex.h>
65 #include <sys/tim_filter.h>
66 #include <sys/time.h>
67 #include <sys/protosw.h>
68 #include <vm/uma.h>
69 #include <sys/kern_prefetch.h>
70 
71 #include <net/route.h>
72 #include <net/route/nhop.h>
73 #include <net/vnet.h>
74 
75 #define TCPSTATES		/* for logging */
76 
77 #include <netinet/in.h>
78 #include <netinet/in_kdtrace.h>
79 #include <netinet/in_pcb.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
82 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
83 #include <netinet/ip_var.h>
84 #include <netinet/ip6.h>
85 #include <netinet6/in6_pcb.h>
86 #include <netinet6/ip6_var.h>
87 #define	TCPOUTFLAGS
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/tcpip.h>
94 #include <netinet/tcp_hpts.h>
95 #include <netinet/cc/cc.h>
96 #include <netinet/tcp_log_buf.h>
97 #include <netinet/tcp_ratelimit.h>
98 #include <netinet/tcp_lro.h>
99 #ifdef TCP_OFFLOAD
100 #include <netinet/tcp_offload.h>
101 #endif
102 #ifdef INET6
103 #include <netinet6/tcp6_var.h>
104 #endif
105 #include <netinet/tcp_fastopen.h>
106 
107 #include <netipsec/ipsec_support.h>
108 #include <net/if.h>
109 #include <net/if_var.h>
110 #include <net/ethernet.h>
111 
112 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
113 #include <netipsec/ipsec.h>
114 #include <netipsec/ipsec6.h>
115 #endif				/* IPSEC */
116 
117 #include <netinet/udp.h>
118 #include <netinet/udp_var.h>
119 #include <machine/in_cksum.h>
120 
121 #ifdef MAC
122 #include <security/mac/mac_framework.h>
123 #endif
124 
125 #include "sack_filter.h"
126 #include "tcp_bbr.h"
127 #include "rack_bbr_common.h"
128 uma_zone_t bbr_zone;
129 uma_zone_t bbr_pcb_zone;
130 
131 struct sysctl_ctx_list bbr_sysctl_ctx;
132 struct sysctl_oid *bbr_sysctl_root;
133 
134 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
135 	(tv) = (value); \
136 	if ((u_long)(tv) < (u_long)(tvmin)) \
137 		(tv) = (tvmin); \
138 	if ((u_long)(tv) > (u_long)(tvmax)) \
139 		(tv) = (tvmax); \
140 } while(0)
141 
142 /*#define BBR_INVARIANT 1*/
143 
144 /*
145  * initial window
146  */
147 static uint32_t bbr_def_init_win = 10;
148 static int32_t bbr_persist_min = 250000;	/* 250ms */
149 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
150 static int32_t bbr_cwnd_may_shrink = 0;
151 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
152 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
153 static int32_t bbr_hardware_pacing_limit = 8000;
154 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
155 static int32_t bbr_no_retran = 0;
156 
157 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
158 static int32_t bbr_max_net_error_cnt = 10;
159 /* Should the following be dynamic too -- loss wise */
160 static int32_t bbr_rtt_gain_thresh = 0;
161 /* Measurement controls */
162 static int32_t bbr_use_google_algo = 1;
163 static int32_t bbr_ts_limiting = 1;
164 static int32_t bbr_ts_can_raise = 0;
165 static int32_t bbr_do_red = 600;
166 static int32_t bbr_red_scale = 20000;
167 static int32_t bbr_red_mul = 1;
168 static int32_t bbr_red_div = 2;
169 static int32_t bbr_red_growth_restrict = 1;
170 static int32_t  bbr_target_is_bbunit = 0;
171 static int32_t bbr_drop_limit = 0;
172 /*
173  * How much gain do we need to see to
174  * stay in startup?
175  */
176 static int32_t bbr_marks_rxt_sack_passed = 0;
177 static int32_t bbr_start_exit = 25;
178 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
179 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
180 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
181 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
182 					 * if we go back ever to where the pacer
183 					 * has priority over timers.
184 					 */
185 static int32_t bbr_policer_call_from_rack_to = 0;
186 static int32_t bbr_policer_detection_enabled = 1;
187 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
188 						 * measurements before we are
189 						 * "good" note that 2 == 1.
190 						 * This is because we use a >
191 						 * comparison. This means if
192 						 * min_measure was 0, it takes
193 						 * num-measures > min(0) and
194 						 * you get 1 measurement and
195 						 * you are good. Set to 1, you
196 						 * have to have two
197 						 * measurements (this is done
198 						 * to prevent it from being ok
199 						 * to have no measurements). */
200 static int32_t bbr_no_pacing_until = 4;
201 
202 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
203 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
204 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
205 
206 static int32_t bbr_target_cwnd_mult_limit = 8;
207 /*
208  * bbr_cwnd_min_val is the number of
209  * segments we hold to in the RTT probe
210  * state typically 4.
211  */
212 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
213 
214 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
215 
216 static int32_t bbr_gain_to_target = 1;
217 static int32_t bbr_gain_gets_extra_too = 1;
218 /*
219  * bbr_high_gain is the 2/ln(2) value we need
220  * to double the sending rate in startup. This
221  * is used for both cwnd and hptsi gain's.
222  */
223 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
224 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
225 static int32_t bbr_use_lower_gain_in_startup = 1;
226 
227 /* thresholds for reduction on drain in sub-states/drain */
228 static int32_t bbr_drain_rtt = BBR_SRTT;
229 static int32_t bbr_drain_floor = 88;
230 static int32_t google_allow_early_out = 1;
231 static int32_t google_consider_lost = 1;
232 static int32_t bbr_drain_drop_mul = 4;
233 static int32_t bbr_drain_drop_div = 5;
234 static int32_t bbr_rand_ot = 50;
235 static int32_t bbr_can_force_probertt = 0;
236 static int32_t bbr_can_adjust_probertt = 1;
237 static int32_t bbr_probertt_sets_rtt = 0;
238 static int32_t bbr_can_use_ts_for_rtt = 1;
239 static int32_t bbr_is_ratio = 0;
240 static int32_t bbr_sub_drain_app_limit = 1;
241 static int32_t bbr_prtt_slam_cwnd = 1;
242 static int32_t bbr_sub_drain_slam_cwnd = 1;
243 static int32_t bbr_slam_cwnd_in_main_drain = 1;
244 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
245 					 * hold */
246 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
247 /*
248  * bbr_drain_gain is the reverse of the high_gain
249  * designed to drain back out the standing queue
250  * that is formed in startup by causing a larger
251  * hptsi gain and thus drainging the packets
252  * in flight.
253  */
254 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
255 static int32_t bbr_rttprobe_gain = 192;
256 
257 /*
258  * The cwnd_gain is the default cwnd gain applied when
259  * calculating a target cwnd. Note that the cwnd is
260  * a secondary factor in the way BBR works (see the
261  * paper and think about it, it will take some time).
262  * Basically the hptsi_gain spreads the packets out
263  * so you never get more than BDP to the peer even
264  * if the cwnd is high. In our implemenation that
265  * means in non-recovery/retransmission scenarios
266  * cwnd will never be reached by the flight-size.
267  */
268 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
269 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
270 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
271 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
272 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
273 static int32_t bbr_ignore_data_after_close = 1;
274 static int16_t bbr_hptsi_gain[] = {
275 	(BBR_UNIT *5 / 4),
276 	(BBR_UNIT * 3 / 4),
277 	BBR_UNIT,
278 	BBR_UNIT,
279 	BBR_UNIT,
280 	BBR_UNIT,
281 	BBR_UNIT,
282 	BBR_UNIT
283 };
284 int32_t bbr_use_rack_resend_cheat = 1;
285 int32_t bbr_sends_full_iwnd = 1;
286 
287 #define BBR_HPTSI_GAIN_MAX 8
288 /*
289  * The BBR module incorporates a number of
290  * TCP ideas that have been put out into the IETF
291  * over the last few years:
292  * - Yuchung Cheng's RACK TCP (for which its named) that
293  *    will stop us using the number of dup acks and instead
294  *    use time as the gage of when we retransmit.
295  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
296  *    of Dukkipati et.al.
297  * - Van Jacobson's et.al BBR.
298  *
299  * RACK depends on SACK, so if an endpoint arrives that
300  * cannot do SACK the state machine below will shuttle the
301  * connection back to using the "default" TCP stack that is
302  * in FreeBSD.
303  *
304  * To implement BBR and RACK the original TCP stack was first decomposed
305  * into a functional state machine with individual states
306  * for each of the possible TCP connection states. The do_segment
307  * functions role in life is to mandate the connection supports SACK
308  * initially and then assure that the RACK state matches the conenction
309  * state before calling the states do_segment function. Data processing
310  * of inbound segments also now happens in the hpts_do_segment in general
311  * with only one exception. This is so we can keep the connection on
312  * a single CPU.
313  *
314  * Each state is simplified due to the fact that the original do_segment
315  * has been decomposed and we *know* what state we are in (no
316  * switches on the state) and all tests for SACK are gone. This
317  * greatly simplifies what each state does.
318  *
319  * TCP output is also over-written with a new version since it
320  * must maintain the new rack scoreboard and has had hptsi
321  * integrated as a requirment. Still todo is to eliminate the
322  * use of the callout_() system and use the hpts for all
323  * timers as well.
324  */
325 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
326 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
327 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
328 						 * free list */
329 static int32_t bbr_tlp_thresh = 1;
330 static int32_t bbr_reorder_thresh = 2;
331 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
332 						 * 60,000,000 - 60 seconds */
333 static int32_t bbr_pkt_delay = 1000;
334 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
335 static int32_t bbr_incr_timers = 1;
336 
337 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
338 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
339 static int32_t bbr_exit_startup_at_loss = 1;
340 
341 /*
342  * bbr_lt_bw_ratio is 1/8th
343  * bbr_lt_bw_diff is  < 4 Kbit/sec
344  */
345 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
346 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
347 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
348 						 * the lt_bw for */
349 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
350 						 * lt_bw */
351 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
352 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
353 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
354 
355 static int32_t bbr_verbose_logging = 0;
356 /*
357  * Currently regular tcp has a rto_min of 30ms
358  * the backoff goes 12 times so that ends up
359  * being a total of 122.850 seconds before a
360  * connection is killed.
361  */
362 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
363 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
364 
365 /****************************************************/
366 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
367 /****************************************************/
368 /* What amount is our formula using to get TSO size */
369 static int32_t bbr_hptsi_per_second = 1000;
370 
371 /*
372  * For hptsi under bbr_cross_over connections what is delay
373  * target 7ms (in usec) combined with a seg_max of 2
374  * gets us close to identical google behavior in
375  * TSO size selection (possibly more 1MSS sends).
376  */
377 static int32_t bbr_hptsi_segments_delay_tar = 7000;
378 
379 /* Does pacing delay include overhead's in its time calculations? */
380 static int32_t bbr_include_enet_oh = 0;
381 static int32_t bbr_include_ip_oh = 1;
382 static int32_t bbr_include_tcp_oh = 1;
383 static int32_t bbr_google_discount = 10;
384 
385 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
386 static int32_t bbr_state_is_pkt_epoch = 0;
387 static int32_t bbr_state_drain_2_tar = 1;
388 /* What is the max the 0 - bbr_cross_over MBPS TSO target
389  * can reach using our delay target. Note that this
390  * value becomes the floor for the cross over
391  * algorithm.
392  */
393 static int32_t bbr_hptsi_segments_max = 2;
394 static int32_t bbr_hptsi_segments_floor = 1;
395 static int32_t bbr_hptsi_utter_max = 0;
396 
397 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
398 static int32_t bbr_hptsi_bytes_min = 1460;
399 static int32_t bbr_all_get_min = 0;
400 
401 /* Cross over point from algo-a to algo-b */
402 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
403 
404 /* Do we deal with our restart state? */
405 static int32_t bbr_uses_idle_restart = 0;
406 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
407 
408 /* Do we allow hardware pacing? */
409 static int32_t bbr_allow_hdwr_pacing = 0;
410 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
411 static int32_t bbr_hdwr_pace_floor = 1;
412 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
413 
414 /****************************************************/
415 static int32_t bbr_resends_use_tso = 0;
416 static int32_t bbr_tlp_max_resend = 2;
417 static int32_t bbr_sack_block_limit = 128;
418 
419 #define  BBR_MAX_STAT 19
420 counter_u64_t bbr_state_time[BBR_MAX_STAT];
421 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
422 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
423 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
424 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
425 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
426 counter_u64_t bbr_flows_whdwr_pacing;
427 counter_u64_t bbr_flows_nohdwr_pacing;
428 
429 counter_u64_t bbr_nohdwr_pacing_enobuf;
430 counter_u64_t bbr_hdwr_pacing_enobuf;
431 
432 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
433 
434 /*
435  * Static defintions we need for forward declarations.
436  */
437 static uint32_t
438 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
439 		      uint32_t useconds_time, uint64_t bw);
440 static uint32_t
441 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
442 static void
443 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
444 static void
445 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
446 static void
447 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
448 		    int dolog);
449 static uint32_t
450 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
451 static void
452 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
453 		 int32_t pkt_epoch, uint32_t losses);
454 static uint32_t
455 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts,
456 		     struct bbr_sendmap *rsm);
457 static uint32_t
458 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
459 static uint32_t
460 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
461 		    struct bbr_sendmap *rsm, uint32_t srtt, uint32_t cts);
462 static void
463 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
464 		 int32_t line);
465 static void
466 bbr_set_state_target(struct tcp_bbr *bbr, int line);
467 static void
468 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
469 static void
470 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick,
471 		       int event, int line);
472 static void
473 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
474 static void
475 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
476 static void
477 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
478 		    uint32_t rtt, uint32_t line, uint8_t is_start,
479 		    uint16_t set);
480 static struct bbr_sendmap *
481 bbr_find_lowest_rsm(struct tcp_bbr *bbr);
482 static __inline uint32_t
483 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
484 static void
485 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot,
486 		 uint8_t which);
487 static void
488 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts,
489 		  uint32_t time_since_sent, uint32_t srtt,
490 		  uint32_t thresh, uint32_t to);
491 static void
492 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
493 static void
494 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
495 		    uint32_t del_by, uint32_t cts, uint32_t sloton,
496 		    uint32_t prev_delay);
497 static void
498 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
499 		  int32_t line);
500 static void
501 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr);
502 static void
503 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
504 static void
505 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
506 static void
507 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
508 static void
509 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
510 			  uint32_t cts, uint32_t usecs, uint64_t bw,
511 			  uint32_t override, int mod);
512 static int bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt);
513 
514 static inline uint8_t
515 bbr_state_val(struct tcp_bbr *bbr)
516 {
517 	return(bbr->rc_bbr_substate);
518 }
519 
520 static inline uint32_t
521 get_min_cwnd(struct tcp_bbr *bbr)
522 {
523 	int mss;
524 
525 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
526 		  bbr->r_ctl.rc_pace_max_segs);
527 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
528 		return (bbr_cwnd_min_val_hs * mss);
529 	else
530 		return (bbr_cwnd_min_val * mss);
531 }
532 
533 static uint32_t
534 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
535 {
536 	uint64_t srtt, var;
537 	uint64_t ret_val;
538 
539 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
540 	if (tp->t_srtt == 0) {
541 		srtt = (uint64_t)BBR_INITIAL_RTO;
542 		var = 0;
543 	} else {
544 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
545 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
546 	}
547 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
548 	    bbr_persist_min, bbr_persist_max);
549 	return ((uint32_t)ret_val);
550 }
551 
552 static uint32_t
553 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
554 {
555 	/*
556 	 * Start the FR timer, we do this based on getting the first one in
557 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
558 	 * events we need to stop the running timer (if its running) before
559 	 * starting the new one.
560 	 */
561 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
562 	int32_t idx;
563 	int32_t is_tlp_timer = 0;
564 	struct bbr_sendmap *rsm;
565 
566 	if (bbr->rc_all_timers_stopped) {
567 		/* All timers have been stopped none are to run */
568 		return (0);
569 	}
570 	if (bbr->rc_in_persist) {
571 		/* We can't start any timer in persists */
572 		return (bbr_get_persists_timer_val(tp, bbr));
573 	}
574 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
575 	if ((rsm == NULL) ||
576 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
577 	    (tp->t_state < TCPS_ESTABLISHED)) {
578 		/* Nothing on the send map */
579 activate_rxt:
580 		if (SEQ_LT(tp->snd_una, tp->snd_max) ||
581 		    sbavail(&tptosocket(tp)->so_snd)) {
582 			uint64_t tov;
583 
584 			time_since_sent = 0;
585 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
586 			if (rsm) {
587 				idx = rsm->r_rtr_cnt - 1;
588 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
589 					tstmp_touse = rsm->r_tim_lastsent[idx];
590 				else
591 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
592 				if (TSTMP_GT(tstmp_touse, cts))
593 				    time_since_sent = cts - tstmp_touse;
594 			}
595 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
596 			if (tp->t_srtt == 0)
597 				tov = BBR_INITIAL_RTO;
598 			else
599 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
600 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
601 			if (tp->t_rxtshift)
602 				tov *= tcp_backoff[tp->t_rxtshift];
603 			if (tov > time_since_sent)
604 				tov -= time_since_sent;
605 			else
606 				tov = bbr->r_ctl.rc_min_to;
607 			TCPT_RANGESET_NOSLOP(to, tov,
608 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
609 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
610 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
611 			return (to);
612 		}
613 		return (0);
614 	}
615 	if (rsm->r_flags & BBR_ACKED) {
616 		rsm = bbr_find_lowest_rsm(bbr);
617 		if (rsm == NULL) {
618 			/* No lowest? */
619 			goto activate_rxt;
620 		}
621 	}
622 	/* Convert from ms to usecs */
623 	if (rsm->r_flags & BBR_SACK_PASSED) {
624 		if ((tp->t_flags & TF_SENTFIN) &&
625 		    ((tp->snd_max - tp->snd_una) == 1) &&
626 		    (rsm->r_flags & BBR_HAS_FIN)) {
627 			/*
628 			 * We don't start a bbr rack timer if all we have is
629 			 * a FIN outstanding.
630 			 */
631 			goto activate_rxt;
632 		}
633 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
634 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
635 		idx = rsm->r_rtr_cnt - 1;
636 		exp = rsm->r_tim_lastsent[idx] + thresh;
637 		if (SEQ_GEQ(exp, cts)) {
638 			to = exp - cts;
639 			if (to < bbr->r_ctl.rc_min_to) {
640 				to = bbr->r_ctl.rc_min_to;
641 			}
642 		} else {
643 			to = bbr->r_ctl.rc_min_to;
644 		}
645 	} else {
646 		/* Ok we need to do a TLP not RACK */
647 		if (bbr->rc_tlp_in_progress != 0) {
648 			/*
649 			 * The previous send was a TLP.
650 			 */
651 			goto activate_rxt;
652 		}
653 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
654 		if (rsm == NULL) {
655 			/* We found no rsm to TLP with. */
656 			goto activate_rxt;
657 		}
658 		if (rsm->r_flags & BBR_HAS_FIN) {
659 			/* If its a FIN we don't do TLP */
660 			rsm = NULL;
661 			goto activate_rxt;
662 		}
663 		time_since_sent = 0;
664 		idx = rsm->r_rtr_cnt - 1;
665 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
666 			tstmp_touse = rsm->r_tim_lastsent[idx];
667 		else
668 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
669 		if (TSTMP_GT(tstmp_touse, cts))
670 		    time_since_sent = cts - tstmp_touse;
671 		is_tlp_timer = 1;
672 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
673 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
674 		if (thresh > time_since_sent)
675 			to = thresh - time_since_sent;
676 		else
677 			to = bbr->r_ctl.rc_min_to;
678 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
679 			/*
680 			 * If the TLP time works out to larger than the max
681 			 * RTO lets not do TLP.. just RTO.
682 			 */
683 			goto activate_rxt;
684 		}
685 		if ((bbr->rc_tlp_rtx_out == 1) &&
686 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
687 			/*
688 			 * Second retransmit of the same TLP
689 			 * lets not.
690 			 */
691 			bbr->rc_tlp_rtx_out = 0;
692 			goto activate_rxt;
693 		}
694 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
695 			/*
696 			 * The tail is no longer the last one I did a probe
697 			 * on
698 			 */
699 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
700 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
701 		}
702 	}
703 	if (is_tlp_timer == 0) {
704 		BBR_STAT_INC(bbr_to_arm_rack);
705 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
706 	} else {
707 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
708 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
709 			/*
710 			 * We have exceeded how many times we can retran the
711 			 * current TLP timer, switch to the RTO timer.
712 			 */
713 			goto activate_rxt;
714 		} else {
715 			BBR_STAT_INC(bbr_to_arm_tlp);
716 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
717 		}
718 	}
719 	return (to);
720 }
721 
722 static inline int32_t
723 bbr_minseg(struct tcp_bbr *bbr)
724 {
725 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
726 }
727 
728 static void
729 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
730 {
731 	struct inpcb *inp = tptoinpcb(tp);
732 	struct hpts_diag diag;
733 	uint32_t delayed_ack = 0;
734 	uint32_t left = 0;
735 	uint32_t hpts_timeout;
736 	uint8_t stopped;
737 	int32_t delay_calc = 0;
738 	uint32_t prev_delay = 0;
739 
740 	if (tcp_in_hpts(tp)) {
741 		/* A previous call is already set up */
742 		return;
743 	}
744 	if ((tp->t_state == TCPS_CLOSED) ||
745 	    (tp->t_state == TCPS_LISTEN)) {
746 		return;
747 	}
748 	stopped = bbr->rc_tmr_stopped;
749 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
750 		left = bbr->r_ctl.rc_timer_exp - cts;
751 	}
752 	bbr->r_ctl.rc_hpts_flags = 0;
753 	bbr->r_ctl.rc_timer_exp = 0;
754 	prev_delay = bbr->r_ctl.rc_last_delay_val;
755 	if (bbr->r_ctl.rc_last_delay_val &&
756 	    (slot == 0)) {
757 		/*
758 		 * If a previous pacer delay was in place we
759 		 * are not coming from the output side (where
760 		 * we calculate a delay, more likely a timer).
761 		 */
762 		slot = bbr->r_ctl.rc_last_delay_val;
763 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
764 			/* Compensate for time passed  */
765 			delay_calc = cts - bbr->rc_pacer_started;
766 			if (delay_calc <= slot)
767 				slot -= delay_calc;
768 		}
769 	}
770 	/* Do we have early to make up for by pushing out the pacing time? */
771 	if (bbr->r_agg_early_set) {
772 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
773 		slot += bbr->r_ctl.rc_agg_early;
774 		bbr->r_ctl.rc_agg_early = 0;
775 		bbr->r_agg_early_set = 0;
776 	}
777 	/* Are we running a total debt that needs to be compensated for? */
778 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
779 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
780 			/* We nuke the delay */
781 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
782 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
783 		} else {
784 			/* We nuke some of the delay, put in a minimal 100usecs  */
785 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
786 			bbr->r_ctl.rc_last_delay_val = slot = 100;
787 		}
788 	}
789 	bbr->r_ctl.rc_last_delay_val = slot;
790 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
791 	if (tp->t_flags & TF_DELACK) {
792 		if (bbr->rc_in_persist == 0) {
793 			delayed_ack = bbr_delack_time;
794 		} else {
795 			/*
796 			 * We are in persists and have
797 			 * gotten a new data element.
798 			 */
799 			if (hpts_timeout > bbr_delack_time) {
800 				/*
801 				 * Lets make the persists timer (which acks)
802 				 * be the smaller of hpts_timeout and bbr_delack_time.
803 				 */
804 				hpts_timeout = bbr_delack_time;
805 			}
806 		}
807 	}
808 	if (delayed_ack &&
809 	    ((hpts_timeout == 0) ||
810 	     (delayed_ack < hpts_timeout))) {
811 		/* We need a Delayed ack timer */
812 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
813 		hpts_timeout = delayed_ack;
814 	}
815 	if (slot) {
816 		/* Mark that we have a pacing timer up */
817 		BBR_STAT_INC(bbr_paced_segments);
818 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
819 	}
820 	/*
821 	 * If no timers are going to run and we will fall off thfe hptsi
822 	 * wheel, we resort to a keep-alive timer if its configured.
823 	 */
824 	if ((hpts_timeout == 0) &&
825 	    (slot == 0)) {
826 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
827 		    (tp->t_state <= TCPS_CLOSING)) {
828 			/*
829 			 * Ok we have no timer (persists, rack, tlp, rxt  or
830 			 * del-ack), we don't have segments being paced. So
831 			 * all that is left is the keepalive timer.
832 			 */
833 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
834 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
835 			} else {
836 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
837 			}
838 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
839 		}
840 	}
841 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
842 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
843 		/*
844 		 * RACK, TLP, persists and RXT timers all are restartable
845 		 * based on actions input .. i.e we received a packet (ack
846 		 * or sack) and that changes things (rw, or snd_una etc).
847 		 * Thus we can restart them with a new value. For
848 		 * keep-alive, delayed_ack we keep track of what was left
849 		 * and restart the timer with a smaller value.
850 		 */
851 		if (left < hpts_timeout)
852 			hpts_timeout = left;
853 	}
854 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
855 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
856 		/*
857 		 * If configured to do so, and the timer is either
858 		 * the TLP or RXT timer, we need to increase the timeout
859 		 * by the pacing time. Consider the bottleneck at my
860 		 * machine as an example, we are sending something
861 		 * to start a TLP on. The last packet won't be emitted
862 		 * fully until the pacing time (the bottleneck will hold
863 		 * the data in place). Once the packet is emitted that
864 		 * is when we want to start waiting for the TLP. This
865 		 * is most evident with hardware pacing (where the nic
866 		 * is holding the packet(s) before emitting). But it
867 		 * can also show up in the network so we do it for all
868 		 * cases. Technically we would take off one packet from
869 		 * this extra delay but this is easier and being more
870 		 * conservative is probably better.
871 		 */
872 		hpts_timeout += slot;
873 	}
874 	if (hpts_timeout) {
875 		/*
876 		 * Hack alert for now we can't time-out over 2147 seconds (a
877 		 * bit more than 35min)
878 		 */
879 		if (hpts_timeout > 0x7ffffffe)
880 			hpts_timeout = 0x7ffffffe;
881 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
882 	} else
883 		bbr->r_ctl.rc_timer_exp = 0;
884 	if ((slot) &&
885 	    (bbr->rc_use_google ||
886 	     bbr->output_error_seen ||
887 	     (slot <= hpts_timeout))  ) {
888 		/*
889 		 * Tell LRO that it can queue packets while
890 		 * we pace.
891 		 */
892 		bbr->rc_tp->t_flags2 |= TF2_MBUF_QUEUE_READY;
893 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
894 		    (bbr->rc_cwnd_limited == 0)) {
895 			/*
896 			 * If we are not cwnd limited and we
897 			 * are running a rack timer we put on
898 			 * the do not disturbe even for sack.
899 			 */
900 			tp->t_flags2 |= TF2_DONT_SACK_QUEUE;
901 		} else
902 			tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
903 		bbr->rc_pacer_started = cts;
904 
905 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(slot),
906 					   __LINE__, &diag);
907 		bbr->rc_timer_first = 0;
908 		bbr->bbr_timer_src = frm;
909 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
910 		bbr_log_hpts_diag(bbr, cts, &diag);
911 	} else if (hpts_timeout) {
912 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(hpts_timeout),
913 					   __LINE__, &diag);
914 		/*
915 		 * We add the flag here as well if the slot is set,
916 		 * since hpts will call in to clear the queue first before
917 		 * calling the output routine (which does our timers).
918 		 * We don't want to set the flag if its just a timer
919 		 * else the arrival of data might (that causes us
920 		 * to send more) might get delayed. Imagine being
921 		 * on a keep-alive timer and a request comes in for
922 		 * more data.
923 		 */
924 		if (slot)
925 			bbr->rc_pacer_started = cts;
926 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
927 		    (bbr->rc_cwnd_limited == 0)) {
928 			/*
929 			 * For a rack timer, don't wake us even
930 			 * if a sack arrives as long as we are
931 			 * not cwnd limited.
932 			 */
933 			tp->t_flags2 |= (TF2_MBUF_QUEUE_READY |
934 			    TF2_DONT_SACK_QUEUE);
935 		} else {
936 			/* All other timers wake us up */
937 			tp->t_flags2 &= ~(TF2_MBUF_QUEUE_READY |
938 			    TF2_DONT_SACK_QUEUE);
939 		}
940 		bbr->bbr_timer_src = frm;
941 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
942 		bbr_log_hpts_diag(bbr, cts, &diag);
943 		bbr->rc_timer_first = 1;
944 	}
945 	bbr->rc_tmr_stopped = 0;
946 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
947 }
948 
949 static void
950 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
951 {
952 	/*
953 	 * We received an ack, and then did not call send or were bounced
954 	 * out due to the hpts was running. Now a timer is up as well, is it
955 	 * the right timer?
956 	 */
957 	struct inpcb *inp;
958 	struct bbr_sendmap *rsm;
959 	uint32_t hpts_timeout;
960 	int tmr_up;
961 
962 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
963 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
964 		return;
965 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
966 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
967 	    (tmr_up == PACE_TMR_RXT)) {
968 		/* Should be an RXT */
969 		return;
970 	}
971 	inp = bbr->rc_inp;
972 	if (rsm == NULL) {
973 		/* Nothing outstanding? */
974 		if (tp->t_flags & TF_DELACK) {
975 			if (tmr_up == PACE_TMR_DELACK)
976 				/*
977 				 * We are supposed to have delayed ack up
978 				 * and we do
979 				 */
980 				return;
981 		} else if (sbavail(&inp->inp_socket->so_snd) &&
982 		    (tmr_up == PACE_TMR_RXT)) {
983 			/*
984 			 * if we hit enobufs then we would expect the
985 			 * possibility of nothing outstanding and the RXT up
986 			 * (and the hptsi timer).
987 			 */
988 			return;
989 		} else if (((V_tcp_always_keepalive ||
990 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
991 			    (tp->t_state <= TCPS_CLOSING)) &&
992 			    (tmr_up == PACE_TMR_KEEP) &&
993 		    (tp->snd_max == tp->snd_una)) {
994 			/* We should have keep alive up and we do */
995 			return;
996 		}
997 	}
998 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
999 		if ((tp->t_flags & TF_SENTFIN) &&
1000 		    ((tp->snd_max - tp->snd_una) == 1) &&
1001 		    (rsm->r_flags & BBR_HAS_FIN)) {
1002 			/* needs to be a RXT */
1003 			if (tmr_up == PACE_TMR_RXT)
1004 				return;
1005 			else
1006 				goto wrong_timer;
1007 		} else if (tmr_up == PACE_TMR_RACK)
1008 			return;
1009 		else
1010 			goto wrong_timer;
1011 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1012 		/* Rack timer has priority if we have data out */
1013 		return;
1014 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1015 		    ((tmr_up == PACE_TMR_TLP) ||
1016 	    (tmr_up == PACE_TMR_RXT))) {
1017 		/*
1018 		 * Either a TLP or RXT is fine if no sack-passed is in place
1019 		 * and data is outstanding.
1020 		 */
1021 		return;
1022 	} else if (tmr_up == PACE_TMR_DELACK) {
1023 		/*
1024 		 * If the delayed ack was going to go off before the
1025 		 * rtx/tlp/rack timer were going to expire, then that would
1026 		 * be the timer in control. Note we don't check the time
1027 		 * here trusting the code is correct.
1028 		 */
1029 		return;
1030 	}
1031 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1032 	    ((tmr_up == PACE_TMR_RXT) ||
1033 	     (tmr_up == PACE_TMR_TLP) ||
1034 	     (tmr_up == PACE_TMR_RACK))) {
1035 		/*
1036 		 * We have outstanding data and
1037 		 * we *do* have a RACK, TLP or RXT
1038 		 * timer running. We won't restart
1039 		 * anything here since thats probably ok we
1040 		 * will get called with some timer here shortly.
1041 		 */
1042 		return;
1043 	}
1044 	/*
1045 	 * Ok the timer originally started is not what we want now. We will
1046 	 * force the hpts to be stopped if any, and restart with the slot
1047 	 * set to what was in the saved slot.
1048 	 */
1049 wrong_timer:
1050 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1051 		if (tcp_in_hpts(tp))
1052 			tcp_hpts_remove(tp);
1053 		bbr_timer_cancel(bbr, __LINE__, cts);
1054 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1055 		    0);
1056 	} else {
1057 		/*
1058 		 * Output is hptsi so we just need to switch the type of
1059 		 * timer. We don't bother with keep-alive, since when we
1060 		 * jump through the output, it will start the keep-alive if
1061 		 * nothing is sent.
1062 		 *
1063 		 * We only need a delayed-ack added and or the hpts_timeout.
1064 		 */
1065 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1066 		if (tp->t_flags & TF_DELACK) {
1067 			if (hpts_timeout == 0) {
1068 				hpts_timeout = bbr_delack_time;
1069 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1070 			}
1071 			else if (hpts_timeout > bbr_delack_time) {
1072 				hpts_timeout = bbr_delack_time;
1073 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1074 			}
1075 		}
1076 		if (hpts_timeout) {
1077 			if (hpts_timeout > 0x7ffffffe)
1078 				hpts_timeout = 0x7ffffffe;
1079 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1080 		}
1081 	}
1082 }
1083 
1084 int32_t bbr_clear_lost = 0;
1085 
1086 /*
1087  * Considers the two time values now (cts) and earlier.
1088  * If cts is smaller than earlier, we could have
1089  * had a sequence wrap (our counter wraps every
1090  * 70 min or so) or it could be just clock skew
1091  * getting us two different time values. Clock skew
1092  * will show up within 10ms or so. So in such
1093  * a case (where cts is behind earlier time by
1094  * less than 10ms) we return 0. Otherwise we
1095  * return the true difference between them.
1096  */
1097 static inline uint32_t
1098 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1099 	/*
1100 	 * Given two timestamps, the current time stamp cts, and some other
1101 	 * time-stamp taken in theory earlier return the difference. The
1102 	 * trick is here sometimes locking will get the other timestamp
1103 	 * after the cts. If this occurs we need to return 0.
1104 	 */
1105 	if (TSTMP_GEQ(cts, earlier_time))
1106 		return (cts - earlier_time);
1107 	/*
1108 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1109 	 * If its more than 10ms difference then we had a time wrap. Else
1110 	 * its just the normal locking foo. I wonder if we should not go to
1111 	 * 64bit TS and get rid of this issue.
1112 	 */
1113 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1114 		return (0);
1115 	/*
1116 	 * Ok the time must have wrapped. So we need to answer a large
1117 	 * amount of time, which the normal subtraction should do.
1118 	 */
1119 	return (cts - earlier_time);
1120 }
1121 
1122 static int
1123 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1124 {
1125 	uint32_t stat;
1126 	int32_t error;
1127 
1128 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1129 	if (error || req->newptr == NULL)
1130 		return error;
1131 
1132 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1133 	if (error)
1134 		return (error);
1135 	if (stat == 1) {
1136 #ifdef BBR_INVARIANTS
1137 		printf("Clearing BBR lost counters\n");
1138 #endif
1139 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1140 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1141 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1142 	} else if (stat == 2) {
1143 #ifdef BBR_INVARIANTS
1144 		printf("Clearing BBR option counters\n");
1145 #endif
1146 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1147 	} else if (stat == 3) {
1148 #ifdef BBR_INVARIANTS
1149 		printf("Clearing BBR stats counters\n");
1150 #endif
1151 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1152 	} else if (stat == 4) {
1153 #ifdef BBR_INVARIANTS
1154 		printf("Clearing BBR out-size counters\n");
1155 #endif
1156 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1157 	}
1158 	bbr_clear_lost = 0;
1159 	return (0);
1160 }
1161 
1162 static void
1163 bbr_init_sysctls(void)
1164 {
1165 	struct sysctl_oid *bbr_probertt;
1166 	struct sysctl_oid *bbr_hptsi;
1167 	struct sysctl_oid *bbr_measure;
1168 	struct sysctl_oid *bbr_cwnd;
1169 	struct sysctl_oid *bbr_timeout;
1170 	struct sysctl_oid *bbr_states;
1171 	struct sysctl_oid *bbr_startup;
1172 	struct sysctl_oid *bbr_policer;
1173 
1174 	/* Probe rtt controls */
1175 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1176 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1177 	    OID_AUTO,
1178 	    "probertt",
1179 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1180 	    "");
1181 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1182 	    SYSCTL_CHILDREN(bbr_probertt),
1183 	    OID_AUTO, "gain", CTLFLAG_RW,
1184 	    &bbr_rttprobe_gain, 192,
1185 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1186 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1187 	    SYSCTL_CHILDREN(bbr_probertt),
1188 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1189 	    &bbr_rtt_probe_cwndtarg, 4,
1190 	    "How many mss's are outstanding during probe-rtt");
1191 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1192 	    SYSCTL_CHILDREN(bbr_probertt),
1193 	    OID_AUTO, "int", CTLFLAG_RW,
1194 	    &bbr_rtt_probe_limit, 4000000,
1195 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1196 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1197 	    SYSCTL_CHILDREN(bbr_probertt),
1198 	    OID_AUTO, "mintime", CTLFLAG_RW,
1199 	    &bbr_rtt_probe_time, 200000,
1200 	    "How many microseconds in probe-rtt");
1201 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1202 	    SYSCTL_CHILDREN(bbr_probertt),
1203 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1204 	    &bbr_filter_len_sec, 6,
1205 	    "How long in seconds does the rttProp filter run?");
1206 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1207 	    SYSCTL_CHILDREN(bbr_probertt),
1208 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1209 	    &bbr_drain_rtt, BBR_SRTT,
1210 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1211 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1212 	    SYSCTL_CHILDREN(bbr_probertt),
1213 	    OID_AUTO, "can_force", CTLFLAG_RW,
1214 	    &bbr_can_force_probertt, 0,
1215 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1216 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1217 	    SYSCTL_CHILDREN(bbr_probertt),
1218 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1219 	    &bbr_probertt_sets_rtt, 0,
1220 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1221 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1222 	    SYSCTL_CHILDREN(bbr_probertt),
1223 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1224 	    &bbr_can_adjust_probertt, 1,
1225 	    "Can we dynamically adjust the probe-rtt limits and times?");
1226 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1227 	    SYSCTL_CHILDREN(bbr_probertt),
1228 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1229 	    &bbr_is_ratio, 0,
1230 	    "is the limit to filter a ratio?");
1231 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1232 	    SYSCTL_CHILDREN(bbr_probertt),
1233 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1234 	    &bbr_prtt_slam_cwnd, 0,
1235 	    "Should we set/recover cwnd?");
1236 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1237 	    SYSCTL_CHILDREN(bbr_probertt),
1238 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1239 	    &bbr_can_use_ts_for_rtt, 1,
1240 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1241 
1242 	/* Pacing controls */
1243 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1244 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1245 	    OID_AUTO,
1246 	    "pacing",
1247 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1248 	    "");
1249 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1250 	    SYSCTL_CHILDREN(bbr_hptsi),
1251 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1252 	    &bbr_allow_hdwr_pacing, 1,
1253 	    "Do we allow hardware pacing?");
1254 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1255 	    SYSCTL_CHILDREN(bbr_hptsi),
1256 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1257 	    &bbr_hardware_pacing_limit, 4000,
1258 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1259 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1260 	    SYSCTL_CHILDREN(bbr_hptsi),
1261 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1262 	    &bbr_hdwr_pace_adjust, 2,
1263 	    "Multiplier to calculated tso size?");
1264 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1265 	    SYSCTL_CHILDREN(bbr_hptsi),
1266 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1267 	    &bbr_hdwr_pace_floor, 1,
1268 	    "Do we invoke the hardware pacing floor?");
1269 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1270 	    SYSCTL_CHILDREN(bbr_hptsi),
1271 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1272 	    &bbr_hdwr_pacing_delay_cnt, 10,
1273 	    "How many packets must be sent after hdwr pacing is enabled");
1274 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1275 	    SYSCTL_CHILDREN(bbr_hptsi),
1276 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1277 	    &bbr_cross_over, 3000000,
1278 	    "What is the point where we cross over to linux like TSO size set");
1279 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1280 	    SYSCTL_CHILDREN(bbr_hptsi),
1281 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1282 	    &bbr_hptsi_segments_delay_tar, 7000,
1283 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1284 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1285 	    SYSCTL_CHILDREN(bbr_hptsi),
1286 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1287 	    &bbr_include_enet_oh, 0,
1288 	    "Do we include the ethernet overhead in calculating pacing delay?");
1289 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1290 	    SYSCTL_CHILDREN(bbr_hptsi),
1291 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1292 	    &bbr_include_ip_oh, 1,
1293 	    "Do we include the IP overhead in calculating pacing delay?");
1294 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1295 	    SYSCTL_CHILDREN(bbr_hptsi),
1296 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1297 	    &bbr_include_tcp_oh, 0,
1298 	    "Do we include the TCP overhead in calculating pacing delay?");
1299 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1300 	    SYSCTL_CHILDREN(bbr_hptsi),
1301 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1302 	    &bbr_google_discount, 10,
1303 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1304 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1305 	    SYSCTL_CHILDREN(bbr_hptsi),
1306 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1307 	    &bbr_all_get_min, 0,
1308 	    "If you are less than a MSS do you just get the min?");
1309 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1310 	    SYSCTL_CHILDREN(bbr_hptsi),
1311 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1312 	    &bbr_hptsi_bytes_min, 1460,
1313 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1314 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1315 	    SYSCTL_CHILDREN(bbr_hptsi),
1316 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1317 	    &bbr_hptsi_segments_max, 6,
1318 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1319 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1320 	    SYSCTL_CHILDREN(bbr_hptsi),
1321 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1322 	    &bbr_hptsi_segments_floor, 1,
1323 	    "Minimum TSO size we will fall too in segments");
1324 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1325 	    SYSCTL_CHILDREN(bbr_hptsi),
1326 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1327 	    &bbr_hptsi_utter_max, 0,
1328 	    "The absolute maximum that any pacing (outside of hardware) can be");
1329 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1330 	    SYSCTL_CHILDREN(bbr_hptsi),
1331 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1332 	    &bbr_hptsi_per_second, 100,
1333 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1334 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1335 	    SYSCTL_CHILDREN(bbr_hptsi),
1336 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1337 	    &bbr_hptsi_max_mul, 1,
1338 	    "The multiplier for pace len max");
1339 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1340 	    SYSCTL_CHILDREN(bbr_hptsi),
1341 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1342 	    &bbr_hptsi_max_div, 2,
1343 	    "The divisor for pace len max");
1344 	/* Measurement controls */
1345 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1346 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1347 	    OID_AUTO,
1348 	    "measure",
1349 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1350 	    "Measurement controls");
1351 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1352 	    SYSCTL_CHILDREN(bbr_measure),
1353 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1354 	    &bbr_initial_bw_bps, 62500,
1355 	    "Minimum initial b/w in bytes per second");
1356 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1357 	    SYSCTL_CHILDREN(bbr_measure),
1358 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1359 	    &bbr_sack_not_required, 0,
1360 	    "Do we allow bbr to run on connections not supporting SACK?");
1361 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1362 	    SYSCTL_CHILDREN(bbr_measure),
1363 	    OID_AUTO, "use_google", CTLFLAG_RW,
1364 	    &bbr_use_google_algo, 0,
1365 	    "Use has close to google V1.0 has possible?");
1366 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1367 	    SYSCTL_CHILDREN(bbr_measure),
1368 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1369 	    &bbr_ts_limiting, 1,
1370 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1371 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1372 	    SYSCTL_CHILDREN(bbr_measure),
1373 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1374 	    &bbr_ts_can_raise, 0,
1375 	    "Can we raise the b/w via timestamp b/w calculation?");
1376 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1377 	    SYSCTL_CHILDREN(bbr_measure),
1378 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1379 	    &bbr_min_usec_delta, 20000,
1380 	    "How long in usec between ts of our sends in ts validation code?");
1381 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1382 	    SYSCTL_CHILDREN(bbr_measure),
1383 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1384 	    &bbr_min_peer_delta, 20,
1385 	    "What min numerical value should be between the peer deltas?");
1386 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1387 	    SYSCTL_CHILDREN(bbr_measure),
1388 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1389 	    &bbr_delta_percent, 150,
1390 	    "What percentage (150 = 15.0) do we allow variance for?");
1391 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1392 	    SYSCTL_CHILDREN(bbr_measure),
1393 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1394 	    &bbr_min_measurements_req, 1,
1395 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1396 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1397 	    SYSCTL_CHILDREN(bbr_measure),
1398 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1399 	    &bbr_no_pacing_until, 4,
1400 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1401 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1402 	    SYSCTL_CHILDREN(bbr_measure),
1403 	    OID_AUTO, "quanta", CTLFLAG_RW,
1404 	    &bbr_quanta, 2,
1405 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1406 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1407 	    SYSCTL_CHILDREN(bbr_measure),
1408 	    OID_AUTO, "noretran", CTLFLAG_RW,
1409 	    &bbr_no_retran, 0,
1410 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1411 	/* State controls */
1412 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1413 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1414 	    OID_AUTO,
1415 	    "states",
1416 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1417 	    "State controls");
1418 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1419 	    SYSCTL_CHILDREN(bbr_states),
1420 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1421 	    &bbr_uses_idle_restart, 0,
1422 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1423 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1424 	    SYSCTL_CHILDREN(bbr_states),
1425 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1426 	    &bbr_idle_restart_threshold, 100000,
1427 	    "How long must we be idle before we restart??");
1428 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1429 	    SYSCTL_CHILDREN(bbr_states),
1430 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1431 	    &bbr_state_is_pkt_epoch, 0,
1432 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1433 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1434 	    SYSCTL_CHILDREN(bbr_states),
1435 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1436 	    &bbr_rtt_gain_thresh, 0,
1437 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1438 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1439 	    SYSCTL_CHILDREN(bbr_states),
1440 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1441 	    &bbr_drain_floor, 88,
1442 	    "What is the lowest we can drain (pg) too?");
1443 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1444 	    SYSCTL_CHILDREN(bbr_states),
1445 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1446 	    &bbr_state_drain_2_tar, 1,
1447 	    "Do we drain to target in drain substate?");
1448 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1449 	    SYSCTL_CHILDREN(bbr_states),
1450 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1451 	    &bbr_gain_to_target, 1,
1452 	    "Does probe bw gain to target??");
1453 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1454 	    SYSCTL_CHILDREN(bbr_states),
1455 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1456 	    &bbr_gain_gets_extra_too, 1,
1457 	    "Does probe bw gain get the extra time too?");
1458 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1459 	    SYSCTL_CHILDREN(bbr_states),
1460 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1461 	    &bbr_drain_drop_div, 5,
1462 	    "Long drain drop divider?");
1463 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1464 	    SYSCTL_CHILDREN(bbr_states),
1465 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1466 	    &bbr_drain_drop_mul, 4,
1467 	    "Long drain drop multiplier?");
1468 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1469 	    SYSCTL_CHILDREN(bbr_states),
1470 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1471 	    &bbr_rand_ot, 50,
1472 	    "Random discount of the ot?");
1473 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1474 	    SYSCTL_CHILDREN(bbr_states),
1475 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1476 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1477 	    "How many packet-epochs does the b/w delivery rate last?");
1478 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1479 	    SYSCTL_CHILDREN(bbr_states),
1480 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1481 	    &bbr_sub_drain_app_limit, 0,
1482 	    "Does our sub-state drain invoke app limited if its long?");
1483 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1484 	    SYSCTL_CHILDREN(bbr_states),
1485 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1486 	    &bbr_sub_drain_slam_cwnd, 0,
1487 	    "Should we set/recover cwnd for sub-state drain?");
1488 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1489 	    SYSCTL_CHILDREN(bbr_states),
1490 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1491 	    &bbr_slam_cwnd_in_main_drain, 0,
1492 	    "Should we set/recover cwnd for main-state drain?");
1493 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1494 	    SYSCTL_CHILDREN(bbr_states),
1495 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1496 	    &google_allow_early_out, 1,
1497 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1498 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1499 	    SYSCTL_CHILDREN(bbr_states),
1500 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1501 	    &google_consider_lost, 1,
1502 	    "Should we have losses exit gain of probebw in google mode??");
1503 	/* Startup controls */
1504 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1505 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1506 	    OID_AUTO,
1507 	    "startup",
1508 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1509 	    "Startup controls");
1510 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1511 	    SYSCTL_CHILDREN(bbr_startup),
1512 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1513 	    &bbr_sends_full_iwnd, 1,
1514 	    "Do we not pace but burst out initial windows has our TSO size?");
1515 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1516 	    SYSCTL_CHILDREN(bbr_startup),
1517 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1518 	    &bbr_startup_loss_thresh, 2000,
1519 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1520 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1521 	    SYSCTL_CHILDREN(bbr_startup),
1522 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1523 	    &bbr_use_lower_gain_in_startup, 1,
1524 	    "Should we use a lower hptsi gain if we see loss in startup?");
1525 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1526 	    SYSCTL_CHILDREN(bbr_startup),
1527 	    OID_AUTO, "gain", CTLFLAG_RW,
1528 	    &bbr_start_exit, 25,
1529 	    "What gain percent do we need to see to stay in startup??");
1530 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1531 	    SYSCTL_CHILDREN(bbr_startup),
1532 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1533 	    &bbr_low_start_exit, 15,
1534 	    "What gain percent do we need to see to stay in the lower gain startup??");
1535 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1536 	    SYSCTL_CHILDREN(bbr_startup),
1537 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1538 	    &bbr_exit_startup_at_loss, 1,
1539 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1540 	/* CWND controls */
1541 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1542 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1543 	    OID_AUTO,
1544 	    "cwnd",
1545 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1546 	    "Cwnd controls");
1547 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1548 	    SYSCTL_CHILDREN(bbr_cwnd),
1549 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1550 	    &bbr_cwndtarget_rtt_touse, 0,
1551 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1552 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1553 	    SYSCTL_CHILDREN(bbr_cwnd),
1554 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1555 	    &bbr_cwnd_may_shrink, 0,
1556 	    "Can the cwnd shrink if it would grow to more than the target?");
1557 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1558 	    SYSCTL_CHILDREN(bbr_cwnd),
1559 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1560 	    &bbr_target_cwnd_mult_limit, 8,
1561 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1562 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1563 	    SYSCTL_CHILDREN(bbr_cwnd),
1564 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1565 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1566 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1567 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1568 	    SYSCTL_CHILDREN(bbr_cwnd),
1569 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1570 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1571 	    "What is the min cwnd (rttProp > 1ms)");
1572 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1573 	    SYSCTL_CHILDREN(bbr_cwnd),
1574 	    OID_AUTO, "initwin", CTLFLAG_RW,
1575 	    &bbr_def_init_win, 10,
1576 	    "What is the BBR initial window, if 0 use tcp version");
1577 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1578 	    SYSCTL_CHILDREN(bbr_cwnd),
1579 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1580 	    &bbr_do_red, 600,
1581 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1582 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1583 	    SYSCTL_CHILDREN(bbr_cwnd),
1584 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1585 	    &bbr_red_scale, 20000,
1586 	    "What RTT do we scale with?");
1587 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1588 	    SYSCTL_CHILDREN(bbr_cwnd),
1589 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1590 	    &bbr_red_growth_restrict, 1,
1591 	    "Do we restrict cwnd growth for whats in flight?");
1592 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1593 	    SYSCTL_CHILDREN(bbr_cwnd),
1594 	    OID_AUTO, "red_div", CTLFLAG_RW,
1595 	    &bbr_red_div, 2,
1596 	    "If we reduce whats the divisor?");
1597 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1598 	    SYSCTL_CHILDREN(bbr_cwnd),
1599 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1600 	    &bbr_red_mul, 1,
1601 	    "If we reduce whats the mulitiplier?");
1602 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1603 	    SYSCTL_CHILDREN(bbr_cwnd),
1604 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1605 	    &bbr_target_is_bbunit, 0,
1606 	    "Is the state target the pacing_gain or BBR_UNIT?");
1607 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1608 	    SYSCTL_CHILDREN(bbr_cwnd),
1609 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1610 	    &bbr_drop_limit, 0,
1611 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1612 
1613 	/* Timeout controls */
1614 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1615 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1616 	    OID_AUTO,
1617 	    "timeout",
1618 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1619 	    "Time out controls");
1620 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1621 	    SYSCTL_CHILDREN(bbr_timeout),
1622 	    OID_AUTO, "delack", CTLFLAG_RW,
1623 	    &bbr_delack_time, 100000,
1624 	    "BBR's delayed ack time");
1625 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1626 	    SYSCTL_CHILDREN(bbr_timeout),
1627 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1628 	    &bbr_tlp_type_to_use, 3,
1629 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1630 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1631 	    SYSCTL_CHILDREN(bbr_timeout),
1632 	    OID_AUTO, "persmin", CTLFLAG_RW,
1633 	    &bbr_persist_min, 250000,
1634 	    "What is the minimum time in microseconds between persists");
1635 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1636 	    SYSCTL_CHILDREN(bbr_timeout),
1637 	    OID_AUTO, "persmax", CTLFLAG_RW,
1638 	    &bbr_persist_max, 1000000,
1639 	    "What is the largest delay in microseconds between persists");
1640 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1641 	    SYSCTL_CHILDREN(bbr_timeout),
1642 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1643 	    &bbr_tlp_min, 10000,
1644 	    "TLP Min timeout in usecs");
1645 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1646 	    SYSCTL_CHILDREN(bbr_timeout),
1647 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1648 	    &bbr_delayed_ack_time, 200000,
1649 	    "TLP delayed ack compensation value");
1650 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1651 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1652 	    OID_AUTO, "minrto", CTLFLAG_RW,
1653 	    &bbr_rto_min_ms, 30,
1654 	    "Minimum RTO in ms");
1655 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1656 	    SYSCTL_CHILDREN(bbr_timeout),
1657 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1658 	    &bbr_rto_max_sec, 4,
1659 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1660 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1661 	    SYSCTL_CHILDREN(bbr_timeout),
1662 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1663 	    &bbr_tlp_max_resend, 2,
1664 	    "How many times does TLP retry a single segment or multiple with no ACK");
1665 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1666 	    SYSCTL_CHILDREN(bbr_timeout),
1667 	    OID_AUTO, "minto", CTLFLAG_RW,
1668 	    &bbr_min_to, 1000,
1669 	    "Minimum rack timeout in useconds");
1670 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1671 	    SYSCTL_CHILDREN(bbr_timeout),
1672 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1673 	    &bbr_pkt_delay, 1000,
1674 	    "Extra RACK time (in useconds) besides reordering thresh");
1675 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1676 	    SYSCTL_CHILDREN(bbr_timeout),
1677 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1678 	    &bbr_incr_timers, 1,
1679 	    "Increase the RXT/TLP timer by the pacing time used?");
1680 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1681 	    SYSCTL_CHILDREN(bbr_timeout),
1682 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1683 	    &bbr_marks_rxt_sack_passed, 0,
1684 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1685 	/* Policer controls */
1686 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1687 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1688 	    OID_AUTO,
1689 	    "policer",
1690 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1691 	    "Policer controls");
1692 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1693 	    SYSCTL_CHILDREN(bbr_policer),
1694 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1695 	    &bbr_policer_detection_enabled, 1,
1696 	    "Is policer detection enabled??");
1697 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1698 	    SYSCTL_CHILDREN(bbr_policer),
1699 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1700 	    &bbr_lt_intvl_min_rtts, 4,
1701 	    "Minimum number of PE's?");
1702 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1703 	    SYSCTL_CHILDREN(bbr_policer),
1704 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1705 	    &bbr_lt_bw_diff, (4000/8),
1706 	    "Minimal bw diff?");
1707 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1708 	    SYSCTL_CHILDREN(bbr_policer),
1709 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1710 	    &bbr_lt_bw_ratio, 8,
1711 	    "Minimal bw diff?");
1712 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1713 	    SYSCTL_CHILDREN(bbr_policer),
1714 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1715 	    &bbr_policer_call_from_rack_to, 0,
1716 	    "Do we call the policer detection code from a rack-timeout?");
1717 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1718 	    SYSCTL_CHILDREN(bbr_policer),
1719 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1720 	    &bbr_lt_intvl_fp, 0,
1721 	    "What packet epoch do we do false-positive detection at (0=no)?");
1722 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1723 	    SYSCTL_CHILDREN(bbr_policer),
1724 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1725 	    &bbr_lt_loss_thresh, 196,
1726 	    "Loss threshold 196 = 19.6%?");
1727 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1728 	    SYSCTL_CHILDREN(bbr_policer),
1729 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1730 	    &bbr_lt_fd_thresh, 100,
1731 	    "What percentage is the false detection threshold (150=15.0)?");
1732 	/* All the rest */
1733 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1734 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1735 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1736 	    &bbr_use_rack_resend_cheat, 0,
1737 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1738 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1739 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1740 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1741 	    &bbr_error_base_paceout, 10000,
1742 	    "When we hit an error what is the min to pace out in usec's?");
1743 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1744 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1745 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1746 	    &bbr_max_net_error_cnt, 10,
1747 	    "When we hit this many errors in a row, kill the session?");
1748 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1749 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1750 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1751 	    &bbr_ignore_data_after_close, 1,
1752 	    "Do we hold off sending a RST until all pending data is ack'd");
1753 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1754 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1755 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1756 	    &bbr_resends_use_tso, 0,
1757 	    "Can resends use TSO?");
1758 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1759 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1760 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1761 	    &bbr_sack_block_limit, 128,
1762 	    "When do we start ignoring small sack blocks");
1763 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1764 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1765 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1766 	    &bbr_verbose_logging, 0,
1767 	    "Should BBR black box logging be verbose");
1768 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1769 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1770 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1771 	    &bbr_reorder_thresh, 2,
1772 	    "What factor for rack will be added when seeing reordering (shift right)");
1773 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1774 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1775 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1776 	    &bbr_reorder_fade, 0,
1777 	    "Does reorder detection fade, if so how many ms (0 means never)");
1778 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1779 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1780 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1781 	    &bbr_tlp_thresh, 1,
1782 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1783 	/* Stats and counters */
1784 	/* The pacing counters for hdwr/software can't be in the array */
1785 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1786 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1787 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1788 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1789 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1790 	    &bbr_hdwr_pacing_enobuf,
1791 	    "Total number of enobufs for hardware paced flows");
1792 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1793 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1794 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1795 	    &bbr_nohdwr_pacing_enobuf,
1796 	    "Total number of enobufs for non-hardware paced flows");
1797 
1798 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1799 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1800 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1801 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1802 	    &bbr_flows_whdwr_pacing,
1803 	    "Total number of hardware paced flows");
1804 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1805 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1806 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1807 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1808 	    &bbr_flows_nohdwr_pacing,
1809 	    "Total number of software paced flows");
1810 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1811 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1812 	    OID_AUTO, "stats", CTLFLAG_RD,
1813 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1814 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1815 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1816 	    OID_AUTO, "opts", CTLFLAG_RD,
1817 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1818 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1819 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1820 	    OID_AUTO, "lost", CTLFLAG_RD,
1821 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1822 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1823 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1824 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1825 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1826 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1827 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1828 	    OID_AUTO, "statetime", CTLFLAG_RD,
1829 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1830 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1831 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1832 	    OID_AUTO, "outsize", CTLFLAG_RD,
1833 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1834 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1835 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1836 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1837 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1838 }
1839 
1840 static void
1841 bbr_counter_destroy(void)
1842 {
1843 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1844 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1845 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1846 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1847 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1848 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1849 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1850 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1851 	counter_u64_free(bbr_flows_whdwr_pacing);
1852 	counter_u64_free(bbr_flows_nohdwr_pacing);
1853 
1854 }
1855 
1856 static __inline void
1857 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1858 {
1859 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1860 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1861 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1862 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1863 	l->bw_inuse = bbr_get_bw(bbr);
1864 	l->inflight = ctf_flight_size(bbr->rc_tp,
1865 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1866 	l->applimited = bbr->r_ctl.r_app_limited_until;
1867 	l->delivered = bbr->r_ctl.rc_delivered;
1868 	l->timeStamp = cts;
1869 	l->lost = bbr->r_ctl.rc_lost;
1870 	l->bbr_state = bbr->rc_bbr_state;
1871 	l->bbr_substate = bbr_state_val(bbr);
1872 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1873 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1874 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1875 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1876 	l->inhpts = tcp_in_hpts(bbr->rc_tp);
1877 	l->use_lt_bw = bbr->rc_lt_use_bw;
1878 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1879 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1880 }
1881 
1882 static void
1883 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1884 {
1885 	if (tcp_bblogging_on(bbr->rc_tp)) {
1886 		union tcp_log_stackspecific log;
1887 
1888 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1889 		log.u_bbr.flex1 = 0;
1890 		log.u_bbr.flex2 = 0;
1891 		log.u_bbr.flex5 = 0;
1892 		log.u_bbr.flex3 = 0;
1893 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1894 		log.u_bbr.flex7 = reason;
1895 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1896 		log.u_bbr.flex8 = 0;
1897 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1898 		    &bbr->rc_inp->inp_socket->so_rcv,
1899 		    &bbr->rc_inp->inp_socket->so_snd,
1900 		    BBR_LOG_BW_RED_EV, 0,
1901 		    0, &log, false, &bbr->rc_tv);
1902 	}
1903 }
1904 
1905 static void
1906 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1907 {
1908 	if (tcp_bblogging_on(bbr->rc_tp)) {
1909 		union tcp_log_stackspecific log;
1910 
1911 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1912 		log.u_bbr.flex1 = seq;
1913 		log.u_bbr.flex2 = count;
1914 		log.u_bbr.flex8 = mode;
1915 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1916 		    &bbr->rc_inp->inp_socket->so_rcv,
1917 		    &bbr->rc_inp->inp_socket->so_snd,
1918 		    BBR_LOG_LOWGAIN, 0,
1919 		    0, &log, false, &bbr->rc_tv);
1920 	}
1921 }
1922 
1923 static void
1924 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1925     uint8_t reason, uint32_t p_maxseg, int len)
1926 {
1927 	if (tcp_bblogging_on(bbr->rc_tp)) {
1928 		union tcp_log_stackspecific log;
1929 
1930 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1931 		log.u_bbr.flex1 = p_maxseg;
1932 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1933 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1934 		log.u_bbr.flex4 = reason;
1935 		log.u_bbr.flex5 = bbr->rc_in_persist;
1936 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1937 		log.u_bbr.flex7 = p_maxseg;
1938 		log.u_bbr.flex8 = bbr->rc_in_persist;
1939 		log.u_bbr.pkts_out = 0;
1940 		log.u_bbr.applimited = len;
1941 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1942 		    &bbr->rc_inp->inp_socket->so_rcv,
1943 		    &bbr->rc_inp->inp_socket->so_snd,
1944 		    BBR_LOG_JUSTRET, 0,
1945 		    tlen, &log, false, &bbr->rc_tv);
1946 	}
1947 }
1948 
1949 static void
1950 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1951 {
1952 	if (tcp_bblogging_on(bbr->rc_tp)) {
1953 		union tcp_log_stackspecific log;
1954 
1955 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1956 		log.u_bbr.flex1 = seq;
1957 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1958 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1959 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1960 		    &bbr->rc_inp->inp_socket->so_rcv,
1961 		    &bbr->rc_inp->inp_socket->so_snd,
1962 		    BBR_LOG_ENTREC, 0,
1963 		    0, &log, false, &bbr->rc_tv);
1964 	}
1965 }
1966 
1967 static void
1968 bbr_log_msgsize_fail(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t len, uint32_t maxseg, uint32_t mtu, int32_t csum_flags, int32_t tso, uint32_t cts)
1969 {
1970 	if (tcp_bblogging_on(tp)) {
1971 		union tcp_log_stackspecific log;
1972 
1973 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1974 		log.u_bbr.flex1 = tso;
1975 		log.u_bbr.flex2 = maxseg;
1976 		log.u_bbr.flex3 = mtu;
1977 		log.u_bbr.flex4 = csum_flags;
1978 		TCP_LOG_EVENTP(tp, NULL,
1979 		    &bbr->rc_inp->inp_socket->so_rcv,
1980 		    &bbr->rc_inp->inp_socket->so_snd,
1981 		    BBR_LOG_MSGSIZE, 0,
1982 		    0, &log, false, &bbr->rc_tv);
1983 	}
1984 }
1985 
1986 static void
1987 bbr_log_flowend(struct tcp_bbr *bbr)
1988 {
1989 	if (tcp_bblogging_on(bbr->rc_tp)) {
1990 		union tcp_log_stackspecific log;
1991 		struct sockbuf *r, *s;
1992 		struct timeval tv;
1993 
1994 		if (bbr->rc_inp->inp_socket) {
1995 			r = &bbr->rc_inp->inp_socket->so_rcv;
1996 			s = &bbr->rc_inp->inp_socket->so_snd;
1997 		} else {
1998 			r = s = NULL;
1999 		}
2000 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2001 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2002 		    r, s,
2003 		    TCP_LOG_FLOWEND, 0,
2004 		    0, &log, false, &tv);
2005 	}
2006 }
2007 
2008 static void
2009 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2010     uint32_t lost, uint32_t del)
2011 {
2012 	if (tcp_bblogging_on(bbr->rc_tp)) {
2013 		union tcp_log_stackspecific log;
2014 
2015 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2016 		log.u_bbr.flex1 = lost;
2017 		log.u_bbr.flex2 = del;
2018 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2019 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2020 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2021 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2022 		log.u_bbr.flex7 = line;
2023 		log.u_bbr.flex8 = 0;
2024 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2025 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2026 		    &bbr->rc_inp->inp_socket->so_rcv,
2027 		    &bbr->rc_inp->inp_socket->so_snd,
2028 		    BBR_LOG_PKT_EPOCH, 0,
2029 		    0, &log, false, &bbr->rc_tv);
2030 	}
2031 }
2032 
2033 static void
2034 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2035 {
2036 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2037 		union tcp_log_stackspecific log;
2038 
2039 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2040 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2041 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2042 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2043 		log.u_bbr.flex7 = line;
2044 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2045 		    &bbr->rc_inp->inp_socket->so_rcv,
2046 		    &bbr->rc_inp->inp_socket->so_snd,
2047 		    BBR_LOG_TIME_EPOCH, 0,
2048 		    0, &log, false, &bbr->rc_tv);
2049 	}
2050 }
2051 
2052 static void
2053 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2054 {
2055 	if (tcp_bblogging_on(bbr->rc_tp)) {
2056 		union tcp_log_stackspecific log;
2057 
2058 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2059 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2060 		log.u_bbr.flex2 = new_tar;
2061 		log.u_bbr.flex3 = line;
2062 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2063 		log.u_bbr.flex5 = bbr_quanta;
2064 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2065 		log.u_bbr.flex7 = bbr->rc_last_options;
2066 		log.u_bbr.flex8 = meth;
2067 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2068 		    &bbr->rc_inp->inp_socket->so_rcv,
2069 		    &bbr->rc_inp->inp_socket->so_snd,
2070 		    BBR_LOG_STATE_TARGET, 0,
2071 		    0, &log, false, &bbr->rc_tv);
2072 	}
2073 
2074 }
2075 
2076 static void
2077 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2078 {
2079 	if (tcp_bblogging_on(bbr->rc_tp)) {
2080 		union tcp_log_stackspecific log;
2081 
2082 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2083 		log.u_bbr.flex1 = line;
2084 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2085 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2086 		if (bbr_state_is_pkt_epoch)
2087 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2088 		else
2089 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2090 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2091 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2092 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2093 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2094 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2095 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2096 		    &bbr->rc_inp->inp_socket->so_rcv,
2097 		    &bbr->rc_inp->inp_socket->so_snd,
2098 		    BBR_LOG_STATE, 0,
2099 		    0, &log, false, &bbr->rc_tv);
2100 	}
2101 }
2102 
2103 static void
2104 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2105 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2106 {
2107 	if (tcp_bblogging_on(bbr->rc_tp)) {
2108 		union tcp_log_stackspecific log;
2109 
2110 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2111 		log.u_bbr.flex1 = line;
2112 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2113 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2114 		log.u_bbr.flex4 = applied;
2115 		log.u_bbr.flex5 = rtt;
2116 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2117 		log.u_bbr.flex7 = cond;
2118 		log.u_bbr.flex8 = reas;
2119 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2120 		    &bbr->rc_inp->inp_socket->so_rcv,
2121 		    &bbr->rc_inp->inp_socket->so_snd,
2122 		    BBR_LOG_RTT_SHRINKS, 0,
2123 		    0, &log, false, &bbr->rc_tv);
2124 	}
2125 }
2126 
2127 static void
2128 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2129 {
2130 	if (tcp_bblogging_on(bbr->rc_tp)) {
2131 		union tcp_log_stackspecific log;
2132 
2133 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2134 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2135 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2136 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2137 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2138 		    &bbr->rc_inp->inp_socket->so_rcv,
2139 		    &bbr->rc_inp->inp_socket->so_snd,
2140 		    BBR_LOG_EXITREC, 0,
2141 		    0, &log, false, &bbr->rc_tv);
2142 	}
2143 }
2144 
2145 static void
2146 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2147     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2148 {
2149 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2150 		union tcp_log_stackspecific log;
2151 
2152 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2153 		log.u_bbr.flex1 = line;
2154 		log.u_bbr.flex2 = prev_acked;
2155 		log.u_bbr.flex3 = bytes_this_ack;
2156 		log.u_bbr.flex4 = chg;
2157 		log.u_bbr.flex5 = th_ack;
2158 		log.u_bbr.flex6 = target;
2159 		log.u_bbr.flex8 = meth;
2160 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2161 		    &bbr->rc_inp->inp_socket->so_rcv,
2162 		    &bbr->rc_inp->inp_socket->so_snd,
2163 		    BBR_LOG_CWND, 0,
2164 		    0, &log, false, &bbr->rc_tv);
2165 	}
2166 }
2167 
2168 static void
2169 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2170 {
2171 	/*
2172 	 * Log the rtt sample we are applying to the srtt algorithm in
2173 	 * useconds.
2174 	 */
2175 	if (tcp_bblogging_on(bbr->rc_tp)) {
2176 		union tcp_log_stackspecific log;
2177 
2178 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2179 		log.u_bbr.flex1 = rtt;
2180 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2181 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2182 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2183 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2184 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2185 		log.u_bbr.flex6 = tsin;
2186 		log.u_bbr.flex7 = 0;
2187 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2188 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2189 		    &bbr->rc_inp->inp_socket->so_rcv,
2190 		    &bbr->rc_inp->inp_socket->so_snd,
2191 		    TCP_LOG_RTT, 0,
2192 		    0, &log, false, &bbr->rc_tv);
2193 	}
2194 }
2195 
2196 static void
2197 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2198 {
2199 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2200 		union tcp_log_stackspecific log;
2201 
2202 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2203 		log.u_bbr.flex1 = time_in;
2204 		log.u_bbr.flex2 = line;
2205 		log.u_bbr.flex8 = enter_exit;
2206 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2207 		    &bbr->rc_inp->inp_socket->so_rcv,
2208 		    &bbr->rc_inp->inp_socket->so_snd,
2209 		    BBR_LOG_PERSIST, 0,
2210 		    0, &log, false, &bbr->rc_tv);
2211 	}
2212 }
2213 static void
2214 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2215 {
2216 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2217 		union tcp_log_stackspecific log;
2218 
2219 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2220 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2221 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2222 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2223 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2224 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2225 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2226 		    &bbr->rc_inp->inp_socket->so_rcv,
2227 		    &bbr->rc_inp->inp_socket->so_snd,
2228 		    BBR_LOG_ACKCLEAR, 0,
2229 		    0, &log, false, &bbr->rc_tv);
2230 	}
2231 }
2232 
2233 static void
2234 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2235 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2236 {
2237 	if (tcp_bblogging_on(bbr->rc_tp)) {
2238 		union tcp_log_stackspecific log;
2239 		struct timeval tv;
2240 
2241 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2242 		log.u_bbr.flex1 = nsegs;
2243 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2244 		if (m) {
2245 			struct timespec ts;
2246 
2247 			log.u_bbr.flex3 = m->m_flags;
2248 			if (m->m_flags & M_TSTMP) {
2249 				mbuf_tstmp2timespec(m, &ts);
2250 				tv.tv_sec = ts.tv_sec;
2251 				tv.tv_usec = ts.tv_nsec / 1000;
2252 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2253 			} else {
2254 				log.u_bbr.lt_epoch = 0;
2255 			}
2256 			if (m->m_flags & M_TSTMP_LRO) {
2257 				mbuf_tstmp2timeval(m, &tv);
2258 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2259 			} else {
2260 				/* No arrival timestamp */
2261 				log.u_bbr.flex5 = 0;
2262 			}
2263 
2264 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2265 		} else {
2266 			log.u_bbr.flex3 = 0;
2267 			log.u_bbr.flex5 = 0;
2268 			log.u_bbr.flex6 = 0;
2269 			log.u_bbr.pkts_out = 0;
2270 		}
2271 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2272 		log.u_bbr.flex7 = bbr->r_wanted_output;
2273 		log.u_bbr.flex8 = bbr->rc_in_persist;
2274 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2275 		    &bbr->rc_inp->inp_socket->so_rcv,
2276 		    &bbr->rc_inp->inp_socket->so_snd,
2277 		    TCP_LOG_IN, 0,
2278 		    tlen, &log, true, &bbr->rc_tv);
2279 	}
2280 }
2281 
2282 static void
2283 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2284 {
2285 	if (tcp_bblogging_on(bbr->rc_tp)) {
2286 		union tcp_log_stackspecific log;
2287 
2288 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2289 		log.u_bbr.flex1 = did_out;
2290 		log.u_bbr.flex2 = nxt_pkt;
2291 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2292 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2293 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2294 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2295 		log.u_bbr.flex7 = bbr->r_wanted_output;
2296 		log.u_bbr.flex8 = bbr->rc_in_persist;
2297 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2298 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2299 		    &bbr->rc_inp->inp_socket->so_rcv,
2300 		    &bbr->rc_inp->inp_socket->so_snd,
2301 		    BBR_LOG_DOSEG_DONE, 0,
2302 		    0, &log, true, &bbr->rc_tv);
2303 	}
2304 }
2305 
2306 static void
2307 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2308     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2309 {
2310 	if (tcp_bblogging_on(bbr->rc_tp)) {
2311 		union tcp_log_stackspecific log;
2312 
2313 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2314 		log.u_bbr.flex1 = line;
2315 		log.u_bbr.flex2 = o_len;
2316 		log.u_bbr.flex3 = segcnt;
2317 		log.u_bbr.flex4 = segsiz;
2318 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2319 		    &bbr->rc_inp->inp_socket->so_rcv,
2320 		    &bbr->rc_inp->inp_socket->so_snd,
2321 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2322 		    len, &log, true, &bbr->rc_tv);
2323 	}
2324 }
2325 
2326 static void
2327 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2328 {
2329 	if (tcp_bblogging_on(bbr->rc_tp)) {
2330 		union tcp_log_stackspecific log;
2331 
2332 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2333 		log.u_bbr.flex1 = timers;
2334 		log.u_bbr.flex2 = ret;
2335 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2336 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2337 		log.u_bbr.flex5 = cts;
2338 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2339 		log.u_bbr.flex8 = hpts_calling;
2340 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2341 		    &bbr->rc_inp->inp_socket->so_rcv,
2342 		    &bbr->rc_inp->inp_socket->so_snd,
2343 		    BBR_LOG_TO_PROCESS, 0,
2344 		    0, &log, false, &bbr->rc_tv);
2345 	}
2346 }
2347 
2348 static void
2349 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2350 {
2351 	if (tcp_bblogging_on(bbr->rc_tp)) {
2352 		union tcp_log_stackspecific log;
2353 		uint64_t ar;
2354 
2355 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2356 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2357 		log.u_bbr.flex2 = 0;
2358 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2359 		ar = (uintptr_t)(bbr->r_ctl.rc_resend);
2360 		ar >>= 32;
2361 		ar &= 0x00000000ffffffff;
2362 		log.u_bbr.flex4 = (uint32_t)ar;
2363 		ar = (uintptr_t)bbr->r_ctl.rc_resend;
2364 		ar &= 0x00000000ffffffff;
2365 		log.u_bbr.flex5 = (uint32_t)ar;
2366 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2367 		log.u_bbr.flex8 = to_num;
2368 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2369 		    &bbr->rc_inp->inp_socket->so_rcv,
2370 		    &bbr->rc_inp->inp_socket->so_snd,
2371 		    BBR_LOG_RTO, 0,
2372 		    0, &log, false, &bbr->rc_tv);
2373 	}
2374 }
2375 
2376 static void
2377 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2378 {
2379 	if (tcp_bblogging_on(bbr->rc_tp)) {
2380 		union tcp_log_stackspecific log;
2381 
2382 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2383 		log.u_bbr.flex1 = flex1;
2384 		log.u_bbr.flex2 = flex2;
2385 		log.u_bbr.flex3 = flex3;
2386 		log.u_bbr.flex4 = 0;
2387 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2388 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2389 		log.u_bbr.flex8 = reason;
2390 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2391 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2392 		    &bbr->rc_inp->inp_socket->so_rcv,
2393 		    &bbr->rc_inp->inp_socket->so_snd,
2394 		    BBR_LOG_REDUCE, 0,
2395 		    0, &log, false, &bbr->rc_tv);
2396 	}
2397 }
2398 
2399 static void
2400 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2401 {
2402 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2403 		union tcp_log_stackspecific log;
2404 
2405 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2406 		log.u_bbr.flex1 = diag->p_nxt_slot;
2407 		log.u_bbr.flex2 = diag->p_cur_slot;
2408 		log.u_bbr.flex3 = diag->slot_req;
2409 		log.u_bbr.flex4 = diag->inp_hptsslot;
2410 		log.u_bbr.flex5 = diag->slot_remaining;
2411 		log.u_bbr.flex6 = diag->need_new_to;
2412 		log.u_bbr.flex7 = diag->p_hpts_active;
2413 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2414 		/* Hijack other fields as needed  */
2415 		log.u_bbr.epoch = diag->have_slept;
2416 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2417 		log.u_bbr.pkts_out = diag->co_ret;
2418 		log.u_bbr.applimited = diag->hpts_sleep_time;
2419 		log.u_bbr.delivered = diag->p_prev_slot;
2420 		log.u_bbr.inflight = diag->p_runningslot;
2421 		log.u_bbr.bw_inuse = diag->wheel_slot;
2422 		log.u_bbr.rttProp = diag->wheel_cts;
2423 		log.u_bbr.delRate = diag->maxslots;
2424 		log.u_bbr.cur_del_rate = diag->p_curtick;
2425 		log.u_bbr.cur_del_rate <<= 32;
2426 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2427 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2428 		    &bbr->rc_inp->inp_socket->so_rcv,
2429 		    &bbr->rc_inp->inp_socket->so_snd,
2430 		    BBR_LOG_HPTSDIAG, 0,
2431 		    0, &log, false, &bbr->rc_tv);
2432 	}
2433 }
2434 
2435 static void
2436 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2437     uint32_t thresh, uint32_t to)
2438 {
2439 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2440 		union tcp_log_stackspecific log;
2441 
2442 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2443 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2444 		log.u_bbr.flex2 = time_since_sent;
2445 		log.u_bbr.flex3 = srtt;
2446 		log.u_bbr.flex4 = thresh;
2447 		log.u_bbr.flex5 = to;
2448 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2449 		log.u_bbr.flex8 = mode;
2450 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2451 		    &bbr->rc_inp->inp_socket->so_rcv,
2452 		    &bbr->rc_inp->inp_socket->so_snd,
2453 		    BBR_LOG_TIMERPREP, 0,
2454 		    0, &log, false, &bbr->rc_tv);
2455 	}
2456 }
2457 
2458 static void
2459 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2460     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2461 {
2462 	if (tcp_bblogging_on(bbr->rc_tp)) {
2463 		union tcp_log_stackspecific log;
2464 
2465 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2466 		log.u_bbr.flex1 = usecs;
2467 		log.u_bbr.flex2 = len;
2468 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2469 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2470 		if (override)
2471 			log.u_bbr.flex5 = (1 << 2);
2472 		else
2473 			log.u_bbr.flex5 = 0;
2474 		log.u_bbr.flex6 = override;
2475 		log.u_bbr.flex7 = gain;
2476 		log.u_bbr.flex8 = mod;
2477 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2478 		    &bbr->rc_inp->inp_socket->so_rcv,
2479 		    &bbr->rc_inp->inp_socket->so_snd,
2480 		    BBR_LOG_HPTSI_CALC, 0,
2481 		    len, &log, false, &bbr->rc_tv);
2482 	}
2483 }
2484 
2485 static void
2486 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2487 {
2488 	if (tcp_bblogging_on(bbr->rc_tp)) {
2489 		union tcp_log_stackspecific log;
2490 
2491 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2492 
2493 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2494 		log.u_bbr.flex2 = to;
2495 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2496 		log.u_bbr.flex4 = slot;
2497 		log.u_bbr.flex5 = bbr->rc_tp->t_hpts_slot;
2498 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2499 		log.u_bbr.pkts_out = bbr->rc_tp->t_flags2;
2500 		log.u_bbr.flex8 = which;
2501 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2502 		    &bbr->rc_inp->inp_socket->so_rcv,
2503 		    &bbr->rc_inp->inp_socket->so_snd,
2504 		    BBR_LOG_TIMERSTAR, 0,
2505 		    0, &log, false, &bbr->rc_tv);
2506 	}
2507 }
2508 
2509 static void
2510 bbr_log_thresh_choice(struct tcp_bbr *bbr, uint32_t cts, uint32_t thresh, uint32_t lro, uint32_t srtt, struct bbr_sendmap *rsm, uint8_t frm)
2511 {
2512 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2513 		union tcp_log_stackspecific log;
2514 
2515 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2516 		log.u_bbr.flex1 = thresh;
2517 		log.u_bbr.flex2 = lro;
2518 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2519 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2520 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2521 		log.u_bbr.flex6 = srtt;
2522 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2523 		log.u_bbr.flex8 = frm;
2524 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2525 		    &bbr->rc_inp->inp_socket->so_rcv,
2526 		    &bbr->rc_inp->inp_socket->so_snd,
2527 		    BBR_LOG_THRESH_CALC, 0,
2528 		    0, &log, false, &bbr->rc_tv);
2529 	}
2530 }
2531 
2532 static void
2533 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2534 {
2535 	if (tcp_bblogging_on(bbr->rc_tp)) {
2536 		union tcp_log_stackspecific log;
2537 
2538 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2539 		log.u_bbr.flex1 = line;
2540 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2541 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2542 		log.u_bbr.flex4 = bbr->rc_in_persist;
2543 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2544 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2545 		log.u_bbr.flex8 = hpts_removed;
2546 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2547 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2548 		    &bbr->rc_inp->inp_socket->so_rcv,
2549 		    &bbr->rc_inp->inp_socket->so_snd,
2550 		    BBR_LOG_TIMERCANC, 0,
2551 		    0, &log, false, &bbr->rc_tv);
2552 	}
2553 }
2554 
2555 static void
2556 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2557 {
2558 	if (tcp_bblogging_on(bbr->rc_tp)) {
2559 		union tcp_log_stackspecific log;
2560 
2561 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2562 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2563 		log.u_bbr.flex2 = (peer_delta >> 32);
2564 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2565 		log.u_bbr.flex4 = (delta >> 32);
2566 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2567 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2568 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2569 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2570 		    &bbr->rc_inp->inp_socket->so_rcv,
2571 		    &bbr->rc_inp->inp_socket->so_snd,
2572 		    BBR_LOG_TSTMP_VAL, 0,
2573 		    0, &log, false, &bbr->rc_tv);
2574 	}
2575 }
2576 
2577 static void
2578 bbr_log_type_tsosize(struct tcp_bbr *bbr, uint32_t cts, uint32_t tsosz, uint32_t tls, uint32_t old_val, uint32_t maxseg, int hdwr)
2579 {
2580 	if (tcp_bblogging_on(bbr->rc_tp)) {
2581 		union tcp_log_stackspecific log;
2582 
2583 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2584 		log.u_bbr.flex1 = tsosz;
2585 		log.u_bbr.flex2 = tls;
2586 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2587 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2588 		log.u_bbr.flex5 = old_val;
2589 		log.u_bbr.flex6 = maxseg;
2590 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2591 		log.u_bbr.flex7 <<= 1;
2592 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2593 		if (hdwr)
2594 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2595 		else
2596 			log.u_bbr.flex8 = bbr->rc_use_google;
2597 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2598 		    &bbr->rc_inp->inp_socket->so_rcv,
2599 		    &bbr->rc_inp->inp_socket->so_snd,
2600 		    BBR_LOG_BBRTSO, 0,
2601 		    0, &log, false, &bbr->rc_tv);
2602 	}
2603 }
2604 
2605 static void
2606 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2607 		      uint32_t flags, uint32_t line)
2608 {
2609 	if (tcp_bblogging_on(bbr->rc_tp)) {
2610 		union tcp_log_stackspecific log;
2611 
2612 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2613 		log.u_bbr.flex1 = line;
2614 		log.u_bbr.flex2 = rsm->r_start;
2615 		log.u_bbr.flex3 = rsm->r_end;
2616 		log.u_bbr.flex4 = rsm->r_delivered;
2617 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2618 		log.u_bbr.flex6 = rsm->r_dupack;
2619 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2620 		log.u_bbr.flex8 = rsm->r_flags;
2621 		/* Hijack the pkts_out fids */
2622 		log.u_bbr.applimited = flags;
2623 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2624 		    &bbr->rc_inp->inp_socket->so_rcv,
2625 		    &bbr->rc_inp->inp_socket->so_snd,
2626 		    BBR_RSM_CLEARED, 0,
2627 		    0, &log, false, &bbr->rc_tv);
2628 	}
2629 }
2630 
2631 static void
2632 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2633     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2634     uint32_t flex6, uint32_t pkts_out, int flex7,
2635     uint32_t flex4, uint32_t flex1)
2636 {
2637 
2638 	if (tcp_bblogging_on(bbr->rc_tp)) {
2639 		union tcp_log_stackspecific log;
2640 
2641 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2642 		log.u_bbr.flex1 = flex1;
2643 		log.u_bbr.flex2 = flex2;
2644 		log.u_bbr.flex3 = flex3;
2645 		log.u_bbr.flex4 = flex4;
2646 		log.u_bbr.flex5 = flex5;
2647 		log.u_bbr.flex6 = flex6;
2648 		log.u_bbr.flex7 = flex7;
2649 		/* Hijack the pkts_out fids */
2650 		log.u_bbr.pkts_out = pkts_out;
2651 		log.u_bbr.flex8 = flex8;
2652 		if (bbr->rc_ack_was_delayed)
2653 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2654 		else
2655 			log.u_bbr.epoch = 0;
2656 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2657 		    &bbr->rc_inp->inp_socket->so_rcv,
2658 		    &bbr->rc_inp->inp_socket->so_snd,
2659 		    BBR_LOG_BBRUPD, 0,
2660 		    flex2, &log, false, &bbr->rc_tv);
2661 	}
2662 }
2663 
2664 static void
2665 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2666 	uint32_t newbw, uint32_t obw, uint32_t diff,
2667 	uint32_t tim)
2668 {
2669 	if (/*bbr_verbose_logging && */tcp_bblogging_on(bbr->rc_tp)) {
2670 		union tcp_log_stackspecific log;
2671 
2672 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2673 		log.u_bbr.flex1 = reason;
2674 		log.u_bbr.flex2 = newbw;
2675 		log.u_bbr.flex3 = obw;
2676 		log.u_bbr.flex4 = diff;
2677 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2678 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2679 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2680 		log.u_bbr.pkts_out = tim;
2681 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2682 		if (bbr->rc_lt_use_bw == 0)
2683 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2684 		else
2685 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2686 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2687 		    &bbr->rc_inp->inp_socket->so_rcv,
2688 		    &bbr->rc_inp->inp_socket->so_snd,
2689 		    BBR_LOG_BWSAMP, 0,
2690 		    0, &log, false, &bbr->rc_tv);
2691 	}
2692 }
2693 
2694 static inline void
2695 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2696 {
2697 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2698 		union tcp_log_stackspecific log;
2699 
2700 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2701 		log.u_bbr.flex1 = line;
2702 		log.u_bbr.flex2 = tick;
2703 		log.u_bbr.flex3 = tp->t_maxunacktime;
2704 		log.u_bbr.flex4 = tp->t_acktime;
2705 		log.u_bbr.flex8 = event;
2706 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2707 		    &bbr->rc_inp->inp_socket->so_rcv,
2708 		    &bbr->rc_inp->inp_socket->so_snd,
2709 		    BBR_LOG_PROGRESS, 0,
2710 		    0, &log, false, &bbr->rc_tv);
2711 	}
2712 }
2713 
2714 static void
2715 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2716 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2717 			 int error)
2718 {
2719 	if (tcp_bblogging_on(bbr->rc_tp)) {
2720 		union tcp_log_stackspecific log;
2721 		uint64_t ifp64 = (uintptr_t)ifp;
2722 
2723 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2724 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2725 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2726 		log.u_bbr.flex3 = ((ifp64  >> 32) & 0x00000000ffffffff);
2727 		log.u_bbr.flex4 = (ifp64 & 0x00000000ffffffff);
2728 		log.u_bbr.bw_inuse = rate;
2729 		log.u_bbr.flex5 = line;
2730 		log.u_bbr.flex6 = error;
2731 		log.u_bbr.flex8 = bbr->skip_gain;
2732 		log.u_bbr.flex8 <<= 1;
2733 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2734 		log.u_bbr.flex8 <<= 1;
2735 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2736 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2737 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2738 		    &bbr->rc_inp->inp_socket->so_rcv,
2739 		    &bbr->rc_inp->inp_socket->so_snd,
2740 		    BBR_LOG_HDWR_PACE, 0,
2741 		    0, &log, false, &bbr->rc_tv);
2742 	}
2743 }
2744 
2745 static void
2746 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)
2747 {
2748 	if (tcp_bblogging_on(bbr->rc_tp)) {
2749 		union tcp_log_stackspecific log;
2750 
2751 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2752 		log.u_bbr.flex1 = slot;
2753 		log.u_bbr.flex2 = del_by;
2754 		log.u_bbr.flex3 = prev_delay;
2755 		log.u_bbr.flex4 = line;
2756 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2757 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2758 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2759 		log.u_bbr.flex8 = bbr->rc_in_persist;
2760 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2761 		    &bbr->rc_inp->inp_socket->so_rcv,
2762 		    &bbr->rc_inp->inp_socket->so_snd,
2763 		    BBR_LOG_BBRSND, 0,
2764 		    len, &log, false, &bbr->rc_tv);
2765 	}
2766 }
2767 
2768 static void
2769 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)
2770 {
2771 	if (tcp_bblogging_on(bbr->rc_tp)) {
2772 		union tcp_log_stackspecific log;
2773 
2774 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2775 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2776 		log.u_bbr.flex2 = 0;
2777 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2778 		log.u_bbr.flex4 = end;
2779 		log.u_bbr.flex5 = seq;
2780 		log.u_bbr.flex6 = t;
2781 		log.u_bbr.flex7 = match;
2782 		log.u_bbr.flex8 = flags;
2783 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2784 		    &bbr->rc_inp->inp_socket->so_rcv,
2785 		    &bbr->rc_inp->inp_socket->so_snd,
2786 		    BBR_LOG_BBRRTT, 0,
2787 		    0, &log, false, &bbr->rc_tv);
2788 	}
2789 }
2790 
2791 static void
2792 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2793 {
2794 	if (tcp_bblogging_on(bbr->rc_tp)) {
2795 		union tcp_log_stackspecific log;
2796 
2797 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2798 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2799 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2800 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2801 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2802 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2803 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2804 		log.u_bbr.flex7 = 0;
2805 		log.u_bbr.flex8 = entry_method;
2806 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2807 		    &bbr->rc_inp->inp_socket->so_rcv,
2808 		    &bbr->rc_inp->inp_socket->so_snd,
2809 		    BBR_LOG_EXIT_GAIN, 0,
2810 		    0, &log, false, &bbr->rc_tv);
2811 	}
2812 }
2813 
2814 static void
2815 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2816 {
2817 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2818 		union tcp_log_stackspecific log;
2819 
2820 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2821 		/* R-HU */
2822 		log.u_bbr.flex1 = 0;
2823 		log.u_bbr.flex2 = 0;
2824 		log.u_bbr.flex3 = 0;
2825 		log.u_bbr.flex4 = 0;
2826 		log.u_bbr.flex7 = 0;
2827 		log.u_bbr.flex8 = settings_desired;
2828 
2829 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2830 		    &bbr->rc_inp->inp_socket->so_rcv,
2831 		    &bbr->rc_inp->inp_socket->so_snd,
2832 		    BBR_LOG_SETTINGS_CHG, 0,
2833 		    0, &log, false, &bbr->rc_tv);
2834 	}
2835 }
2836 
2837 /*
2838  * Returns the bw from the our filter.
2839  */
2840 static inline uint64_t
2841 bbr_get_full_bw(struct tcp_bbr *bbr)
2842 {
2843 	uint64_t bw;
2844 
2845 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2846 
2847 	return (bw);
2848 }
2849 
2850 static inline void
2851 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2852 {
2853 	uint64_t calclr;
2854 	uint32_t lost, del;
2855 
2856 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2857 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2858 	else
2859 		lost = 0;
2860 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2861 	if (lost == 0)  {
2862 		calclr = 0;
2863 	} else if (del) {
2864 		calclr = lost;
2865 		calclr *= (uint64_t)1000;
2866 		calclr /= (uint64_t)del;
2867 	} else {
2868 		/* Nothing delivered? 100.0% loss */
2869 		calclr = 1000;
2870 	}
2871 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2872 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2873 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2874 	bbr->r_ctl.rc_pkt_epoch++;
2875 	if (bbr->rc_no_pacing &&
2876 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2877 		bbr->rc_no_pacing = 0;
2878 		tcp_bbr_tso_size_check(bbr, cts);
2879 	}
2880 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2881 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2882 	/* What was our loss rate */
2883 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2884 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2885 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2886 }
2887 
2888 static inline void
2889 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2890 {
2891 	uint32_t epoch_time;
2892 
2893 	/* Tick the RTT clock */
2894 	bbr->r_ctl.rc_rtt_epoch++;
2895 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2896 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2897 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2898 }
2899 
2900 static inline void
2901 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2902 {
2903 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2904 		bbr->rc_is_pkt_epoch_now = 1;
2905 	}
2906 }
2907 
2908 /*
2909  * Returns the bw from either the b/w filter
2910  * or from the lt_bw (if the connection is being
2911  * policed).
2912  */
2913 static inline uint64_t
2914 __bbr_get_bw(struct tcp_bbr *bbr)
2915 {
2916 	uint64_t bw, min_bw;
2917 	uint64_t rtt;
2918 	int gm_measure_cnt = 1;
2919 
2920 	/*
2921 	 * For startup we make, like google, a
2922 	 * minimum b/w. This is generated from the
2923 	 * IW and the rttProp. We do fall back to srtt
2924 	 * if for some reason (initial handshake) we don't
2925 	 * have a rttProp. We, in the worst case, fall back
2926 	 * to the configured min_bw (rc_initial_hptsi_bw).
2927 	 */
2928 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2929 		/* Attempt first to use rttProp */
2930 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2931 		if (rtt && (rtt < 0xffffffff)) {
2932 measure:
2933 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2934 				((uint64_t)1000000);
2935 			min_bw /= rtt;
2936 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2937 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2938 			}
2939 
2940 		} else if (bbr->rc_tp->t_srtt != 0) {
2941 			/* No rttProp, use srtt? */
2942 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2943 			goto measure;
2944 		} else {
2945 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2946 		}
2947 	} else
2948 		min_bw = 0;
2949 
2950 	if ((bbr->rc_past_init_win == 0) &&
2951 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2952 		bbr->rc_past_init_win = 1;
2953 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2954 		gm_measure_cnt = 0;
2955 	if (gm_measure_cnt &&
2956 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2957 	     (bbr->rc_past_init_win == 0))) {
2958 		/* For google we use our guess rate until we get 1 measurement */
2959 
2960 use_initial_window:
2961 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2962 		if (rtt && (rtt < 0xffffffff)) {
2963 			/*
2964 			 * We have an RTT measurement. Use that in
2965 			 * combination with our initial window to calculate
2966 			 * a b/w.
2967 			 */
2968 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2969 				((uint64_t)1000000);
2970 			bw /= rtt;
2971 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2972 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2973 			}
2974 		} else {
2975 			/* Drop back to the 40 and punt to a default */
2976 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2977 		}
2978 		if (bw < 1)
2979 			/* Probably should panic */
2980 			bw = 1;
2981 		if (bw > min_bw)
2982 			return (bw);
2983 		else
2984 			return (min_bw);
2985 	}
2986 	if (bbr->rc_lt_use_bw)
2987 		bw = bbr->r_ctl.rc_lt_bw;
2988 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2989 		bw = bbr->r_ctl.red_bw;
2990 	else
2991 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2992 	if (bw == 0) {
2993 		/* We should not be at 0, go to the initial window then  */
2994 		goto use_initial_window;
2995 	}
2996 	if (bw < 1)
2997 		/* Probably should panic */
2998 		bw = 1;
2999 	if (bw < min_bw)
3000 		bw = min_bw;
3001 	return (bw);
3002 }
3003 
3004 static inline uint64_t
3005 bbr_get_bw(struct tcp_bbr *bbr)
3006 {
3007 	uint64_t bw;
3008 
3009 	bw = __bbr_get_bw(bbr);
3010 	return (bw);
3011 }
3012 
3013 static inline void
3014 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3015 {
3016 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3017 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3018 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3019 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3020 }
3021 
3022 static inline void
3023 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3024 {
3025 	bbr->rc_lt_is_sampling = 0;
3026 	bbr->rc_lt_use_bw = 0;
3027 	bbr->r_ctl.rc_lt_bw = 0;
3028 	bbr_reset_lt_bw_interval(bbr, cts);
3029 }
3030 
3031 static inline void
3032 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3033 {
3034 	uint64_t diff;
3035 
3036 	/* Do we have a previous sample? */
3037 	if (bbr->r_ctl.rc_lt_bw) {
3038 		/* Get the diff in bytes per second */
3039 		if (bbr->r_ctl.rc_lt_bw > bw)
3040 			diff = bbr->r_ctl.rc_lt_bw - bw;
3041 		else
3042 			diff = bw - bbr->r_ctl.rc_lt_bw;
3043 		if ((diff <= bbr_lt_bw_diff) ||
3044 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3045 			/* Consider us policed */
3046 			uint32_t saved_bw;
3047 
3048 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3049 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3050 			bbr->rc_lt_use_bw = 1;
3051 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3052 			/*
3053 			 * Use pkt based epoch for measuring length of
3054 			 * policer up
3055 			 */
3056 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3057 			/*
3058 			 * reason 4 is we need to start consider being
3059 			 * policed
3060 			 */
3061 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3062 			return;
3063 		}
3064 	}
3065 	bbr->r_ctl.rc_lt_bw = bw;
3066 	bbr_reset_lt_bw_interval(bbr, cts);
3067 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3068 }
3069 
3070 static void
3071 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3072 {
3073 	uint32_t ran, deduct;
3074 
3075 	ran = arc4random_uniform(bbr_rand_ot);
3076 	if (ran) {
3077 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3078 		bbr->r_ctl.rc_level_state_extra -= deduct;
3079 	}
3080 }
3081 /*
3082  * Return randomly the starting state
3083  * to use in probebw.
3084  */
3085 static uint8_t
3086 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3087 {
3088 	uint32_t ran;
3089 	uint8_t ret_val;
3090 
3091 	/* Initialize the offset to 0 */
3092 	bbr->r_ctl.rc_exta_time_gd = 0;
3093 	bbr->rc_hit_state_1 = 0;
3094 	bbr->r_ctl.rc_level_state_extra = 0;
3095 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3096 	/*
3097 	 * The math works funny here :) the return value is used to set the
3098 	 * substate and then the state change is called which increments by
3099 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3100 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3101 	 * we return 1 - 7, so we dont return 0 and end up starting in
3102 	 * state 1 (DRAIN).
3103 	 */
3104 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3105 	/* Set an epoch */
3106 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3107 		bbr_set_epoch(bbr, cts, __LINE__);
3108 
3109 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3110 	return (ret_val);
3111 }
3112 
3113 static void
3114 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3115 {
3116 	uint32_t diff, d_time;
3117 	uint64_t del_time, bw, lost, delivered;
3118 
3119 	if (bbr->r_use_policer == 0)
3120 		return;
3121 	if (bbr->rc_lt_use_bw) {
3122 		/* We are using lt bw do we stop yet? */
3123 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3124 		if (diff > bbr_lt_bw_max_rtts) {
3125 			/* Reset it all */
3126 reset_all:
3127 			bbr_reset_lt_bw_sampling(bbr, cts);
3128 			if (bbr->rc_filled_pipe) {
3129 				bbr_set_epoch(bbr, cts, __LINE__);
3130 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3131 				bbr_substate_change(bbr, cts, __LINE__, 0);
3132 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3133 				bbr_log_type_statechange(bbr, cts, __LINE__);
3134 			} else {
3135 				/*
3136 				 * This should not happen really
3137 				 * unless we remove the startup/drain
3138 				 * restrictions above.
3139 				 */
3140 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3141 				bbr_set_epoch(bbr, cts, __LINE__);
3142 				bbr->r_ctl.rc_bbr_state_time = cts;
3143 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3144 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3145 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3146 				bbr_set_state_target(bbr, __LINE__);
3147 				bbr_log_type_statechange(bbr, cts, __LINE__);
3148 			}
3149 			/* reason 0 is to stop using lt-bw */
3150 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3151 			return;
3152 		}
3153 		if (bbr_lt_intvl_fp == 0) {
3154 			/* Not doing false-positive detection */
3155 			return;
3156 		}
3157 		/* False positive detection */
3158 		if (diff == bbr_lt_intvl_fp) {
3159 			/* At bbr_lt_intvl_fp we record the lost */
3160 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3161 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3162 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3163 			/* Now is our loss rate still high? */
3164 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3165 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3166 			if ((delivered == 0) ||
3167 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3168 				/* No still below our threshold */
3169 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3170 			} else {
3171 				/* Yikes its still high, it must be a false positive */
3172 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3173 				goto reset_all;
3174 			}
3175 		}
3176 		return;
3177 	}
3178 	/*
3179 	 * Wait for the first loss before sampling, to let the policer
3180 	 * exhaust its tokens and estimate the steady-state rate allowed by
3181 	 * the policer. Starting samples earlier includes bursts that
3182 	 * over-estimate the bw.
3183 	 */
3184 	if (bbr->rc_lt_is_sampling == 0) {
3185 		/* reason 1 is to begin doing the sampling  */
3186 		if (loss_detected == 0)
3187 			return;
3188 		bbr_reset_lt_bw_interval(bbr, cts);
3189 		bbr->rc_lt_is_sampling = 1;
3190 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3191 		return;
3192 	}
3193 	/* Now how long were we delivering long term last> */
3194 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3195 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3196 	else
3197 		d_time = 0;
3198 
3199 	/* To avoid underestimates, reset sampling if we run out of data. */
3200 	if (bbr->r_ctl.r_app_limited_until) {
3201 		/* Can not measure in app-limited state */
3202 		bbr_reset_lt_bw_sampling(bbr, cts);
3203 		/* reason 2 is to reset sampling due to app limits  */
3204 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3205 		return;
3206 	}
3207 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3208 	if (diff < bbr_lt_intvl_min_rtts) {
3209 		/*
3210 		 * need more samples (we don't
3211 		 * start on a round like linux so
3212 		 * we need 1 more).
3213 		 */
3214 		/* 6 is not_enough time or no-loss */
3215 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3216 		return;
3217 	}
3218 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3219 		/*
3220 		 * For now if we wait too long, reset all sampling. We need
3221 		 * to do some research here, its possible that we should
3222 		 * base this on how much loss as occurred.. something like
3223 		 * if its under 10% (or some thresh) reset all otherwise
3224 		 * don't.  Thats for phase II I guess.
3225 		 */
3226 		bbr_reset_lt_bw_sampling(bbr, cts);
3227  		/* reason 3 is to reset sampling due too long of sampling */
3228 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3229 		return;
3230 	}
3231 	/*
3232 	 * End sampling interval when a packet is lost, so we estimate the
3233 	 * policer tokens were exhausted. Stopping the sampling before the
3234 	 * tokens are exhausted under-estimates the policed rate.
3235 	 */
3236 	if (loss_detected == 0) {
3237 		/* 6 is not_enough time or no-loss */
3238 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3239 		return;
3240 	}
3241 	/* Calculate packets lost and delivered in sampling interval. */
3242 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3243 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3244 	if ((delivered == 0) ||
3245 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3246 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3247 		return;
3248 	}
3249 	if (d_time < 1000) {
3250 		/* Not enough time. wait */
3251 		/* 6 is not_enough time or no-loss */
3252 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3253 		return;
3254 	}
3255 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3256 		/* Too long */
3257 		bbr_reset_lt_bw_sampling(bbr, cts);
3258  		/* reason 3 is to reset sampling due too long of sampling */
3259 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3260 		return;
3261 	}
3262 	del_time = d_time;
3263 	bw = delivered;
3264 	bw *= (uint64_t)USECS_IN_SECOND;
3265 	bw /= del_time;
3266 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3267 }
3268 
3269 /*
3270  * Allocate a sendmap from our zone.
3271  */
3272 static struct bbr_sendmap *
3273 bbr_alloc(struct tcp_bbr *bbr)
3274 {
3275 	struct bbr_sendmap *rsm;
3276 
3277 	BBR_STAT_INC(bbr_to_alloc);
3278 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3279 	if (rsm) {
3280 		bbr->r_ctl.rc_num_maps_alloced++;
3281 		return (rsm);
3282 	}
3283 	if (bbr->r_ctl.rc_free_cnt) {
3284 		BBR_STAT_INC(bbr_to_alloc_emerg);
3285 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3286 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3287 		bbr->r_ctl.rc_free_cnt--;
3288 		return (rsm);
3289 	}
3290 	BBR_STAT_INC(bbr_to_alloc_failed);
3291 	return (NULL);
3292 }
3293 
3294 static struct bbr_sendmap *
3295 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3296 {
3297 	if ((V_tcp_map_entries_limit > 0) &&
3298 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3299 		BBR_STAT_INC(bbr_alloc_limited);
3300 		if (!bbr->alloc_limit_reported) {
3301 			bbr->alloc_limit_reported = 1;
3302 			BBR_STAT_INC(bbr_alloc_limited_conns);
3303 		}
3304 		return (NULL);
3305 	}
3306 	return (bbr_alloc(bbr));
3307 }
3308 
3309 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3310 static struct bbr_sendmap *
3311 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3312 {
3313 	struct bbr_sendmap *rsm;
3314 
3315 	if (limit_type) {
3316 		/* currently there is only one limit type */
3317 		if (V_tcp_map_split_limit > 0 &&
3318 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3319 			BBR_STAT_INC(bbr_split_limited);
3320 			if (!bbr->alloc_limit_reported) {
3321 				bbr->alloc_limit_reported = 1;
3322 				BBR_STAT_INC(bbr_alloc_limited_conns);
3323 			}
3324 			return (NULL);
3325 		}
3326 	}
3327 
3328 	/* allocate and mark in the limit type, if set */
3329 	rsm = bbr_alloc(bbr);
3330 	if (rsm != NULL && limit_type) {
3331 		rsm->r_limit_type = limit_type;
3332 		bbr->r_ctl.rc_num_split_allocs++;
3333 	}
3334 	return (rsm);
3335 }
3336 
3337 static void
3338 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3339 {
3340 	if (rsm->r_limit_type) {
3341 		/* currently there is only one limit type */
3342 		bbr->r_ctl.rc_num_split_allocs--;
3343 	}
3344 	if (rsm->r_is_smallmap)
3345 		bbr->r_ctl.rc_num_small_maps_alloced--;
3346 	if (bbr->r_ctl.rc_tlp_send == rsm)
3347 		bbr->r_ctl.rc_tlp_send = NULL;
3348 	if (bbr->r_ctl.rc_resend == rsm) {
3349 		bbr->r_ctl.rc_resend = NULL;
3350 	}
3351 	if (bbr->r_ctl.rc_next == rsm)
3352 		bbr->r_ctl.rc_next = NULL;
3353 	if (bbr->r_ctl.rc_sacklast == rsm)
3354 		bbr->r_ctl.rc_sacklast = NULL;
3355 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3356 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3357 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3358 		rsm->r_limit_type = 0;
3359 		bbr->r_ctl.rc_free_cnt++;
3360 		return;
3361 	}
3362 	bbr->r_ctl.rc_num_maps_alloced--;
3363 	uma_zfree(bbr_zone, rsm);
3364 }
3365 
3366 /*
3367  * Returns the BDP.
3368  */
3369 static uint64_t
3370 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3371 	/*
3372 	 * Calculate the bytes in flight needed given the bw (in bytes per
3373 	 * second) and the specifyed rtt in useconds. We need to put out the
3374 	 * returned value per RTT to match that rate. Gain will normally
3375 	 * raise it up from there.
3376 	 *
3377 	 * This should not overflow as long as the bandwidth is below 1
3378 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3379 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3380 	 */
3381 	uint64_t usec_per_sec;
3382 
3383 	usec_per_sec = USECS_IN_SECOND;
3384 	return ((rtt * bw) / usec_per_sec);
3385 }
3386 
3387 /*
3388  * Return the initial cwnd.
3389  */
3390 static uint32_t
3391 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3392 {
3393 	uint32_t i_cwnd;
3394 
3395 	if (bbr->rc_init_win) {
3396 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3397 	} else if (V_tcp_initcwnd_segments)
3398 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3399 		    max(2 * tp->t_maxseg, 14600));
3400 	else if (V_tcp_do_rfc3390)
3401 		i_cwnd = min(4 * tp->t_maxseg,
3402 		    max(2 * tp->t_maxseg, 4380));
3403 	else {
3404 		/* Per RFC5681 Section 3.1 */
3405 		if (tp->t_maxseg > 2190)
3406 			i_cwnd = 2 * tp->t_maxseg;
3407 		else if (tp->t_maxseg > 1095)
3408 			i_cwnd = 3 * tp->t_maxseg;
3409 		else
3410 			i_cwnd = 4 * tp->t_maxseg;
3411 	}
3412 	return (i_cwnd);
3413 }
3414 
3415 /*
3416  * Given a specified gain, return the target
3417  * cwnd based on that gain.
3418  */
3419 static uint32_t
3420 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3421 {
3422 	uint64_t bdp, rtt;
3423 	uint32_t cwnd;
3424 
3425 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3426 	    (bbr_get_full_bw(bbr) == 0)) {
3427 		/* No measurements yet */
3428 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3429 	}
3430 	/*
3431 	 * Get bytes per RTT needed (rttProp is normally in
3432 	 * bbr_cwndtarget_rtt_touse)
3433 	 */
3434 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3435 	/* Get the bdp from the two values */
3436 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3437 	/* Now apply the gain */
3438 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3439 
3440 	return (cwnd);
3441 }
3442 
3443 static uint32_t
3444 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3445 {
3446 	uint32_t cwnd, mss;
3447 
3448 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3449 	/* Get the base cwnd with gain rounded to a mss */
3450 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3451 	/*
3452 	 * Add in N (2 default since we do not have a
3453 	 * fq layer to trap packets in) quanta's per the I-D
3454 	 * section 4.2.3.2 quanta adjust.
3455 	 */
3456 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3457 	if (bbr->rc_use_google) {
3458 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3459 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3460 			/*
3461 			 * The linux implementation adds
3462 			 * an extra 2 x mss in gain cycle which
3463 			 * is documented no-where except in the code.
3464 			 * so we add more for Neal undocumented feature
3465 			 */
3466 			cwnd += 2 * mss;
3467 		}
3468  		if ((cwnd / mss) & 0x1) {
3469 			/* Round up for odd num mss */
3470 			cwnd += mss;
3471 		}
3472 	}
3473 	/* Are we below the min cwnd? */
3474 	if (cwnd < get_min_cwnd(bbr))
3475 		return (get_min_cwnd(bbr));
3476 	return (cwnd);
3477 }
3478 
3479 static uint16_t
3480 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3481 {
3482 	if (gain < 1)
3483 		gain = 1;
3484 	return (gain);
3485 }
3486 
3487 static uint32_t
3488 bbr_get_header_oh(struct tcp_bbr *bbr)
3489 {
3490 	int seg_oh;
3491 
3492 	seg_oh = 0;
3493 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3494 		/* Do we include TCP overhead? */
3495 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3496 	}
3497 	if (bbr->r_ctl.rc_inc_ip_oh) {
3498 		/* Do we include IP overhead? */
3499 #ifdef INET6
3500 		if (bbr->r_is_v6) {
3501 			seg_oh += sizeof(struct ip6_hdr);
3502 		} else
3503 #endif
3504 		{
3505 
3506 #ifdef INET
3507 			seg_oh += sizeof(struct ip);
3508 #endif
3509 		}
3510 	}
3511 	if (bbr->r_ctl.rc_inc_enet_oh) {
3512 		/* Do we include the ethernet overhead?  */
3513 		seg_oh += sizeof(struct ether_header);
3514 	}
3515 	return(seg_oh);
3516 }
3517 
3518 static uint32_t
3519 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3520 {
3521 	uint64_t divor, res, tim;
3522 
3523 	if (useconds_time == 0)
3524 		return (0);
3525 	gain = bbr_gain_adjust(bbr, gain);
3526 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3527 	tim = useconds_time;
3528 	res = (tim * bw * gain) / divor;
3529 	if (res == 0)
3530 		res = 1;
3531 	return ((uint32_t)res);
3532 }
3533 
3534 /*
3535  * Given a gain and a length return the delay in useconds that
3536  * should be used to evenly space out packets
3537  * on the connection (based on the gain factor).
3538  */
3539 static uint32_t
3540 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3541 {
3542 	uint64_t bw, lentim, res;
3543 	uint32_t usecs, srtt, over = 0;
3544 	uint32_t seg_oh, num_segs, maxseg;
3545 
3546 	if (len == 0)
3547 		return (0);
3548 
3549 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3550 	num_segs = (len + maxseg - 1) / maxseg;
3551 	if (bbr->rc_use_google == 0) {
3552 		seg_oh = bbr_get_header_oh(bbr);
3553 		len += (num_segs * seg_oh);
3554 	}
3555 	gain = bbr_gain_adjust(bbr, gain);
3556 	bw = bbr_get_bw(bbr);
3557 	if (bbr->rc_use_google) {
3558 		uint64_t cbw;
3559 
3560 		/*
3561 		 * Reduce the b/w by the google discount
3562 		 * factor 10 = 1%.
3563 		 */
3564 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3565 		cbw /= (uint64_t)1000;
3566 		/* We don't apply a discount if it results in 0 */
3567 		if (cbw > 0)
3568 			bw = cbw;
3569 	}
3570 	lentim = ((uint64_t)len *
3571 		  (uint64_t)USECS_IN_SECOND *
3572 		  (uint64_t)BBR_UNIT);
3573 	res = lentim / ((uint64_t)gain * bw);
3574 	if (res == 0)
3575 		res = 1;
3576 	usecs = (uint32_t)res;
3577 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3578 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3579 	    (bbr->rc_use_google == 0) &&
3580 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3581 		/*
3582 		 * We cannot let the delay be more than 1/2 the srtt time.
3583 		 * Otherwise we cannot pace out or send properly.
3584 		 */
3585 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3586 		BBR_STAT_INC(bbr_hpts_min_time);
3587 	}
3588 	if (!nolog)
3589 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3590 	return (usecs);
3591 }
3592 
3593 static void
3594 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3595 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3596 {
3597 	uint64_t bw;
3598 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3599 	int32_t meth;
3600 
3601 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3602 
3603 #ifdef STATS
3604 	if ((tp->t_flags & TF_GPUTINPROG) &&
3605 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3606 		/*
3607 		 * Strech acks and compressed acks will cause this to
3608 		 * oscillate but we are doing it the same way as the main
3609 		 * stack so it will be compariable (though possibly not
3610 		 * ideal).
3611 		 */
3612 		int32_t cgput;
3613 		int64_t gput, time_stamp;
3614 
3615 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3616 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3617 		cgput = gput / time_stamp;
3618 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3619 					 cgput);
3620 		if (tp->t_stats_gput_prev > 0)
3621 			stats_voi_update_abs_s32(tp->t_stats,
3622 						 VOI_TCP_GPUT_ND,
3623 						 ((gput - tp->t_stats_gput_prev) * 100) /
3624 						 tp->t_stats_gput_prev);
3625 		tp->t_flags &= ~TF_GPUTINPROG;
3626 		tp->t_stats_gput_prev = cgput;
3627 	}
3628 #endif
3629 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3630 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3631 		/* We don't change anything in probe-rtt */
3632 		return;
3633 	}
3634 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3635 	saved_bytes = bytes_this_ack;
3636 	bytes_this_ack += sack_changed;
3637 	if (bytes_this_ack > prev_acked) {
3638 		bytes_this_ack -= prev_acked;
3639 		/*
3640 		 * A byte ack'd gives us a full mss
3641 		 * to be like linux i.e. they count packets.
3642 		 */
3643 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3644 			bytes_this_ack = maxseg;
3645 	} else {
3646 		/* Unlikely */
3647 		bytes_this_ack = 0;
3648 	}
3649 	cwnd = tp->snd_cwnd;
3650 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3651 	if (bw)
3652 		target_cwnd = bbr_get_target_cwnd(bbr,
3653 						  bw,
3654 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3655 	else
3656 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3657 	if (IN_RECOVERY(tp->t_flags) &&
3658 	    (bbr->bbr_prev_in_rec == 0)) {
3659 		/*
3660 		 * We are entering recovery and
3661 		 * thus packet conservation.
3662 		 */
3663 		bbr->pkt_conservation = 1;
3664 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3665 		cwnd = ctf_flight_size(tp,
3666 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3667 			bytes_this_ack;
3668 	}
3669 	if (IN_RECOVERY(tp->t_flags)) {
3670 		uint32_t flight;
3671 
3672 		bbr->bbr_prev_in_rec = 1;
3673 		if (cwnd > losses) {
3674 			cwnd -= losses;
3675 			if (cwnd < maxseg)
3676 				cwnd = maxseg;
3677 		} else
3678 			cwnd = maxseg;
3679 		flight = ctf_flight_size(tp,
3680 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3681 		bbr_log_type_cwndupd(bbr, flight, 0,
3682 				     losses, 10, 0, 0, line);
3683 		if (bbr->pkt_conservation) {
3684 			uint32_t time_in;
3685 
3686 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3687 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3688 			else
3689 				time_in = 0;
3690 
3691 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3692 				/* Clear packet conservation after an rttProp */
3693 				bbr->pkt_conservation = 0;
3694 			} else {
3695 				if ((flight + bytes_this_ack) > cwnd)
3696 					cwnd = flight + bytes_this_ack;
3697 				if (cwnd < get_min_cwnd(bbr))
3698 					cwnd = get_min_cwnd(bbr);
3699 				tp->snd_cwnd = cwnd;
3700 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3701 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3702 				return;
3703 			}
3704 		}
3705 	} else
3706 		bbr->bbr_prev_in_rec = 0;
3707 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3708 		bbr->r_ctl.restrict_growth--;
3709 		if (bytes_this_ack > maxseg)
3710 			bytes_this_ack = maxseg;
3711 	}
3712 	if (bbr->rc_filled_pipe) {
3713 		/*
3714 		 * Here we have exited startup and filled the pipe. We will
3715 		 * thus allow the cwnd to shrink to the target. We hit here
3716 		 * mostly.
3717 		 */
3718 		uint32_t s_cwnd;
3719 
3720 		meth = 2;
3721 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3722 		if (s_cwnd > cwnd)
3723 			cwnd = s_cwnd;
3724 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3725 			cwnd = s_cwnd;
3726 	} else {
3727 		/*
3728 		 * Here we are still in startup, we increase cwnd by what
3729 		 * has been acked.
3730 		 */
3731 		if ((cwnd < target_cwnd) ||
3732 		    (bbr->rc_past_init_win == 0)) {
3733 			meth = 3;
3734 			cwnd += bytes_this_ack;
3735 		} else {
3736 			/*
3737 			 * Method 4 means we are at target so no gain in
3738 			 * startup and past the initial window.
3739 			 */
3740 			meth = 4;
3741 		}
3742 	}
3743 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3744 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3745 }
3746 
3747 static void
3748 tcp_bbr_partialack(struct tcpcb *tp)
3749 {
3750 	struct tcp_bbr *bbr;
3751 
3752 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3753 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3754 	if (ctf_flight_size(tp,
3755 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3756 	    tp->snd_cwnd) {
3757 		bbr->r_wanted_output = 1;
3758 	}
3759 }
3760 
3761 static void
3762 bbr_post_recovery(struct tcpcb *tp)
3763 {
3764 	struct tcp_bbr *bbr;
3765 	uint32_t  flight;
3766 
3767 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3768 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3769 	/*
3770 	 * Here we just exit recovery.
3771 	 */
3772 	EXIT_RECOVERY(tp->t_flags);
3773 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3774 	bbr->r_recovery_bw = 0;
3775 	tp->snd_recover = tp->snd_una;
3776 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3777 	bbr->pkt_conservation = 0;
3778 	if (bbr->rc_use_google == 0) {
3779 		/*
3780 		 * For non-google mode lets
3781 		 * go ahead and make sure we clear
3782 		 * the recovery state so if we
3783 		 * bounce back in to recovery we
3784 		 * will do PC.
3785 		 */
3786 		bbr->bbr_prev_in_rec = 0;
3787 	}
3788 	bbr_log_type_exit_rec(bbr);
3789 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3790 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3791 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3792 	} else {
3793 		/* For probe-rtt case lets fix up its saved_cwnd */
3794 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3795 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3796 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3797 		}
3798 	}
3799 	flight = ctf_flight_size(tp,
3800 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3801 	if ((bbr->rc_use_google == 0) &&
3802 	    bbr_do_red) {
3803 		uint64_t val, lr2use;
3804 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3805 		uint32_t *cwnd_p;
3806 
3807 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3808 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3809 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3810 			ratio = (uint32_t)val;
3811 		} else
3812 			ratio = 1000;
3813 
3814 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3815 				     bbr->r_ctl.recovery_lr, 21,
3816 				     ratio,
3817 				     bbr->r_ctl.rc_red_cwnd_pe,
3818 				     __LINE__);
3819 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3820 			goto done;
3821 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3822 		     bbr_prtt_slam_cwnd) ||
3823 		    (bbr_sub_drain_slam_cwnd &&
3824 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3825 		     bbr->rc_hit_state_1 &&
3826 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3827 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3828 		     bbr_slam_cwnd_in_main_drain)) {
3829 			/*
3830 			 * Here we must poke at the saved cwnd
3831 			 * as well as the cwnd.
3832 			 */
3833 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3834 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3835 		} else {
3836  			cwnd = tp->snd_cwnd;
3837 			cwnd_p = &tp->snd_cwnd;
3838 		}
3839 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3840 		/* Add the overall lr with the recovery lr */
3841 		if (bbr->r_ctl.rc_lost == 0)
3842 			lr2use = 0;
3843 		else if (bbr->r_ctl.rc_delivered == 0)
3844 			lr2use = 1000;
3845 		else {
3846 			lr2use = bbr->r_ctl.rc_lost * 1000;
3847 			lr2use /= bbr->r_ctl.rc_delivered;
3848 		}
3849 		lr2use += bbr->r_ctl.recovery_lr;
3850 		acks_inflight = (flight / (maxseg * 2));
3851 		if (bbr_red_scale) {
3852 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3853 			lr2use /= bbr_red_scale;
3854 			if ((bbr_red_growth_restrict) &&
3855 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3856 			    bbr->r_ctl.restrict_growth += acks_inflight;
3857 		}
3858 		if (lr2use) {
3859 			val = (uint64_t)cwnd * lr2use;
3860 			val /= 1000;
3861 			if (cwnd > val)
3862 				newcwnd = roundup((cwnd - val), maxseg);
3863 			else
3864 				newcwnd = maxseg;
3865 		} else {
3866 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3867 			val /= (uint64_t)bbr_red_div;
3868 			newcwnd = roundup((uint32_t)val, maxseg);
3869 		}
3870 		/* with standard delayed acks how many acks can I expect? */
3871 		if (bbr_drop_limit == 0) {
3872 			/*
3873 			 * Anticpate how much we will
3874 			 * raise the cwnd based on the acks.
3875 			 */
3876 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3877 				/* We do enforce the min (with the acks) */
3878 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3879 			}
3880 		} else {
3881 			/*
3882 			 * A strict drop limit of N is inplace
3883 			 */
3884 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3885 				newcwnd = bbr_drop_limit * maxseg;
3886 			}
3887 		}
3888 		/* For the next N acks do we restrict the growth */
3889 		*cwnd_p = newcwnd;
3890 		if (tp->snd_cwnd > newcwnd)
3891 			tp->snd_cwnd = newcwnd;
3892 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3893 				     (uint32_t)lr2use,
3894 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3895 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3896 	}
3897 done:
3898 	bbr->r_ctl.recovery_lr = 0;
3899 	if (flight <= tp->snd_cwnd) {
3900 		bbr->r_wanted_output = 1;
3901 	}
3902 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3903 }
3904 
3905 static void
3906 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3907 {
3908 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3909 	/* Limit the drop in b/w to 1/2 our current filter. */
3910 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3911 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3912 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3913 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3914 	tcp_bbr_tso_size_check(bbr, cts);
3915 }
3916 
3917 static void
3918 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3919 {
3920 	struct tcp_bbr *bbr;
3921 
3922 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3923 #ifdef STATS
3924 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3925 #endif
3926 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3927 	switch (type) {
3928 	case CC_NDUPACK:
3929 		if (!IN_RECOVERY(tp->t_flags)) {
3930 			tp->snd_recover = tp->snd_max;
3931 			/* Start a new epoch */
3932 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3933 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3934 				/*
3935 				 * Move forward the lt epoch
3936 				 * so it won't count the truncated
3937 				 * epoch.
3938 				 */
3939 				bbr->r_ctl.rc_lt_epoch++;
3940 			}
3941 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3942 				/*
3943 				 * Just like the policer detection code
3944 				 * if we are in startup we must push
3945 				 * forward the last startup epoch
3946 				 * to hide the truncated PE.
3947 				 */
3948 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3949 			}
3950 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3951 			ENTER_RECOVERY(tp->t_flags);
3952 			bbr->rc_tlp_rtx_out = 0;
3953 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3954 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3955 			if (tcp_in_hpts(bbr->rc_tp) &&
3956 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3957 				/*
3958 				 * When we enter recovery, we need to restart
3959 				 * any timers. This may mean we gain an agg
3960 				 * early, which will be made up for at the last
3961 				 * rxt out.
3962 				 */
3963 				bbr->rc_timer_first = 1;
3964 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3965 			}
3966 			/*
3967 			 * Calculate a new cwnd based on to the current
3968 			 * delivery rate with no gain. We get the bdp
3969 			 * without gaining it up like we normally would and
3970 			 * we use the last cur_del_rate.
3971 			 */
3972 			if ((bbr->rc_use_google == 0) &&
3973 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3974 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3975 				tp->snd_cwnd = ctf_flight_size(tp,
3976 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3977 					(tp->t_maxseg - bbr->rc_last_options);
3978 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3979 					/* We always gate to min cwnd */
3980 					tp->snd_cwnd = get_min_cwnd(bbr);
3981 				}
3982 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3983 			}
3984 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3985 		}
3986 		break;
3987 	case CC_RTO_ERR:
3988 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
3989 		/* RTO was unnecessary, so reset everything. */
3990 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
3991 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3992 			tp->snd_cwnd = tp->snd_cwnd_prev;
3993 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
3994 			tp->snd_recover = tp->snd_recover_prev;
3995 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3996 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
3997 		}
3998 		tp->t_badrxtwin = 0;
3999 		break;
4000 	}
4001 }
4002 
4003 /*
4004  * Indicate whether this ack should be delayed.  We can delay the ack if
4005  * following conditions are met:
4006  *	- There is no delayed ack timer in progress.
4007  *	- Our last ack wasn't a 0-sized window. We never want to delay
4008  *	  the ack that opens up a 0-sized window.
4009  *	- LRO wasn't used for this segment. We make sure by checking that the
4010  *	  segment size is not larger than the MSS.
4011  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4012  *	  connection.
4013  *	- The data being acked is less than a full segment (a stretch ack
4014  *        of more than a segment we should ack.
4015  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4016  */
4017 #define DELAY_ACK(tp, bbr, nsegs)				\
4018 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4019 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4020 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4021 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4022 
4023 /*
4024  * Return the lowest RSM in the map of
4025  * packets still in flight that is not acked.
4026  * This should normally find on the first one
4027  * since we remove packets from the send
4028  * map after they are marked ACKED.
4029  */
4030 static struct bbr_sendmap *
4031 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4032 {
4033 	struct bbr_sendmap *rsm;
4034 
4035 	/*
4036 	 * Walk the time-order transmitted list looking for an rsm that is
4037 	 * not acked. This will be the one that was sent the longest time
4038 	 * ago that is still outstanding.
4039 	 */
4040 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4041 		if (rsm->r_flags & BBR_ACKED) {
4042 			continue;
4043 		}
4044 		goto finish;
4045 	}
4046 finish:
4047 	return (rsm);
4048 }
4049 
4050 static struct bbr_sendmap *
4051 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4052 {
4053 	struct bbr_sendmap *prsm;
4054 
4055 	/*
4056 	 * Walk the sequence order list backward until we hit and arrive at
4057 	 * the highest seq not acked. In theory when this is called it
4058 	 * should be the last segment (which it was not).
4059 	 */
4060 	prsm = rsm;
4061 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4062 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4063 			continue;
4064 		}
4065 		return (prsm);
4066 	}
4067 	return (NULL);
4068 }
4069 
4070 /*
4071  * Returns to the caller the number of microseconds that
4072  * the packet can be outstanding before we think we
4073  * should have had an ack returned.
4074  */
4075 static uint32_t
4076 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4077 {
4078 	/*
4079 	 * lro is the flag we use to determine if we have seen reordering.
4080 	 * If it gets set we have seen reordering. The reorder logic either
4081 	 * works in one of two ways:
4082 	 *
4083 	 * If reorder-fade is configured, then we track the last time we saw
4084 	 * re-ordering occur. If we reach the point where enough time as
4085 	 * passed we no longer consider reordering has occuring.
4086 	 *
4087 	 * Or if reorder-face is 0, then once we see reordering we consider
4088 	 * the connection to alway be subject to reordering and just set lro
4089 	 * to 1.
4090 	 *
4091 	 * In the end if lro is non-zero we add the extra time for
4092 	 * reordering in.
4093 	 */
4094 	int32_t lro;
4095 	uint32_t thresh, t_rxtcur;
4096 
4097 	if (srtt == 0)
4098 		srtt = 1;
4099 	if (bbr->r_ctl.rc_reorder_ts) {
4100 		if (bbr->r_ctl.rc_reorder_fade) {
4101 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4102 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4103 				if (lro == 0) {
4104 					/*
4105 					 * No time as passed since the last
4106 					 * reorder, mark it as reordering.
4107 					 */
4108 					lro = 1;
4109 				}
4110 			} else {
4111 				/* Negative time? */
4112 				lro = 0;
4113 			}
4114 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4115 				/* Turn off reordering seen too */
4116 				bbr->r_ctl.rc_reorder_ts = 0;
4117 				lro = 0;
4118 			}
4119 		} else {
4120 			/* Reodering does not fade */
4121 			lro = 1;
4122 		}
4123 	} else {
4124 		lro = 0;
4125 	}
4126 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4127 	if (lro) {
4128 		/* It must be set, if not you get 1/4 rtt */
4129 		if (bbr->r_ctl.rc_reorder_shift)
4130 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4131 		else
4132 			thresh += (srtt >> 2);
4133 	} else {
4134 		thresh += 1000;
4135 	}
4136 	/* We don't let the rack timeout be above a RTO */
4137 	if ((bbr->rc_tp)->t_srtt == 0)
4138 		t_rxtcur = BBR_INITIAL_RTO;
4139 	else
4140 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4141 	if (thresh > t_rxtcur) {
4142 		thresh = t_rxtcur;
4143 	}
4144 	/* And we don't want it above the RTO max either */
4145 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4146 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4147 	}
4148 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4149 	return (thresh);
4150 }
4151 
4152 /*
4153  * Return to the caller the amount of time in mico-seconds
4154  * that should be used for the TLP timer from the last
4155  * send time of this packet.
4156  */
4157 static uint32_t
4158 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4159     struct bbr_sendmap *rsm, uint32_t srtt,
4160     uint32_t cts)
4161 {
4162 	uint32_t thresh, len, maxseg, t_rxtcur;
4163 	struct bbr_sendmap *prsm;
4164 
4165 	if (srtt == 0)
4166 		srtt = 1;
4167 	if (bbr->rc_tlp_threshold)
4168 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4169 	else
4170 		thresh = (srtt * 2);
4171 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4172 	/* Get the previous sent packet, if any  */
4173 	len = rsm->r_end - rsm->r_start;
4174 
4175 	/* 2.1 behavior */
4176 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4177 	if (prsm && (len <= maxseg)) {
4178 		/*
4179 		 * Two packets outstanding, thresh should be (2*srtt) +
4180 		 * possible inter-packet delay (if any).
4181 		 */
4182 		uint32_t inter_gap = 0;
4183 		int idx, nidx;
4184 
4185 		idx = rsm->r_rtr_cnt - 1;
4186 		nidx = prsm->r_rtr_cnt - 1;
4187 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4188 			/* Yes it was sent later (or at the same time) */
4189 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4190 		}
4191 		thresh += inter_gap;
4192 	} else if (len <= maxseg) {
4193 		/*
4194 		 * Possibly compensate for delayed-ack.
4195 		 */
4196 		uint32_t alt_thresh;
4197 
4198 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4199 		if (alt_thresh > thresh)
4200 			thresh = alt_thresh;
4201 	}
4202 	/* Not above the current  RTO */
4203 	if (tp->t_srtt == 0)
4204 		t_rxtcur = BBR_INITIAL_RTO;
4205 	else
4206 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4207 
4208 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4209 	/* Not above an RTO */
4210 	if (thresh > t_rxtcur) {
4211 		thresh = t_rxtcur;
4212 	}
4213 	/* Not above a RTO max */
4214 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4215 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4216 	}
4217 	/* And now apply the user TLP min */
4218 	if (thresh < bbr_tlp_min) {
4219 		thresh = bbr_tlp_min;
4220 	}
4221 	return (thresh);
4222 }
4223 
4224 /*
4225  * Return one of three RTTs to use (in microseconds).
4226  */
4227 static __inline uint32_t
4228 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4229 {
4230 	uint32_t f_rtt;
4231 	uint32_t srtt;
4232 
4233 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4234 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4235 		/* We have no rtt at all */
4236 		if (bbr->rc_tp->t_srtt == 0)
4237 			f_rtt = BBR_INITIAL_RTO;
4238 		else
4239 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4240 		/*
4241 		 * Since we don't know how good the rtt is apply a
4242 		 * delayed-ack min
4243 		 */
4244 		if (f_rtt < bbr_delayed_ack_time) {
4245 			f_rtt = bbr_delayed_ack_time;
4246 		}
4247 	}
4248 	/* Take the filter version or last measured pkt-rtt */
4249 	if (rtt_type == BBR_RTT_PROP) {
4250 		srtt = f_rtt;
4251 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4252 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4253 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4254 		} else {
4255 			/* No pkt rtt yet */
4256 			srtt = f_rtt;
4257 		}
4258 	} else if (rtt_type == BBR_RTT_RACK) {
4259 		srtt = bbr->r_ctl.rc_last_rtt;
4260 		/* We need to add in any internal delay for our timer */
4261 		if (bbr->rc_ack_was_delayed)
4262 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4263 	} else if (rtt_type == BBR_SRTT) {
4264 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4265 	} else {
4266 		/* TSNH */
4267 		srtt = f_rtt;
4268 #ifdef BBR_INVARIANTS
4269 		panic("Unknown rtt request type %d", rtt_type);
4270 #endif
4271 	}
4272 	return (srtt);
4273 }
4274 
4275 static int
4276 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4277 {
4278 	uint32_t thresh;
4279 
4280 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4281 				      cts, rsm);
4282 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4283 		/* It is lost (past time) */
4284 		return (1);
4285 	}
4286 	return (0);
4287 }
4288 
4289 /*
4290  * Return a sendmap if we need to retransmit something.
4291  */
4292 static struct bbr_sendmap *
4293 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4294 {
4295 	/*
4296 	 * Check to see that we don't need to fall into recovery. We will
4297 	 * need to do so if our oldest transmit is past the time we should
4298 	 * have had an ack.
4299 	 */
4300 
4301 	struct bbr_sendmap *rsm;
4302 	int32_t idx;
4303 
4304 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4305 		/* Nothing outstanding that we know of */
4306 		return (NULL);
4307 	}
4308 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4309 	if (rsm == NULL) {
4310 		/* Nothing in the transmit map */
4311 		return (NULL);
4312 	}
4313 	if (tp->t_flags & TF_SENTFIN) {
4314 		/* Fin restricted, don't find anything once a fin is sent */
4315 		return (NULL);
4316 	}
4317 	if (rsm->r_flags & BBR_ACKED) {
4318 		/*
4319 		 * Ok the first one is acked (this really should not happen
4320 		 * since we remove the from the tmap once they are acked)
4321 		 */
4322 		rsm = bbr_find_lowest_rsm(bbr);
4323 		if (rsm == NULL)
4324 			return (NULL);
4325 	}
4326 	idx = rsm->r_rtr_cnt - 1;
4327 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4328 		/* Send timestamp is the same or less? can't be ready */
4329 		return (NULL);
4330 	}
4331 	/* Get our RTT time */
4332 	if (bbr_is_lost(bbr, rsm, cts) &&
4333 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4334 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4335 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4336 			rsm->r_flags |= BBR_MARKED_LOST;
4337 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4338 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4339 		}
4340 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4341 #ifdef BBR_INVARIANTS
4342 		if ((rsm->r_end - rsm->r_start) == 0)
4343 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4344 #endif
4345 		return (rsm);
4346 	}
4347 	return (NULL);
4348 }
4349 
4350 /*
4351  * RACK Timer, here we simply do logging and house keeping.
4352  * the normal bbr_output_wtime() function will call the
4353  * appropriate thing to check if we need to do a RACK retransmit.
4354  * We return 1, saying don't proceed with bbr_output_wtime only
4355  * when all timers have been stopped (destroyed PCB?).
4356  */
4357 static int
4358 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4359 {
4360 	/*
4361 	 * This timer simply provides an internal trigger to send out data.
4362 	 * The check_recovery_mode call will see if there are needed
4363 	 * retransmissions, if so we will enter fast-recovery. The output
4364 	 * call may or may not do the same thing depending on sysctl
4365 	 * settings.
4366 	 */
4367 	uint32_t lost;
4368 
4369 	if (bbr->rc_all_timers_stopped) {
4370 		return (1);
4371 	}
4372 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4373 		/* Its not time yet */
4374 		return (0);
4375 	}
4376 	BBR_STAT_INC(bbr_to_tot);
4377 	lost = bbr->r_ctl.rc_lost;
4378 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4379 		bbr_set_state(tp, bbr, 0);
4380 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4381 	if (bbr->r_ctl.rc_resend == NULL) {
4382 		/* Lets do the check here */
4383 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4384 	}
4385 	if (bbr_policer_call_from_rack_to)
4386 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4387 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4388 	return (0);
4389 }
4390 
4391 static __inline void
4392 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4393 {
4394 	int idx;
4395 
4396 	nrsm->r_start = start;
4397 	nrsm->r_end = rsm->r_end;
4398 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4399 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4400 	nrsm->r_flags = rsm->r_flags;
4401 	/* We don't transfer forward the SYN flag */
4402 	nrsm->r_flags &= ~BBR_HAS_SYN;
4403 	/* We move forward the FIN flag, not that this should happen */
4404 	rsm->r_flags &= ~BBR_HAS_FIN;
4405 	nrsm->r_dupack = rsm->r_dupack;
4406 	nrsm->r_rtr_bytes = 0;
4407 	nrsm->r_is_gain = rsm->r_is_gain;
4408 	nrsm->r_is_drain = rsm->r_is_drain;
4409 	nrsm->r_delivered = rsm->r_delivered;
4410 	nrsm->r_ts_valid = rsm->r_ts_valid;
4411 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4412 	nrsm->r_del_time = rsm->r_del_time;
4413 	nrsm->r_app_limited = rsm->r_app_limited;
4414 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4415 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4416 	/* We split a piece the lower section looses any just_ret flag. */
4417 	nrsm->r_bbr_state = rsm->r_bbr_state;
4418 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4419 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4420 	}
4421 	rsm->r_end = nrsm->r_start;
4422 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4423 	idx /= 8;
4424 	/* Check if we got too small */
4425 	if ((rsm->r_is_smallmap == 0) &&
4426 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4427 		bbr->r_ctl.rc_num_small_maps_alloced++;
4428 		rsm->r_is_smallmap = 1;
4429 	}
4430 	/* Check the new one as well */
4431 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4432 		bbr->r_ctl.rc_num_small_maps_alloced++;
4433 		nrsm->r_is_smallmap = 1;
4434 	}
4435 }
4436 
4437 static int
4438 bbr_sack_mergable(struct bbr_sendmap *at,
4439 		  uint32_t start, uint32_t end)
4440 {
4441 	/*
4442 	 * Given a sack block defined by
4443 	 * start and end, and a current position
4444 	 * at. Return 1 if either side of at
4445 	 * would show that the block is mergable
4446 	 * to that side. A block to be mergable
4447 	 * must have overlap with the start/end
4448 	 * and be in the SACK'd state.
4449 	 */
4450 	struct bbr_sendmap *l_rsm;
4451 	struct bbr_sendmap *r_rsm;
4452 
4453 	/* first get the either side blocks */
4454 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4455 	r_rsm = TAILQ_NEXT(at, r_next);
4456 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4457 		/* Potentially mergeable */
4458 		if ((l_rsm->r_end == start) ||
4459 		    (SEQ_LT(start, l_rsm->r_end) &&
4460 		     SEQ_GT(end, l_rsm->r_end))) {
4461 			    /*
4462 			     * map blk   |------|
4463 			     * sack blk         |------|
4464 			     * <or>
4465 			     * map blk   |------|
4466 			     * sack blk      |------|
4467 			     */
4468 			    return (1);
4469 		    }
4470 	}
4471 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4472 		/* Potentially mergeable */
4473 		if ((r_rsm->r_start == end) ||
4474 		    (SEQ_LT(start, r_rsm->r_start) &&
4475 		     SEQ_GT(end, r_rsm->r_start))) {
4476 			/*
4477 			 * map blk          |---------|
4478 			 * sack blk    |----|
4479 			 * <or>
4480 			 * map blk          |---------|
4481 			 * sack blk    |-------|
4482 			 */
4483 			return (1);
4484 		}
4485 	}
4486 	return (0);
4487 }
4488 
4489 static struct bbr_sendmap *
4490 bbr_merge_rsm(struct tcp_bbr *bbr,
4491 	      struct bbr_sendmap *l_rsm,
4492 	      struct bbr_sendmap *r_rsm)
4493 {
4494 	/*
4495 	 * We are merging two ack'd RSM's,
4496 	 * the l_rsm is on the left (lower seq
4497 	 * values) and the r_rsm is on the right
4498 	 * (higher seq value). The simplest way
4499 	 * to merge these is to move the right
4500 	 * one into the left. I don't think there
4501 	 * is any reason we need to try to find
4502 	 * the oldest (or last oldest retransmitted).
4503 	 */
4504 	l_rsm->r_end = r_rsm->r_end;
4505 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4506 		l_rsm->r_dupack = r_rsm->r_dupack;
4507 	if (r_rsm->r_rtr_bytes)
4508 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4509 	if (r_rsm->r_in_tmap) {
4510 		/* This really should not happen */
4511 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4512 	}
4513 	if (r_rsm->r_app_limited)
4514 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4515 	/* Now the flags */
4516 	if (r_rsm->r_flags & BBR_HAS_FIN)
4517 		l_rsm->r_flags |= BBR_HAS_FIN;
4518 	if (r_rsm->r_flags & BBR_TLP)
4519 		l_rsm->r_flags |= BBR_TLP;
4520 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4521 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4522 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4523 		/* This really should not happen */
4524 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4525 	}
4526 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4527 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4528 		/* Transfer the split limit to the map we free */
4529 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4530 		l_rsm->r_limit_type = 0;
4531 	}
4532 	bbr_free(bbr, r_rsm);
4533 	return(l_rsm);
4534 }
4535 
4536 /*
4537  * TLP Timer, here we simply setup what segment we want to
4538  * have the TLP expire on, the normal bbr_output_wtime() will then
4539  * send it out.
4540  *
4541  * We return 1, saying don't proceed with bbr_output_wtime only
4542  * when all timers have been stopped (destroyed PCB?).
4543  */
4544 static int
4545 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4546 {
4547 	/*
4548 	 * Tail Loss Probe.
4549 	 */
4550 	struct bbr_sendmap *rsm = NULL;
4551 	struct socket *so;
4552 	uint32_t amm;
4553 	uint32_t out, avail;
4554 	uint32_t maxseg;
4555 	int collapsed_win = 0;
4556 
4557 	if (bbr->rc_all_timers_stopped) {
4558 		return (1);
4559 	}
4560 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4561 		/* Its not time yet */
4562 		return (0);
4563 	}
4564 	if (ctf_progress_timeout_check(tp, true)) {
4565 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4566 		return (-ETIMEDOUT);	/* tcp_drop() */
4567 	}
4568 	/* Did we somehow get into persists? */
4569 	if (bbr->rc_in_persist) {
4570 		return (0);
4571 	}
4572 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4573 		bbr_set_state(tp, bbr, 0);
4574 	BBR_STAT_INC(bbr_tlp_tot);
4575 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4576 	/*
4577 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4578 	 * need to figure out how to force a full MSS segment out.
4579 	 */
4580 	so = tptosocket(tp);
4581 	avail = sbavail(&so->so_snd);
4582 	out = ctf_outstanding(tp);
4583 	if (out > tp->snd_wnd) {
4584 		/* special case, we need a retransmission */
4585 		collapsed_win = 1;
4586 		goto need_retran;
4587 	}
4588 	if (avail > out) {
4589 		/* New data is available */
4590 		amm = avail - out;
4591 		if (amm > maxseg) {
4592 			amm = maxseg;
4593 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4594 			/* not enough to fill a MTU and no-delay is off */
4595 			goto need_retran;
4596 		}
4597 		/* Set the send-new override */
4598 		if ((out + amm) <= tp->snd_wnd) {
4599 			bbr->rc_tlp_new_data = 1;
4600 		} else {
4601 			goto need_retran;
4602 		}
4603 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4604 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4605 		bbr->r_ctl.rc_tlp_send = NULL;
4606 		/* cap any slots */
4607 		BBR_STAT_INC(bbr_tlp_newdata);
4608 		goto send;
4609 	}
4610 need_retran:
4611 	/*
4612 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4613 	 * optionally the first un-acked segment.
4614 	 */
4615 	if (collapsed_win == 0) {
4616 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4617 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4618 			rsm = bbr_find_high_nonack(bbr, rsm);
4619 		}
4620 		if (rsm == NULL) {
4621 			goto restore;
4622 		}
4623 	} else {
4624 		/*
4625 		 * We must find the last segment
4626 		 * that was acceptable by the client.
4627 		 */
4628 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4629 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4630 				/* Found one */
4631 				break;
4632 			}
4633 		}
4634 		if (rsm == NULL) {
4635 			/* None? if so send the first */
4636 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4637 			if (rsm == NULL)
4638 				goto restore;
4639 		}
4640 	}
4641 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4642 		/*
4643 		 * We need to split this the last segment in two.
4644 		 */
4645 		struct bbr_sendmap *nrsm;
4646 
4647 		nrsm = bbr_alloc_full_limit(bbr);
4648 		if (nrsm == NULL) {
4649 			/*
4650 			 * We can't get memory to split, we can either just
4651 			 * not split it. Or retransmit the whole piece, lets
4652 			 * do the large send (BTLP :-) ).
4653 			 */
4654 			goto go_for_it;
4655 		}
4656 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4657 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4658 		if (rsm->r_in_tmap) {
4659 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4660 			nrsm->r_in_tmap = 1;
4661 		}
4662 		rsm->r_flags &= (~BBR_HAS_FIN);
4663 		rsm = nrsm;
4664 	}
4665 go_for_it:
4666 	bbr->r_ctl.rc_tlp_send = rsm;
4667 	bbr->rc_tlp_rtx_out = 1;
4668 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4669 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4670 		tp->t_rxtshift++;
4671 	} else {
4672 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4673 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4674 	}
4675 send:
4676 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4677 		/*
4678 		 * Can't [re]/transmit a segment we have retransmitted the
4679 		 * max times. We need the retransmit timer to take over.
4680 		 */
4681 restore:
4682 		bbr->rc_tlp_new_data = 0;
4683 		bbr->r_ctl.rc_tlp_send = NULL;
4684 		if (rsm)
4685 			rsm->r_flags &= ~BBR_TLP;
4686 		BBR_STAT_INC(bbr_tlp_retran_fail);
4687 		return (0);
4688 	} else if (rsm) {
4689 		rsm->r_flags |= BBR_TLP;
4690 	}
4691 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4692 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4693 		/*
4694 		 * We have retransmitted to many times for TLP. Switch to
4695 		 * the regular RTO timer
4696 		 */
4697 		goto restore;
4698 	}
4699 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4700 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4701 	return (0);
4702 }
4703 
4704 /*
4705  * Delayed ack Timer, here we simply need to setup the
4706  * ACK_NOW flag and remove the DELACK flag. From there
4707  * the output routine will send the ack out.
4708  *
4709  * We only return 1, saying don't proceed, if all timers
4710  * are stopped (destroyed PCB?).
4711  */
4712 static int
4713 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4714 {
4715 	if (bbr->rc_all_timers_stopped) {
4716 		return (1);
4717 	}
4718 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4719 	tp->t_flags &= ~TF_DELACK;
4720 	tp->t_flags |= TF_ACKNOW;
4721 	KMOD_TCPSTAT_INC(tcps_delack);
4722 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4723 	return (0);
4724 }
4725 
4726 /*
4727  * Here we send a KEEP-ALIVE like probe to the
4728  * peer, we do not send data.
4729  *
4730  * We only return 1, saying don't proceed, if all timers
4731  * are stopped (destroyed PCB?).
4732  */
4733 static int
4734 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4735 {
4736 	struct tcptemp *t_template;
4737 	int32_t retval = 1;
4738 
4739 	if (bbr->rc_all_timers_stopped) {
4740 		return (1);
4741 	}
4742 	if (bbr->rc_in_persist == 0)
4743 		return (0);
4744 
4745 	/*
4746 	 * Persistence timer into zero window. Force a byte to be output, if
4747 	 * possible.
4748 	 */
4749 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4750 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4751 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4752 	/*
4753 	 * Have we exceeded the user specified progress time?
4754 	 */
4755 	if (ctf_progress_timeout_check(tp, true)) {
4756 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4757 		return (-ETIMEDOUT);	/* tcp_drop() */
4758 	}
4759 	/*
4760 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4761 	 * window is closed.  After a full backoff, drop the connection if
4762 	 * the idle time (no responses to probes) reaches the maximum
4763 	 * backoff that we would use if retransmitting.
4764 	 */
4765 	if (tp->t_rxtshift >= V_tcp_retries &&
4766 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4767 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4768 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4769 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4770 		return (-ETIMEDOUT);	/* tcp_drop() */
4771 	}
4772 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4773 	    tp->snd_una == tp->snd_max) {
4774 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4775 		retval = 0;
4776 		goto out;
4777 	}
4778 	/*
4779 	 * If the user has closed the socket then drop a persisting
4780 	 * connection after a much reduced timeout.
4781 	 */
4782 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4783 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4784 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4785 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4786 		return (-ETIMEDOUT);	/* tcp_drop() */
4787 	}
4788 	t_template = tcpip_maketemplate(bbr->rc_inp);
4789 	if (t_template) {
4790 		tcp_respond(tp, t_template->tt_ipgen,
4791 			    &t_template->tt_t, (struct mbuf *)NULL,
4792 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4793 		/* This sends an ack */
4794 		if (tp->t_flags & TF_DELACK)
4795 			tp->t_flags &= ~TF_DELACK;
4796 		free(t_template, M_TEMP);
4797 	}
4798 	if (tp->t_rxtshift < V_tcp_retries)
4799 		tp->t_rxtshift++;
4800 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4801 out:
4802 	return (retval);
4803 }
4804 
4805 /*
4806  * If a keepalive goes off, we had no other timers
4807  * happening. We always return 1 here since this
4808  * routine either drops the connection or sends
4809  * out a segment with respond.
4810  */
4811 static int
4812 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4813 {
4814 	struct tcptemp *t_template;
4815 	struct inpcb *inp = tptoinpcb(tp);
4816 
4817 	if (bbr->rc_all_timers_stopped) {
4818 		return (1);
4819 	}
4820 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4821 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4822 	/*
4823 	 * Keep-alive timer went off; send something or drop connection if
4824 	 * idle for too long.
4825 	 */
4826 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4827 	if (tp->t_state < TCPS_ESTABLISHED)
4828 		goto dropit;
4829 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4830 	    tp->t_state <= TCPS_CLOSING) {
4831 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4832 			goto dropit;
4833 		/*
4834 		 * Send a packet designed to force a response if the peer is
4835 		 * up and reachable: either an ACK if the connection is
4836 		 * still alive, or an RST if the peer has closed the
4837 		 * connection due to timeout or reboot. Using sequence
4838 		 * number tp->snd_una-1 causes the transmitted zero-length
4839 		 * segment to lie outside the receive window; by the
4840 		 * protocol spec, this requires the correspondent TCP to
4841 		 * respond.
4842 		 */
4843 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4844 		t_template = tcpip_maketemplate(inp);
4845 		if (t_template) {
4846 			tcp_respond(tp, t_template->tt_ipgen,
4847 			    &t_template->tt_t, (struct mbuf *)NULL,
4848 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4849 			free(t_template, M_TEMP);
4850 		}
4851 	}
4852 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4853 	return (1);
4854 dropit:
4855 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4856 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4857 	return (-ETIMEDOUT);	/* tcp_drop() */
4858 }
4859 
4860 /*
4861  * Retransmit helper function, clear up all the ack
4862  * flags and take care of important book keeping.
4863  */
4864 static void
4865 bbr_remxt_tmr(struct tcpcb *tp)
4866 {
4867 	/*
4868 	 * The retransmit timer went off, all sack'd blocks must be
4869 	 * un-acked.
4870 	 */
4871 	struct bbr_sendmap *rsm, *trsm = NULL;
4872 	struct tcp_bbr *bbr;
4873 	uint32_t cts, lost;
4874 
4875 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4876 	cts = tcp_get_usecs(&bbr->rc_tv);
4877 	lost = bbr->r_ctl.rc_lost;
4878 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4879 		bbr_set_state(tp, bbr, 0);
4880 
4881 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4882 		if (rsm->r_flags & BBR_ACKED) {
4883 			uint32_t old_flags;
4884 
4885 			rsm->r_dupack = 0;
4886 			if (rsm->r_in_tmap == 0) {
4887 				/* We must re-add it back to the tlist */
4888 				if (trsm == NULL) {
4889 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4890 				} else {
4891 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4892 				}
4893 				rsm->r_in_tmap = 1;
4894 			}
4895 			old_flags = rsm->r_flags;
4896 			rsm->r_flags |= BBR_RXT_CLEARED;
4897 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4898 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4899 		} else {
4900 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4901 			    (rsm->r_start == tp->snd_una)) {
4902 				/*
4903 				 * Special case for TCP FO. Where
4904 				 * we sent more data beyond the snd_max.
4905 				 * We don't mark that as lost and stop here.
4906 				 */
4907 				break;
4908 			}
4909 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4910 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4911 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4912 			}
4913 			if (bbr_marks_rxt_sack_passed) {
4914 				/*
4915 				 * With this option, we will rack out
4916 				 * in 1ms increments the rest of the packets.
4917 				 */
4918 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4919 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4920 			} else {
4921 				/*
4922 				 * With this option we only mark them lost
4923 				 * and remove all sack'd markings. We will run
4924 				 * another RXT or a TLP. This will cause
4925 				 * us to eventually send more based on what
4926 				 * ack's come in.
4927 				 */
4928 				rsm->r_flags |= BBR_MARKED_LOST;
4929 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4930 				rsm->r_flags &= ~BBR_SACK_PASSED;
4931 			}
4932 		}
4933 		trsm = rsm;
4934 	}
4935 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4936 	/* Clear the count (we just un-acked them) */
4937 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4938 	bbr->rc_tlp_new_data = 0;
4939 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4940 	/* zap the behindness on a rxt */
4941 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4942 	bbr->r_agg_early_set = 0;
4943 	bbr->r_ctl.rc_agg_early = 0;
4944 	bbr->rc_tlp_rtx_out = 0;
4945 	bbr->r_ctl.rc_sacked = 0;
4946 	bbr->r_ctl.rc_sacklast = NULL;
4947 	bbr->r_timer_override = 1;
4948 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4949 }
4950 
4951 /*
4952  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4953  * we will setup to retransmit the lowest seq number outstanding.
4954  */
4955 static int
4956 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4957 {
4958 	struct inpcb *inp = tptoinpcb(tp);
4959 	int32_t rexmt;
4960 	int32_t retval = 0;
4961 	bool isipv6;
4962 
4963 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4964 	if (bbr->rc_all_timers_stopped) {
4965 		return (1);
4966 	}
4967 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4968 	    (tp->snd_una == tp->snd_max)) {
4969 		/* Nothing outstanding .. nothing to do */
4970 		return (0);
4971 	}
4972 	/*
4973 	 * Retransmission timer went off.  Message has not been acked within
4974 	 * retransmit interval.  Back off to a longer retransmit interval
4975 	 * and retransmit one segment.
4976 	 */
4977 	if (ctf_progress_timeout_check(tp, true)) {
4978 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4979 		return (-ETIMEDOUT);	/* tcp_drop() */
4980 	}
4981 	bbr_remxt_tmr(tp);
4982 	if ((bbr->r_ctl.rc_resend == NULL) ||
4983 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4984 		/*
4985 		 * If the rwnd collapsed on
4986 		 * the one we are retransmitting
4987 		 * it does not count against the
4988 		 * rxt count.
4989 		 */
4990 		tp->t_rxtshift++;
4991 	}
4992 	if (tp->t_rxtshift > V_tcp_retries) {
4993 		tp->t_rxtshift = V_tcp_retries;
4994 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
4995 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
4996 		/* XXXGL: previously t_softerror was casted to uint16_t */
4997 		MPASS(tp->t_softerror >= 0);
4998 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
4999 		return (retval);	/* tcp_drop() */
5000 	}
5001 	if (tp->t_state == TCPS_SYN_SENT) {
5002 		/*
5003 		 * If the SYN was retransmitted, indicate CWND to be limited
5004 		 * to 1 segment in cc_conn_init().
5005 		 */
5006 		tp->snd_cwnd = 1;
5007 	} else if (tp->t_rxtshift == 1) {
5008 		/*
5009 		 * first retransmit; record ssthresh and cwnd so they can be
5010 		 * recovered if this turns out to be a "bad" retransmit. A
5011 		 * retransmit is considered "bad" if an ACK for this segment
5012 		 * is received within RTT/2 interval; the assumption here is
5013 		 * that the ACK was already in flight.  See "On Estimating
5014 		 * End-to-End Network Path Properties" by Allman and Paxson
5015 		 * for more details.
5016 		 */
5017 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5018 		if (!IN_RECOVERY(tp->t_flags)) {
5019 			tp->snd_cwnd_prev = tp->snd_cwnd;
5020 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5021 			tp->snd_recover_prev = tp->snd_recover;
5022 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5023 			tp->t_flags |= TF_PREVVALID;
5024 		} else {
5025 			tp->t_flags &= ~TF_PREVVALID;
5026 		}
5027 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5028 	} else {
5029 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5030 		tp->t_flags &= ~TF_PREVVALID;
5031 	}
5032 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5033 	if ((tp->t_state == TCPS_SYN_SENT) ||
5034 	    (tp->t_state == TCPS_SYN_RECEIVED))
5035 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5036 	else
5037 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5038 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5039 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5040 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5041 	/*
5042 	 * We enter the path for PLMTUD if connection is established or, if
5043 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5044 	 * amount of data we send is very small, we could send it in couple
5045 	 * of packets and process straight to FIN. In that case we won't
5046 	 * catch ESTABLISHED state.
5047 	 */
5048 #ifdef INET6
5049 	isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
5050 #else
5051 	isipv6 = false;
5052 #endif
5053 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5054 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5055 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5056 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5057 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5058 		/*
5059 		 * Idea here is that at each stage of mtu probe (usually,
5060 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5061 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5062 		 * should take care of that.
5063 		 */
5064 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5065 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5066 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5067 		    tp->t_rxtshift % 2 == 0)) {
5068 			/*
5069 			 * Enter Path MTU Black-hole Detection mechanism: -
5070 			 * Disable Path MTU Discovery (IP "DF" bit). -
5071 			 * Reduce MTU to lower value than what we negotiated
5072 			 * with peer.
5073 			 */
5074 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5075 				/*
5076 				 * Record that we may have found a black
5077 				 * hole.
5078 				 */
5079 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5080 				/* Keep track of previous MSS. */
5081 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5082 			}
5083 			/*
5084 			 * Reduce the MSS to blackhole value or to the
5085 			 * default in an attempt to retransmit.
5086 			 */
5087 #ifdef INET6
5088 			isipv6 = bbr->r_is_v6;
5089 			if (isipv6 &&
5090 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5091 				/* Use the sysctl tuneable blackhole MSS. */
5092 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5093 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5094 			} else if (isipv6) {
5095 				/* Use the default MSS. */
5096 				tp->t_maxseg = V_tcp_v6mssdflt;
5097 				/*
5098 				 * Disable Path MTU Discovery when we switch
5099 				 * to minmss.
5100 				 */
5101 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5102 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5103 			}
5104 #endif
5105 #if defined(INET6) && defined(INET)
5106 			else
5107 #endif
5108 #ifdef INET
5109 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5110 				/* Use the sysctl tuneable blackhole MSS. */
5111 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5112 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5113 			} else {
5114 				/* Use the default MSS. */
5115 				tp->t_maxseg = V_tcp_mssdflt;
5116 				/*
5117 				 * Disable Path MTU Discovery when we switch
5118 				 * to minmss.
5119 				 */
5120 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5121 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5122 			}
5123 #endif
5124 		} else {
5125 			/*
5126 			 * If further retransmissions are still unsuccessful
5127 			 * with a lowered MTU, maybe this isn't a blackhole
5128 			 * and we restore the previous MSS and blackhole
5129 			 * detection flags. The limit '6' is determined by
5130 			 * giving each probe stage (1448, 1188, 524) 2
5131 			 * chances to recover.
5132 			 */
5133 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5134 			    (tp->t_rxtshift >= 6)) {
5135 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5136 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5137 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5138 				if (tp->t_maxseg < V_tcp_mssdflt) {
5139 					/*
5140 					 * The MSS is so small we should not
5141 					 * process incoming SACK's since we are
5142 					 * subject to attack in such a case.
5143 					 */
5144 					tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
5145 				} else {
5146 					tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
5147 				}
5148 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5149 			}
5150 		}
5151 	}
5152 	/*
5153 	 * Disable RFC1323 and SACK if we haven't got any response to our
5154 	 * third SYN to work-around some broken terminal servers (most of
5155 	 * which have hopefully been retired) that have bad VJ header
5156 	 * compression code which trashes TCP segments containing
5157 	 * unknown-to-them TCP options.
5158 	 */
5159 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5160 	    (tp->t_rxtshift == 3))
5161 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5162 	/*
5163 	 * If we backed off this far, our srtt estimate is probably bogus.
5164 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5165 	 * move the current srtt into rttvar to keep the current retransmit
5166 	 * times until then.
5167 	 */
5168 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5169 #ifdef INET6
5170 		if (bbr->r_is_v6)
5171 			in6_losing(inp);
5172 		else
5173 #endif
5174 			in_losing(inp);
5175 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5176 		tp->t_srtt = 0;
5177 	}
5178 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5179 	tp->snd_recover = tp->snd_max;
5180 	tp->t_flags |= TF_ACKNOW;
5181 	tp->t_rtttime = 0;
5182 
5183 	return (retval);
5184 }
5185 
5186 static int
5187 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5188 {
5189 	int32_t ret = 0;
5190 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5191 
5192 	if (timers == 0) {
5193 		return (0);
5194 	}
5195 	if (tp->t_state == TCPS_LISTEN) {
5196 		/* no timers on listen sockets */
5197 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5198 			return (0);
5199 		return (1);
5200 	}
5201 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5202 		uint32_t left;
5203 
5204 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5205 			ret = -1;
5206 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5207 			return (0);
5208 		}
5209 		if (hpts_calling == 0) {
5210 			ret = -2;
5211 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5212 			return (0);
5213 		}
5214 		/*
5215 		 * Ok our timer went off early and we are not paced false
5216 		 * alarm, go back to sleep.
5217 		 */
5218 		left = bbr->r_ctl.rc_timer_exp - cts;
5219 		ret = -3;
5220 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5221 		tcp_hpts_insert(tp, HPTS_USEC_TO_SLOTS(left));
5222 		return (1);
5223 	}
5224 	bbr->rc_tmr_stopped = 0;
5225 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5226 	if (timers & PACE_TMR_DELACK) {
5227 		ret = bbr_timeout_delack(tp, bbr, cts);
5228 	} else if (timers & PACE_TMR_PERSIT) {
5229 		ret = bbr_timeout_persist(tp, bbr, cts);
5230 	} else if (timers & PACE_TMR_RACK) {
5231 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5232 		ret = bbr_timeout_rack(tp, bbr, cts);
5233 	} else if (timers & PACE_TMR_TLP) {
5234 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5235 		ret = bbr_timeout_tlp(tp, bbr, cts);
5236 	} else if (timers & PACE_TMR_RXT) {
5237 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5238 		ret = bbr_timeout_rxt(tp, bbr, cts);
5239 	} else if (timers & PACE_TMR_KEEP) {
5240 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5241 	}
5242 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5243 	return (ret);
5244 }
5245 
5246 static void
5247 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5248 {
5249 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5250 		uint8_t hpts_removed = 0;
5251 
5252 		if (tcp_in_hpts(bbr->rc_tp) &&
5253 		    (bbr->rc_timer_first == 1)) {
5254 			/*
5255 			 * If we are canceling timer's when we have the
5256 			 * timer ahead of the output being paced. We also
5257 			 * must remove ourselves from the hpts.
5258 			 */
5259 			hpts_removed = 1;
5260 			tcp_hpts_remove(bbr->rc_tp);
5261 			if (bbr->r_ctl.rc_last_delay_val) {
5262 				/* Update the last hptsi delay too */
5263 				uint32_t time_since_send;
5264 
5265 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5266 					time_since_send = cts - bbr->rc_pacer_started;
5267 				else
5268 					time_since_send = 0;
5269 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5270 					/* Cut down our slot time */
5271 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5272 				} else {
5273 					bbr->r_ctl.rc_last_delay_val = 0;
5274 				}
5275 				bbr->rc_pacer_started = cts;
5276 			}
5277 		}
5278 		bbr->rc_timer_first = 0;
5279 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5280 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5281 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5282 	}
5283 }
5284 
5285 static int
5286 bbr_stopall(struct tcpcb *tp)
5287 {
5288 	struct tcp_bbr *bbr;
5289 
5290 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5291 	bbr->rc_all_timers_stopped = 1;
5292 
5293 	tcp_hpts_remove(tp);
5294 
5295 	return (0);
5296 }
5297 
5298 static uint32_t
5299 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5300 {
5301 	struct bbr_sendmap *rsm;
5302 
5303 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5304 	if ((rsm == NULL) || (u_rsm == rsm))
5305 		return (cts);
5306 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5307 }
5308 
5309 static void
5310 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5311      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5312 {
5313 	int32_t idx;
5314 
5315 	rsm->r_rtr_cnt++;
5316 	rsm->r_dupack = 0;
5317 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5318 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5319 		rsm->r_flags |= BBR_OVERMAX;
5320 	}
5321 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5322 		/* Take off the collapsed flag at rxt */
5323 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5324 	}
5325 	if (rsm->r_flags & BBR_MARKED_LOST) {
5326 		/* We have retransmitted, its no longer lost */
5327 		rsm->r_flags &= ~BBR_MARKED_LOST;
5328 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5329 	}
5330 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5331 		/*
5332 		 * We hit a RXT timer on it and
5333 		 * we cleared the "acked" flag.
5334 		 * We now have it going back into
5335 		 * flight, we can remove the cleared
5336 		 * flag and possibly do accounting on
5337 		 * this piece.
5338 		 */
5339 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5340 	}
5341 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5342 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5343 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5344 	}
5345 	idx = rsm->r_rtr_cnt - 1;
5346 	rsm->r_tim_lastsent[idx] = cts;
5347 	rsm->r_pacing_delay = pacing_time;
5348 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5349 	rsm->r_ts_valid = bbr->rc_ts_valid;
5350 	if (bbr->rc_ts_valid)
5351 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5352 	if (bbr->r_ctl.r_app_limited_until)
5353 		rsm->r_app_limited = 1;
5354 	else
5355 		rsm->r_app_limited = 0;
5356 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5357 		rsm->r_bbr_state = bbr_state_val(bbr);
5358 	else
5359 		rsm->r_bbr_state = 8;
5360 	if (rsm->r_flags & BBR_ACKED) {
5361 		/* Problably MTU discovery messing with us */
5362 		uint32_t old_flags;
5363 
5364 		old_flags = rsm->r_flags;
5365 		rsm->r_flags &= ~BBR_ACKED;
5366 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5367 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5368 		if (bbr->r_ctl.rc_sacked == 0)
5369 			bbr->r_ctl.rc_sacklast = NULL;
5370 	}
5371 	if (rsm->r_in_tmap) {
5372 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5373 	}
5374 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5375 	rsm->r_in_tmap = 1;
5376 	if (rsm->r_flags & BBR_SACK_PASSED) {
5377 		/* We have retransmitted due to the SACK pass */
5378 		rsm->r_flags &= ~BBR_SACK_PASSED;
5379 		rsm->r_flags |= BBR_WAS_SACKPASS;
5380 	}
5381 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5382 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5383 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5384 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5385 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5386 		rsm->r_is_gain = 1;
5387 		rsm->r_is_drain = 0;
5388 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5389 		rsm->r_is_drain = 1;
5390 		rsm->r_is_gain = 0;
5391 	} else {
5392 		rsm->r_is_drain = 0;
5393 		rsm->r_is_gain = 0;
5394 	}
5395 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5396 }
5397 
5398 /*
5399  * Returns 0, or the sequence where we stopped
5400  * updating. We also update the lenp to be the amount
5401  * of data left.
5402  */
5403 
5404 static uint32_t
5405 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5406     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5407 {
5408 	/*
5409 	 * We (re-)transmitted starting at rsm->r_start for some length
5410 	 * (possibly less than r_end.
5411 	 */
5412 	struct bbr_sendmap *nrsm;
5413 	uint32_t c_end;
5414 	int32_t len;
5415 
5416 	len = *lenp;
5417 	c_end = rsm->r_start + len;
5418 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5419 		/*
5420 		 * We retransmitted the whole piece or more than the whole
5421 		 * slopping into the next rsm.
5422 		 */
5423 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5424 		if (c_end == rsm->r_end) {
5425 			*lenp = 0;
5426 			return (0);
5427 		} else {
5428 			int32_t act_len;
5429 
5430 			/* Hangs over the end return whats left */
5431 			act_len = rsm->r_end - rsm->r_start;
5432 			*lenp = (len - act_len);
5433 			return (rsm->r_end);
5434 		}
5435 		/* We don't get out of this block. */
5436 	}
5437 	/*
5438 	 * Here we retransmitted less than the whole thing which means we
5439 	 * have to split this into what was transmitted and what was not.
5440 	 */
5441 	nrsm = bbr_alloc_full_limit(bbr);
5442 	if (nrsm == NULL) {
5443 		*lenp = 0;
5444 		return (0);
5445 	}
5446 	/*
5447 	 * So here we are going to take the original rsm and make it what we
5448 	 * retransmitted. nrsm will be the tail portion we did not
5449 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5450 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5451 	 * 1, 6 and the new piece will be 6, 11.
5452 	 */
5453 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5454 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5455 	nrsm->r_dupack = 0;
5456 	if (rsm->r_in_tmap) {
5457 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5458 		nrsm->r_in_tmap = 1;
5459 	}
5460 	rsm->r_flags &= (~BBR_HAS_FIN);
5461 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5462 	*lenp = 0;
5463 	return (0);
5464 }
5465 
5466 static uint64_t
5467 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5468 {
5469 	uint64_t bw;
5470 
5471 	bw = bbr_get_bw(bbr);
5472 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5473 	bw /= (uint64_t)BBR_UNIT;
5474 	return(bw);
5475 }
5476 
5477 static void
5478 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5479 		       uint64_t act_rate, uint64_t rate_wanted)
5480 {
5481 	/*
5482 	 * We could not get a full gains worth
5483 	 * of rate.
5484 	 */
5485 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5486 		/* we can't even get the real rate */
5487 		uint64_t red;
5488 
5489 		bbr->skip_gain = 1;
5490 		bbr->gain_is_limited = 0;
5491 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5492 		if (red)
5493 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5494 	} else {
5495 		/* We can use a lower gain */
5496 		bbr->skip_gain = 0;
5497 		bbr->gain_is_limited = 1;
5498 	}
5499 }
5500 
5501 static void
5502 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5503 {
5504 	const struct tcp_hwrate_limit_table *nrte;
5505 	int error, rate = -1;
5506 
5507 	if (bbr->r_ctl.crte == NULL)
5508 		return;
5509 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5510 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5511 		/* Lost our routes? */
5512 		/* Clear the way for a re-attempt */
5513 		bbr->bbr_attempt_hdwr_pace = 0;
5514 lost_rate:
5515 		bbr->gain_is_limited = 0;
5516 		bbr->skip_gain = 0;
5517 		bbr->bbr_hdrw_pacing = 0;
5518 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5519 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5520 		tcp_bbr_tso_size_check(bbr, cts);
5521 		return;
5522 	}
5523 	rate = bbr_get_hardware_rate(bbr);
5524 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5525 				   bbr->rc_tp,
5526 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5527 				   rate,
5528 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5529 				   &error, NULL);
5530 	if (nrte == NULL) {
5531 		goto lost_rate;
5532 	}
5533 	if (nrte != bbr->r_ctl.crte) {
5534 		bbr->r_ctl.crte = nrte;
5535 		if (error == 0)  {
5536 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5537 			if (bbr->r_ctl.crte->rate < rate) {
5538 				/* We have a problem */
5539 				bbr_setup_less_of_rate(bbr, cts,
5540 						       bbr->r_ctl.crte->rate, rate);
5541 			} else {
5542 				/* We are good */
5543 				bbr->gain_is_limited = 0;
5544 				bbr->skip_gain = 0;
5545 			}
5546 		} else {
5547 			/* A failure should release the tag */
5548 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5549 			bbr->gain_is_limited = 0;
5550 			bbr->skip_gain = 0;
5551 			bbr->bbr_hdrw_pacing = 0;
5552 		}
5553 		bbr_type_log_hdwr_pacing(bbr,
5554 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5555 					 rate,
5556 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5557 					 __LINE__,
5558 					 cts,
5559 					 error);
5560 	}
5561 }
5562 
5563 static void
5564 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5565 {
5566 	/*
5567 	 * If we have hardware pacing support
5568 	 * we need to factor that in for our
5569 	 * TSO size.
5570 	 */
5571 	const struct tcp_hwrate_limit_table *rlp;
5572 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5573 
5574 	if ((bbr->bbr_hdrw_pacing == 0) ||
5575 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5576 	    (bbr->r_ctl.crte == NULL))
5577 		return;
5578 	if (bbr->hw_pacing_set == 0) {
5579 		/* Not yet by the hdwr pacing count delay */
5580 		return;
5581 	}
5582 	if (bbr_hdwr_pace_adjust == 0) {
5583 		/* No adjustment */
5584 		return;
5585 	}
5586 	rlp = bbr->r_ctl.crte;
5587 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5588 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5589 	else
5590 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5591 	/*
5592 	 * So lets first get the
5593 	 * time we will take between
5594 	 * TSO sized sends currently without
5595 	 * hardware help.
5596 	 */
5597 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5598 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5599 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5600 	hdwr_delay *= rlp->time_between;
5601 	if (cur_delay > hdwr_delay)
5602 		delta = cur_delay - hdwr_delay;
5603 	else
5604 		delta = 0;
5605 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5606 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5607 			     1);
5608 	if (delta &&
5609 	    (delta < (max(rlp->time_between,
5610 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5611 		/*
5612 		 * Now lets divide by the pacing
5613 		 * time between each segment the
5614 		 * hardware sends rounding up and
5615 		 * derive a bytes from that. We multiply
5616 		 * that by bbr_hdwr_pace_adjust to get
5617 		 * more bang for our buck.
5618 		 *
5619 		 * The goal is to have the software pacer
5620 		 * waiting no more than an additional
5621 		 * pacing delay if we can (without the
5622 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5623 		 */
5624 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5625 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5626 		seg_sz *= bbr_hdwr_pace_adjust;
5627 		if (bbr_hdwr_pace_floor &&
5628 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5629 			/* Currently hardware paces
5630 			 * out rs_min_seg segments at a time.
5631 			 * We need to make sure we always send at least
5632 			 * a full burst of bbr_hdwr_pace_floor down.
5633 			 */
5634 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5635 		}
5636 		seg_sz *= maxseg;
5637 	} else if (delta == 0) {
5638 		/*
5639 		 * The highest pacing rate is
5640 		 * above our b/w gained. This means
5641 		 * we probably are going quite fast at
5642 		 * the hardware highest rate. Lets just multiply
5643 		 * the calculated TSO size by the
5644 		 * multiplier factor (its probably
5645 		 * 4 segments in the default config for
5646 		 * mlx).
5647 		 */
5648 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5649 		if (bbr_hdwr_pace_floor &&
5650 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5651 			/* Currently hardware paces
5652 			 * out rs_min_seg segments at a time.
5653 			 * We need to make sure we always send at least
5654 			 * a full burst of bbr_hdwr_pace_floor down.
5655 			 */
5656 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5657 		}
5658 	} else {
5659 		/*
5660 		 * The pacing time difference is so
5661 		 * big that the hardware will
5662 		 * pace out more rapidly then we
5663 		 * really want and then we
5664 		 * will have a long delay. Lets just keep
5665 		 * the same TSO size so its as if
5666 		 * we were not using hdwr pacing (we
5667 		 * just gain a bit of spacing from the
5668 		 * hardware if seg_sz > 1).
5669 		 */
5670 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5671 	}
5672 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5673 		new_tso = seg_sz;
5674 	else
5675 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5676 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5677 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5678 
5679 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5680 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5681 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5682 	}
5683 }
5684 
5685 static void
5686 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5687 {
5688 	uint64_t bw;
5689 	uint32_t old_tso = 0, new_tso;
5690 	uint32_t maxseg, bytes;
5691 	uint32_t tls_seg=0;
5692 	/*
5693 	 * Google/linux uses the following algorithm to determine
5694 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5695 	 *
5696 	 *  bytes = bw_in_bytes_per_second / 1000
5697 	 *  bytes = min(bytes, 64k)
5698 	 *  tso_segs = bytes / MSS
5699 	 *  if (bw < 1.2Mbs)
5700 	 *      min_tso_segs = 1
5701 	 *  else
5702 	 *	min_tso_segs = 2
5703 	 * tso_segs = max(tso_segs, min_tso_segs)
5704 	 *
5705 	 * * Note apply a device specific limit (we apply this in the
5706 	 *   tcp_m_copym).
5707 	 * Note that before the initial measurement is made google bursts out
5708 	 * a full iwnd just like new-reno/cubic.
5709 	 *
5710 	 * We do not use this algorithm. Instead we
5711 	 * use a two phased approach:
5712 	 *
5713 	 *  if ( bw <= per-tcb-cross-over)
5714 	 *     goal_tso =  calculate how much with this bw we
5715 	 *                 can send in goal-time seconds.
5716 	 *     if (goal_tso > mss)
5717 	 *         seg = goal_tso / mss
5718 	 *         tso = seg * mss
5719 	 *     else
5720 	 *         tso = mss
5721 	 *     if (tso > per-tcb-max)
5722 	 *         tso = per-tcb-max
5723 	 *  else if ( bw > 512Mbps)
5724 	 *     tso = max-tso (64k/mss)
5725 	 *  else
5726 	 *     goal_tso = bw / per-tcb-divsor
5727 	 *     seg = (goal_tso + mss-1)/mss
5728 	 *     tso = seg * mss
5729 	 *
5730 	 * if (tso < per-tcb-floor)
5731 	 *    tso = per-tcb-floor
5732 	 * if (tso > per-tcb-utter_max)
5733 	 *    tso = per-tcb-utter_max
5734 	 *
5735 	 * Note the default per-tcb-divisor is 1000 (same as google).
5736 	 * the goal cross over is 30Mbps however. To recreate googles
5737 	 * algorithm you need to set:
5738 	 *
5739 	 * cross-over = 23,168,000 bps
5740 	 * goal-time = 18000
5741 	 * per-tcb-max = 2
5742 	 * per-tcb-divisor = 1000
5743 	 * per-tcb-floor = 1
5744 	 *
5745 	 * This will get you "google bbr" behavior with respect to tso size.
5746 	 *
5747 	 * Note we do set anything TSO size until we are past the initial
5748 	 * window. Before that we gnerally use either a single MSS
5749 	 * or we use the full IW size (so we burst a IW at a time)
5750 	 */
5751 
5752 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5753 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5754 	} else {
5755 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5756 	}
5757 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5758 	if (bbr->rc_past_init_win == 0) {
5759 		/*
5760 		 * Not enough data has been acknowledged to make a
5761 		 * judgement. Set up the initial TSO based on if we
5762 		 * are sending a full IW at once or not.
5763 		 */
5764 		if (bbr->rc_use_google)
5765 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5766 		else if (bbr->bbr_init_win_cheat)
5767 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5768 		else
5769 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5770 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5771 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5772 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5773 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5774 		}
5775 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5776 			bbr_adjust_for_hw_pacing(bbr, cts);
5777 		return;
5778 	}
5779 	/**
5780 	 * Now lets set the TSO goal based on our delivery rate in
5781 	 * bytes per second. Note we only do this if
5782 	 * we have acked at least the initial cwnd worth of data.
5783 	 */
5784 	bw = bbr_get_bw(bbr);
5785 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5786 	     (bbr->rc_use_google == 0)) {
5787 		/* We clamp to one MSS in recovery */
5788 		new_tso = maxseg;
5789 	} else if (bbr->rc_use_google) {
5790 		int min_tso_segs;
5791 
5792 		/* Google considers the gain too */
5793 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5794 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5795 			bw /= BBR_UNIT;
5796 		}
5797 		bytes = bw / 1024;
5798 		if (bytes > (64 * 1024))
5799 			bytes = 64 * 1024;
5800 		new_tso = bytes / maxseg;
5801 		if (bw < ONE_POINT_TWO_MEG)
5802 			min_tso_segs = 1;
5803 		else
5804 			min_tso_segs = 2;
5805 		if (new_tso < min_tso_segs)
5806 			new_tso = min_tso_segs;
5807 		new_tso *= maxseg;
5808 	} else if (bbr->rc_no_pacing) {
5809 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5810 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5811 		/*
5812 		 * Calculate the worse case b/w TSO if we are inserting no
5813 		 * more than a delay_target number of TSO's.
5814 		 */
5815 		uint32_t tso_len, min_tso;
5816 
5817 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5818 		if (tso_len > maxseg) {
5819 			new_tso = tso_len / maxseg;
5820 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5821 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5822 			new_tso *= maxseg;
5823 		} else {
5824 			/*
5825 			 * less than a full sized frame yikes.. long rtt or
5826 			 * low bw?
5827 			 */
5828 			min_tso = bbr_minseg(bbr);
5829 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5830 				new_tso = rounddown(tso_len, min_tso);
5831 			else
5832 				new_tso = min_tso;
5833 		}
5834 	} else if (bw > FIVETWELVE_MBPS) {
5835 		/*
5836 		 * This guy is so fast b/w wise that we can TSO as large as
5837 		 * possible of segments that the NIC will allow.
5838 		 */
5839 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5840 	} else {
5841 		/*
5842 		 * This formula is based on attempting to send a segment or
5843 		 * more every bbr_hptsi_per_second. The default is 1000
5844 		 * which means you are targeting what you can send every 1ms
5845 		 * based on the peers bw.
5846 		 *
5847 		 * If the number drops to say 500, then you are looking more
5848 		 * at 2ms and you will raise how much we send in a single
5849 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5850 		 * trade off of course is you will send more at once and
5851 		 * thus tend to clump up the sends into larger "bursts"
5852 		 * building a queue.
5853 		 */
5854 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5855 		new_tso = roundup(bw, (uint64_t)maxseg);
5856 		/*
5857 		 * Gate the floor to match what our lower than 48Mbps
5858 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5859 		 * becomes the floor for this calculation.
5860 		 */
5861 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5862 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5863 	}
5864 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5865 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5866 	if (new_tso > PACE_MAX_IP_BYTES)
5867 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5868 	/* Enforce an utter maximum. */
5869 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5870 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5871 	}
5872 	if (old_tso != new_tso) {
5873 		/* Only log changes */
5874 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5875 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5876 	}
5877 	/* We have hardware pacing! */
5878 	bbr_adjust_for_hw_pacing(bbr, cts);
5879 }
5880 
5881 static void
5882 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5883     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5884     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5885     struct sockbuf *sb)
5886 {
5887 
5888 	struct bbr_sendmap *rsm, *nrsm;
5889 	register uint32_t snd_max, snd_una;
5890 	uint32_t pacing_time;
5891 	/*
5892 	 * Add to the RACK log of packets in flight or retransmitted. If
5893 	 * there is a TS option we will use the TS echoed, if not we will
5894 	 * grab a TS.
5895 	 *
5896 	 * Retransmissions will increment the count and move the ts to its
5897 	 * proper place. Note that if options do not include TS's then we
5898 	 * won't be able to effectively use the ACK for an RTT on a retran.
5899 	 *
5900 	 * Notes about r_start and r_end. Lets consider a send starting at
5901 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5902 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5903 	 * This means that r_end is actually the first sequence for the next
5904 	 * slot (11).
5905 	 *
5906 	 */
5907 	INP_WLOCK_ASSERT(tptoinpcb(tp));
5908 	if (err) {
5909 		/*
5910 		 * We don't log errors -- we could but snd_max does not
5911 		 * advance in this case either.
5912 		 */
5913 		return;
5914 	}
5915 	if (th_flags & TH_RST) {
5916 		/*
5917 		 * We don't log resets and we return immediately from
5918 		 * sending
5919 		 */
5920 		*abandon = 1;
5921 		return;
5922 	}
5923 	snd_una = tp->snd_una;
5924 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5925 		/*
5926 		 * The call to bbr_log_output is made before bumping
5927 		 * snd_max. This means we can record one extra byte on a SYN
5928 		 * or FIN if seq_out is adding more on and a FIN is present
5929 		 * (and we are not resending).
5930 		 */
5931 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5932 			len++;
5933 		if (th_flags & TH_FIN)
5934 			len++;
5935 	}
5936 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5937 		/* Are sending an old segment to induce an ack (keep-alive)? */
5938 		return;
5939 	}
5940 	if (SEQ_LT(seq_out, snd_una)) {
5941 		/* huh? should we panic? */
5942 		uint32_t end;
5943 
5944 		end = seq_out + len;
5945 		seq_out = snd_una;
5946 		len = end - seq_out;
5947 	}
5948 	snd_max = tp->snd_max;
5949 	if (len == 0) {
5950 		/* We don't log zero window probes */
5951 		return;
5952 	}
5953 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5954 	/* First question is it a retransmission? */
5955 	if (seq_out == snd_max) {
5956 again:
5957 		rsm = bbr_alloc(bbr);
5958 		if (rsm == NULL) {
5959 			return;
5960 		}
5961 		rsm->r_flags = 0;
5962 		if (th_flags & TH_SYN)
5963 			rsm->r_flags |= BBR_HAS_SYN;
5964 		if (th_flags & TH_FIN)
5965 			rsm->r_flags |= BBR_HAS_FIN;
5966 		rsm->r_tim_lastsent[0] = cts;
5967 		rsm->r_rtr_cnt = 1;
5968 		rsm->r_rtr_bytes = 0;
5969 		rsm->r_start = seq_out;
5970 		rsm->r_end = rsm->r_start + len;
5971 		rsm->r_dupack = 0;
5972 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5973 		rsm->r_pacing_delay = pacing_time;
5974 		rsm->r_ts_valid = bbr->rc_ts_valid;
5975 		if (bbr->rc_ts_valid)
5976 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5977 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
5978 		if (bbr->r_ctl.r_app_limited_until)
5979 			rsm->r_app_limited = 1;
5980 		else
5981 			rsm->r_app_limited = 0;
5982 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5983 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5984 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5985 		/*
5986 		 * Here we must also add in this rsm since snd_max
5987 		 * is updated after we return from a new send.
5988 		 */
5989 		rsm->r_flight_at_send += len;
5990 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
5991 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5992 		rsm->r_in_tmap = 1;
5993 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5994 			rsm->r_bbr_state = bbr_state_val(bbr);
5995 		else
5996 			rsm->r_bbr_state = 8;
5997 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5998 			rsm->r_is_gain = 1;
5999 			rsm->r_is_drain = 0;
6000 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6001 			rsm->r_is_drain = 1;
6002 			rsm->r_is_gain = 0;
6003 		} else {
6004 			rsm->r_is_drain = 0;
6005 			rsm->r_is_gain = 0;
6006 		}
6007 		return;
6008 	}
6009 	/*
6010 	 * If we reach here its a retransmission and we need to find it.
6011 	 */
6012 more:
6013 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6014 		rsm = hintrsm;
6015 		hintrsm = NULL;
6016 	} else if (bbr->r_ctl.rc_next) {
6017 		/* We have a hint from a previous run */
6018 		rsm = bbr->r_ctl.rc_next;
6019 	} else {
6020 		/* No hints sorry */
6021 		rsm = NULL;
6022 	}
6023 	if ((rsm) && (rsm->r_start == seq_out)) {
6024 		/*
6025 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6026 		 * likely case.
6027 		 */
6028 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6029 		if (len == 0) {
6030 			return;
6031 		} else {
6032 			goto more;
6033 		}
6034 	}
6035 	/* Ok it was not the last pointer go through it the hard way. */
6036 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6037 		if (rsm->r_start == seq_out) {
6038 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6039 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6040 			if (len == 0) {
6041 				return;
6042 			} else {
6043 				continue;
6044 			}
6045 		}
6046 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6047 			/* Transmitted within this piece */
6048 			/*
6049 			 * Ok we must split off the front and then let the
6050 			 * update do the rest
6051 			 */
6052 			nrsm = bbr_alloc_full_limit(bbr);
6053 			if (nrsm == NULL) {
6054 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6055 				return;
6056 			}
6057 			/*
6058 			 * copy rsm to nrsm and then trim the front of rsm
6059 			 * to not include this part.
6060 			 */
6061 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6062 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6063 			if (rsm->r_in_tmap) {
6064 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6065 				nrsm->r_in_tmap = 1;
6066 			}
6067 			rsm->r_flags &= (~BBR_HAS_FIN);
6068 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6069 			if (len == 0) {
6070 				return;
6071 			}
6072 		}
6073 	}
6074 	/*
6075 	 * Hmm not found in map did they retransmit both old and on into the
6076 	 * new?
6077 	 */
6078 	if (seq_out == tp->snd_max) {
6079 		goto again;
6080 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6081 #ifdef BBR_INVARIANTS
6082 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6083 		    seq_out, len, tp->snd_una, tp->snd_max);
6084 		printf("Starting Dump of all rack entries\n");
6085 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6086 			printf("rsm:%p start:%u end:%u\n",
6087 			    rsm, rsm->r_start, rsm->r_end);
6088 		}
6089 		printf("Dump complete\n");
6090 		panic("seq_out not found rack:%p tp:%p",
6091 		    bbr, tp);
6092 #endif
6093 	} else {
6094 #ifdef BBR_INVARIANTS
6095 		/*
6096 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6097 		 * flag)
6098 		 */
6099 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6100 		    seq_out, len, tp->snd_max, tp);
6101 #endif
6102 	}
6103 }
6104 
6105 static void
6106 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6107 {
6108 	/*
6109 	 * Collapse timeout back the cum-ack moved.
6110 	 */
6111 	tp->t_rxtshift = 0;
6112 	tp->t_softerror = 0;
6113 }
6114 
6115 static void
6116 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6117 {
6118 	bbr->rtt_valid = 1;
6119 	bbr->r_ctl.cur_rtt = rtt_usecs;
6120 	bbr->r_ctl.ts_in = tsin;
6121 	if (rsm_send_time)
6122 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6123 }
6124 
6125 static void
6126 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6127 {
6128 	/**
6129 	 * We have in our bbr control:
6130 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6131 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6132 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6133 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6134 	 *
6135 	 * Now we can calculate the time between the sends by doing:
6136 	 *
6137 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6138 	 *
6139 	 * And the peer's time between receiving them by doing:
6140 	 *
6141 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6142 	 *
6143 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6144 	 * We also may find that we can't use the timestamps if say we see
6145 	 * that the peer_delta indicates that though we may have taken 10ms to
6146 	 * pace out the data, it only saw 1ms between the two packets. This would
6147 	 * indicate that somewhere on the path is a batching entity that is giving
6148 	 * out time-slices of the actual b/w. This would mean we could not use
6149 	 * reliably the peers timestamps.
6150 	 *
6151 	 * We expect delta > peer_delta initially. Until we figure out the
6152 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6153 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6154 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6155 	 * put a 1 there. If the value is faster then ours, we will disable the
6156 	 * use of timestamps (though we could revist this later if we find it to be not
6157 	 * just an isolated one or two flows)).
6158 	 *
6159 	 * To detect the batching middle boxes we will come up with our compensation and
6160 	 * if with it in place, we find the peer is drastically off (by some margin) in
6161 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6162 	 *
6163 	 */
6164 	uint64_t delta, peer_delta, delta_up;
6165 
6166 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6167 	if (delta < bbr_min_usec_delta) {
6168 		/*
6169 		 * Have not seen a min amount of time
6170 		 * between our send times so we can
6171 		 * make a determination of the timestamp
6172 		 * yet.
6173 		 */
6174 		return;
6175 	}
6176 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6177 	if (peer_delta < bbr_min_peer_delta) {
6178 		/*
6179 		 * We may have enough in the form of
6180 		 * our delta but the peers number
6181 		 * has not changed that much. It could
6182 		 * be its clock ratio is such that
6183 		 * we need more data (10ms tick) or
6184 		 * there may be other compression scenarios
6185 		 * going on. In any event we need the
6186 		 * spread to be larger.
6187 		 */
6188 		return;
6189 	}
6190 	/* Ok lets first see which way our delta is going */
6191 	if (peer_delta > delta) {
6192 		/* Very unlikely, the peer without
6193 		 * compensation shows that it saw
6194 		 * the two sends arrive further apart
6195 		 * then we saw then in micro-seconds.
6196 		 */
6197 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6198 			/* well it looks like the peer is a micro-second clock. */
6199 			bbr->rc_ts_clock_set = 1;
6200 			bbr->r_ctl.bbr_peer_tsratio = 1;
6201 		} else {
6202 			bbr->rc_ts_cant_be_used = 1;
6203 			bbr->rc_ts_clock_set = 1;
6204 		}
6205 		return;
6206 	}
6207 	/* Ok we know that the peer_delta is smaller than our send distance */
6208 	bbr->rc_ts_clock_set = 1;
6209 	/* First question is it within the percentage that they are using usec time? */
6210 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6211 	if ((peer_delta + delta_up) >= delta) {
6212 		/* Its a usec clock */
6213 		bbr->r_ctl.bbr_peer_tsratio = 1;
6214 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6215 		return;
6216 	}
6217 	/* Ok if not usec, what about 10usec (though unlikely)? */
6218 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6219 	if (((peer_delta * 10) + delta_up) >= delta) {
6220 		bbr->r_ctl.bbr_peer_tsratio = 10;
6221 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6222 		return;
6223 	}
6224 	/* And what about 100usec (though again unlikely)? */
6225 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6226 	if (((peer_delta * 100) + delta_up) >= delta) {
6227 		bbr->r_ctl.bbr_peer_tsratio = 100;
6228 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6229 		return;
6230 	}
6231 	/* And how about 1 msec (the most likely one)? */
6232 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6233 	if (((peer_delta * 1000) + delta_up) >= delta) {
6234 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6235 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6236 		return;
6237 	}
6238 	/* Ok if not msec could it be 10 msec? */
6239 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6240 	if (((peer_delta * 10000) + delta_up) >= delta) {
6241 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6242 		return;
6243 	}
6244 	/* If we fall down here the clock tick so slowly we can't use it */
6245 	bbr->rc_ts_cant_be_used = 1;
6246 	bbr->r_ctl.bbr_peer_tsratio = 0;
6247 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6248 }
6249 
6250 /*
6251  * Collect new round-trip time estimate
6252  * and update averages and current timeout.
6253  */
6254 static void
6255 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6256 {
6257 	int32_t delta;
6258 	uint32_t rtt, tsin;
6259 	int32_t rtt_ticks;
6260 
6261 	if (bbr->rtt_valid == 0)
6262 		/* No valid sample */
6263 		return;
6264 
6265 	rtt = bbr->r_ctl.cur_rtt;
6266 	tsin = bbr->r_ctl.ts_in;
6267 	if (bbr->rc_prtt_set_ts) {
6268 		/*
6269 		 * We are to force feed the rttProp filter due
6270 		 * to an entry into PROBE_RTT. This assures
6271 		 * that the times are sync'd between when we
6272 		 * go into PROBE_RTT and the filter expiration.
6273 		 *
6274 		 * Google does not use a true filter, so they do
6275 		 * this implicitly since they only keep one value
6276 		 * and when they enter probe-rtt they update the
6277 		 * value to the newest rtt.
6278 		 */
6279 		uint32_t rtt_prop;
6280 
6281 		bbr->rc_prtt_set_ts = 0;
6282 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6283 		if (rtt > rtt_prop)
6284 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6285 		else
6286 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6287 	}
6288 #ifdef STATS
6289 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_PATHRTT, imax(0, rtt));
6290 #endif
6291 	if (bbr->rc_ack_was_delayed)
6292 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6293 
6294 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6295 		bbr->r_ctl.rc_lowest_rtt = rtt;
6296 	bbr_log_rtt_sample(bbr, rtt, tsin);
6297 	if (bbr->r_init_rtt) {
6298 		/*
6299 		 * The initial rtt is not-trusted, nuke it and lets get
6300 		 * our first valid measurement in.
6301 		 */
6302 		bbr->r_init_rtt = 0;
6303 		tp->t_srtt = 0;
6304 	}
6305 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6306 		/*
6307 		 * So we have not yet figured out
6308 		 * what the peers TSTMP value is
6309 		 * in (most likely ms). We need a
6310 		 * series of cum-ack's to determine
6311 		 * this reliably.
6312 		 */
6313 		if (bbr->rc_ack_is_cumack) {
6314 			if (bbr->rc_ts_data_set) {
6315 				/* Lets attempt to determine the timestamp granularity. */
6316 				bbr_make_timestamp_determination(bbr);
6317 			} else {
6318 				bbr->rc_ts_data_set = 1;
6319 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6320 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6321 			}
6322 		} else {
6323 			/*
6324 			 * We have to have consecutive acks
6325 			 * reset any "filled" state to none.
6326 			 */
6327 			bbr->rc_ts_data_set = 0;
6328 		}
6329 	}
6330 	/* Round it up */
6331 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6332 	if (rtt_ticks == 0)
6333 		rtt_ticks = 1;
6334 	if (tp->t_srtt != 0) {
6335 		/*
6336 		 * srtt is stored as fixed point with 5 bits after the
6337 		 * binary point (i.e., scaled by 8).  The following magic is
6338 		 * equivalent to the smoothing algorithm in rfc793 with an
6339 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6340 		 * Adjust rtt to origin 0.
6341 		 */
6342 
6343 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6344 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6345 
6346 		tp->t_srtt += delta;
6347 		if (tp->t_srtt <= 0)
6348 			tp->t_srtt = 1;
6349 
6350 		/*
6351 		 * We accumulate a smoothed rtt variance (actually, a
6352 		 * smoothed mean difference), then set the retransmit timer
6353 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6354 		 * is stored as fixed point with 4 bits after the binary
6355 		 * point (scaled by 16).  The following is equivalent to
6356 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6357 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6358 		 * wired-in beta.
6359 		 */
6360 		if (delta < 0)
6361 			delta = -delta;
6362 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6363 		tp->t_rttvar += delta;
6364 		if (tp->t_rttvar <= 0)
6365 			tp->t_rttvar = 1;
6366 	} else {
6367 		/*
6368 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6369 		 * variance to half the rtt (so our first retransmit happens
6370 		 * at 3*rtt).
6371 		 */
6372 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6373 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6374 	}
6375 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6376 	if (tp->t_rttupdated < UCHAR_MAX)
6377 		tp->t_rttupdated++;
6378 #ifdef STATS
6379 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6380 #endif
6381 	/*
6382 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6383 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6384 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6385 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6386 	 * uncertainty in the firing of the timer.  The bias will give us
6387 	 * exactly the 1.5 tick we need.  But, because the bias is
6388 	 * statistical, we have to test that we don't drop below the minimum
6389 	 * feasible timer (which is 2 ticks).
6390 	 */
6391 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6392 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6393 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6394 
6395 	/*
6396 	 * We received an ack for a packet that wasn't retransmitted; it is
6397 	 * probably safe to discard any error indications we've received
6398 	 * recently.  This isn't quite right, but close enough for now (a
6399 	 * route might have failed after we sent a segment, and the return
6400 	 * path might not be symmetrical).
6401 	 */
6402 	tp->t_softerror = 0;
6403 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6404 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6405 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6406 }
6407 
6408 static void
6409 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6410 {
6411 	bbr->r_ctl.rc_rtt_shrinks = cts;
6412 	if (bbr_can_force_probertt &&
6413 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6414 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6415 		/*
6416 		 * We should enter probe-rtt its been too long
6417 		 * since we have been there.
6418 		 */
6419 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6420 	} else
6421 		bbr_check_probe_rtt_limits(bbr, cts);
6422 }
6423 
6424 static void
6425 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6426 {
6427 	uint64_t orig_bw;
6428 
6429 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6430 		/* We never apply a zero measurement */
6431 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6432 				    0, 0, 0, 0, 0, 0);
6433 		return;
6434 	}
6435 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6436 		bbr->r_ctl.r_measurement_count++;
6437 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6438 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6439 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6440 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6441 			    0, 0, 0, 0, 0, 0);
6442 	if (orig_bw &&
6443 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6444 		if (bbr->bbr_hdrw_pacing) {
6445 			/*
6446 			 * Apply a new rate to the hardware
6447 			 * possibly.
6448 			 */
6449 			bbr_update_hardware_pacing_rate(bbr, cts);
6450 		}
6451 		bbr_set_state_target(bbr, __LINE__);
6452 		tcp_bbr_tso_size_check(bbr, cts);
6453 		if (bbr->r_recovery_bw)  {
6454 			bbr_setup_red_bw(bbr, cts);
6455 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6456 		}
6457 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6458 		tcp_bbr_tso_size_check(bbr, cts);
6459 }
6460 
6461 static void
6462 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6463 {
6464 	if (bbr->rc_in_persist == 0) {
6465 		/* We log only when not in persist */
6466 		/* Translate to a Bytes Per Second */
6467 		uint64_t tim, bw, ts_diff, ts_bw;
6468 		uint32_t delivered;
6469 
6470 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6471 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6472 		else
6473 			tim = 1;
6474 		/*
6475 		 * Now that we have processed the tim (skipping the sample
6476 		 * or possibly updating the time, go ahead and
6477 		 * calculate the cdr.
6478 		 */
6479 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6480 		bw = (uint64_t)delivered;
6481 		bw *= (uint64_t)USECS_IN_SECOND;
6482 		bw /= tim;
6483 		if (bw == 0) {
6484 			/* We must have a calculatable amount */
6485 			return;
6486 		}
6487 		/*
6488 		 * If we are using this b/w shove it in now so we
6489 		 * can see in the trace viewer if it gets over-ridden.
6490 		 */
6491 		if (rsm->r_ts_valid &&
6492 		    bbr->rc_ts_valid &&
6493 		    bbr->rc_ts_clock_set &&
6494 		    (bbr->rc_ts_cant_be_used == 0) &&
6495 		    bbr->rc_use_ts_limit) {
6496 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6497 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6498 			if ((delivered == 0) ||
6499 			    (rtt < 1000)) {
6500 				/* Can't use the ts */
6501 				bbr_log_type_bbrupd(bbr, 61, cts,
6502 						    ts_diff,
6503 						    bbr->r_ctl.last_inbound_ts,
6504 						    rsm->r_del_ack_ts, 0,
6505 						    0, 0, 0, delivered);
6506 			} else {
6507 				ts_bw = (uint64_t)delivered;
6508 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6509 				ts_bw /= ts_diff;
6510 				bbr_log_type_bbrupd(bbr, 62, cts,
6511 						    (ts_bw >> 32),
6512 						    (ts_bw & 0xffffffff), 0, 0,
6513 						    0, 0, ts_diff, delivered);
6514 				if ((bbr->ts_can_raise) &&
6515 				    (ts_bw > bw)) {
6516 					bbr_log_type_bbrupd(bbr, 8, cts,
6517 							    delivered,
6518 							    ts_diff,
6519 							    (bw >> 32),
6520 							    (bw & 0x00000000ffffffff),
6521 							    0, 0, 0, 0);
6522 					bw = ts_bw;
6523 				} else if (ts_bw && (ts_bw < bw)) {
6524 					bbr_log_type_bbrupd(bbr, 7, cts,
6525 							    delivered,
6526 							    ts_diff,
6527 							    (bw >> 32),
6528 							    (bw & 0x00000000ffffffff),
6529 							    0, 0, 0, 0);
6530 					bw = ts_bw;
6531 				}
6532 			}
6533 		}
6534 		if (rsm->r_first_sent_time &&
6535 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6536 			uint64_t sbw, sti;
6537 			/*
6538 			 * We use what was in flight at the time of our
6539 			 * send  and the size of this send to figure
6540 			 * out what we have been sending at (amount).
6541 			 * For the time we take from the time of
6542 			 * the send of the first send outstanding
6543 			 * until this send plus this sends pacing
6544 			 * time. This gives us a good calculation
6545 			 * as to the rate we have been sending at.
6546 			 */
6547 
6548 			sbw = (uint64_t)(rsm->r_flight_at_send);
6549 			sbw *= (uint64_t)USECS_IN_SECOND;
6550 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6551 			sti += rsm->r_pacing_delay;
6552 			sbw /= sti;
6553 			if (sbw < bw) {
6554 				bbr_log_type_bbrupd(bbr, 6, cts,
6555 						    delivered,
6556 						    (uint32_t)sti,
6557 						    (bw >> 32),
6558 						    (uint32_t)bw,
6559 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6560 						    (uint32_t)sbw);
6561 				bw = sbw;
6562 			}
6563 		}
6564 		/* Use the google algorithm for b/w measurements */
6565 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6566 		if ((rsm->r_app_limited == 0) ||
6567 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6568 			tcp_bbr_commit_bw(bbr, cts);
6569 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6570 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6571 		}
6572 	}
6573 }
6574 
6575 static void
6576 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6577 {
6578 	if (bbr->rc_in_persist == 0) {
6579 		/* We log only when not in persist */
6580 		/* Translate to a Bytes Per Second */
6581 		uint64_t tim, bw;
6582 		uint32_t delivered;
6583 		int no_apply = 0;
6584 
6585 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6586 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6587 		else
6588 			tim = 1;
6589 		/*
6590 		 * Now that we have processed the tim (skipping the sample
6591 		 * or possibly updating the time, go ahead and
6592 		 * calculate the cdr.
6593 		 */
6594 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6595 		bw = (uint64_t)delivered;
6596 		bw *= (uint64_t)USECS_IN_SECOND;
6597 		bw /= tim;
6598 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6599 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6600 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6601 
6602 			no_apply = 1;
6603 		}
6604 		/*
6605 		 * If we are using this b/w shove it in now so we
6606 		 * can see in the trace viewer if it gets over-ridden.
6607 		 */
6608 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6609 		/* Gate by the sending rate */
6610 		if (rsm->r_first_sent_time &&
6611 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6612 			uint64_t sbw, sti;
6613 			/*
6614 			 * We use what was in flight at the time of our
6615 			 * send  and the size of this send to figure
6616 			 * out what we have been sending at (amount).
6617 			 * For the time we take from the time of
6618 			 * the send of the first send outstanding
6619 			 * until this send plus this sends pacing
6620 			 * time. This gives us a good calculation
6621 			 * as to the rate we have been sending at.
6622 			 */
6623 
6624 			sbw = (uint64_t)(rsm->r_flight_at_send);
6625 			sbw *= (uint64_t)USECS_IN_SECOND;
6626 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6627 			sti += rsm->r_pacing_delay;
6628 			sbw /= sti;
6629 			if (sbw < bw) {
6630 				bbr_log_type_bbrupd(bbr, 6, cts,
6631 						    delivered,
6632 						    (uint32_t)sti,
6633 						    (bw >> 32),
6634 						    (uint32_t)bw,
6635 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6636 						    (uint32_t)sbw);
6637 				bw = sbw;
6638 			}
6639 			if ((sti > tim) &&
6640 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6641 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6642 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6643 				no_apply = 1;
6644 			} else
6645 				no_apply = 0;
6646 		}
6647 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6648 		if ((no_apply == 0) &&
6649 		    ((rsm->r_app_limited == 0) ||
6650 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6651 			tcp_bbr_commit_bw(bbr, cts);
6652 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6653 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6654 		}
6655 	}
6656 }
6657 
6658 static void
6659 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6660     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6661 {
6662 	uint64_t old_rttprop;
6663 
6664 	/* Update our delivery time and amount */
6665 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6666 	bbr->r_ctl.rc_del_time = cts;
6667 	if (rtt == 0) {
6668 		/*
6669 		 * 0 means its a retransmit, for now we don't use these for
6670 		 * the rest of BBR.
6671 		 */
6672 		return;
6673 	}
6674 	if ((bbr->rc_use_google == 0) &&
6675 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6676 	    (match != BBR_RTT_BY_TIMESTAMP)){
6677 		/*
6678 		 * We get a lot of rtt updates, lets not pay attention to
6679 		 * any that are not an exact match. That way we don't have
6680 		 * to worry about timestamps and the whole nonsense of
6681 		 * unsure if its a retransmission etc (if we ever had the
6682 		 * timestamp fixed to always have the last thing sent this
6683 		 * would not be a issue).
6684 		 */
6685 		return;
6686 	}
6687 	if ((bbr_no_retran && bbr->rc_use_google) &&
6688 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6689 	    (match != BBR_RTT_BY_TIMESTAMP)){
6690 		/*
6691 		 * We only do measurements in google mode
6692 		 * with bbr_no_retran on for sure things.
6693 		 */
6694 		return;
6695 	}
6696 	/* Only update srtt if we know by exact match */
6697 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6698 	if (ack_type == BBR_CUM_ACKED)
6699 		bbr->rc_ack_is_cumack = 1;
6700 	else
6701 		bbr->rc_ack_is_cumack = 0;
6702 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6703 	/*
6704 	 * Note the following code differs to the original
6705 	 * BBR spec. It calls for <= not <. However after a
6706 	 * long discussion in email with Neal, he acknowledged
6707 	 * that it should be < than so that we will have flows
6708 	 * going into probe-rtt (we were seeing cases where that
6709 	 * did not happen and caused ugly things to occur). We
6710 	 * have added this agreed upon fix to our code base.
6711 	 */
6712 	if (rtt < old_rttprop) {
6713 		/* Update when we last saw a rtt drop */
6714 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6715 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6716 	}
6717 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6718 	    match, rsm->r_start, rsm->r_flags);
6719 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6720 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6721 		/*
6722 		 * The RTT-prop moved, reset the target (may be a
6723 		 * nop for some states).
6724 		 */
6725 		bbr_set_state_target(bbr, __LINE__);
6726 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6727 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6728 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6729 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6730 			/* It went up */
6731 			bbr_check_probe_rtt_limits(bbr, cts);
6732 	}
6733 	if ((bbr->rc_use_google == 0) &&
6734 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6735 		/*
6736 		 * We don't do b/w update with
6737 		 * these since they are not really
6738 		 * reliable.
6739 		 */
6740 		return;
6741 	}
6742 	if (bbr->r_ctl.r_app_limited_until &&
6743 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6744 		/* We are no longer app-limited */
6745 		bbr->r_ctl.r_app_limited_until = 0;
6746 	}
6747 	if (bbr->rc_use_google) {
6748 		bbr_google_measurement(bbr, rsm, rtt, cts);
6749 	} else {
6750 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6751 	}
6752 }
6753 
6754 /*
6755  * Convert a timestamp that the main stack
6756  * uses (milliseconds) into one that bbr uses
6757  * (microseconds). Return that converted timestamp.
6758  */
6759 static uint32_t
6760 bbr_ts_convert(uint32_t cts) {
6761 	uint32_t sec, msec;
6762 
6763 	sec = cts / MS_IN_USEC;
6764 	msec = cts - (MS_IN_USEC * sec);
6765 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6766 }
6767 
6768 /*
6769  * Return 0 if we did not update the RTT time, return
6770  * 1 if we did.
6771  */
6772 static int
6773 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6774     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6775 {
6776 	int32_t i;
6777 	uint32_t t, uts = 0;
6778 
6779 	if ((rsm->r_flags & BBR_ACKED) ||
6780 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6781 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6782 		/* Already done */
6783 		return (0);
6784 	}
6785 	if (rsm->r_rtt_not_allowed) {
6786 		/* Not allowed */
6787 		return (0);
6788 	}
6789 	if (rsm->r_rtr_cnt == 1) {
6790 		/*
6791 		 * Only one transmit. Hopefully the normal case.
6792 		 */
6793 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6794 			t = cts - rsm->r_tim_lastsent[0];
6795 		else
6796 			t = 1;
6797 		if ((int)t <= 0)
6798 			t = 1;
6799 		bbr->r_ctl.rc_last_rtt = t;
6800 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6801 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6802 		return (1);
6803 	}
6804 	/* Convert to usecs */
6805 	if ((bbr_can_use_ts_for_rtt == 1) &&
6806 	    (bbr->rc_use_google == 1) &&
6807 	    (ack_type == BBR_CUM_ACKED) &&
6808 	    (to->to_flags & TOF_TS) &&
6809 	    (to->to_tsecr != 0)) {
6810 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6811 		if (t < 1)
6812 			t = 1;
6813 		t *= MS_IN_USEC;
6814 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6815 				    BBR_RTT_BY_TIMESTAMP,
6816 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6817 				    ack_type, to);
6818 		return (1);
6819 	}
6820 	uts = bbr_ts_convert(to->to_tsecr);
6821 	if ((to->to_flags & TOF_TS) &&
6822 	    (to->to_tsecr != 0) &&
6823 	    (ack_type == BBR_CUM_ACKED) &&
6824 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6825 		/*
6826 		 * Now which timestamp does it match? In this block the ACK
6827 		 * may be coming from a previous transmission.
6828 		 */
6829 		uint32_t fudge;
6830 
6831 		fudge = BBR_TIMER_FUDGE;
6832 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6833 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6834 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6835 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6836 					t = cts - rsm->r_tim_lastsent[i];
6837 				else
6838 					t = 1;
6839 				if ((int)t <= 0)
6840 					t = 1;
6841 				bbr->r_ctl.rc_last_rtt = t;
6842 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6843 						    rsm->r_tim_lastsent[i], ack_type, to);
6844 				if ((i + 1) < rsm->r_rtr_cnt) {
6845 					/* Likely */
6846 					return (0);
6847 				} else if (rsm->r_flags & BBR_TLP) {
6848 					bbr->rc_tlp_rtx_out = 0;
6849 				}
6850 				return (1);
6851 			}
6852 		}
6853 		/* Fall through if we can't find a matching timestamp */
6854 	}
6855 	/*
6856 	 * Ok its a SACK block that we retransmitted. or a windows
6857 	 * machine without timestamps. We can tell nothing from the
6858 	 * time-stamp since its not there or the time the peer last
6859 	 * received a segment that moved forward its cum-ack point.
6860 	 *
6861 	 * Lets look at the last retransmit and see what we can tell
6862 	 * (with BBR for space we only keep 2 note we have to keep
6863 	 * at least 2 so the map can not be condensed more).
6864 	 */
6865 	i = rsm->r_rtr_cnt - 1;
6866 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6867 		t = cts - rsm->r_tim_lastsent[i];
6868 	else
6869 		goto not_sure;
6870 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6871 		/*
6872 		 * We retransmitted and the ack came back in less
6873 		 * than the smallest rtt we have observed in the
6874 		 * windowed rtt. We most likey did an improper
6875 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6876 		 * the rack-draft.
6877 		 *
6878 		 * Use the prior transmission to update all the
6879 		 * information as long as there is only one prior
6880 		 * transmission.
6881 		 */
6882 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6883 #ifdef BBR_INVARIANTS
6884 			if (rsm->r_rtr_cnt == 1)
6885 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6886 #endif
6887 			i = rsm->r_rtr_cnt - 2;
6888 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6889 				t = cts - rsm->r_tim_lastsent[i];
6890 			else
6891 				t = 1;
6892 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6893 					    rsm->r_tim_lastsent[i], ack_type, to);
6894 			return (0);
6895 		} else {
6896 			/*
6897 			 * Too many prior transmissions, just
6898 			 * updated BBR delivered
6899 			 */
6900 not_sure:
6901 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6902 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6903 		}
6904 	} else {
6905 		/*
6906 		 * We retransmitted it and the retransmit did the
6907 		 * job.
6908 		 */
6909 		if (rsm->r_flags & BBR_TLP)
6910 			bbr->rc_tlp_rtx_out = 0;
6911 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6912 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6913 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6914 		else
6915 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6916 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6917 		return (1);
6918 	}
6919 	return (0);
6920 }
6921 
6922 /*
6923  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6924  */
6925 static void
6926 bbr_log_sack_passed(struct tcpcb *tp,
6927     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6928 {
6929 	struct bbr_sendmap *nrsm;
6930 
6931 	nrsm = rsm;
6932 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6933 	    bbr_head, r_tnext) {
6934 		if (nrsm == rsm) {
6935 			/* Skip original segment he is acked */
6936 			continue;
6937 		}
6938 		if (nrsm->r_flags & BBR_ACKED) {
6939 			/* Skip ack'd segments */
6940 			continue;
6941 		}
6942 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6943 			/*
6944 			 * We found one that is already marked
6945 			 * passed, we have been here before and
6946 			 * so all others below this are marked.
6947 			 */
6948 			break;
6949 		}
6950 		BBR_STAT_INC(bbr_sack_passed);
6951 		nrsm->r_flags |= BBR_SACK_PASSED;
6952 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6953 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6954 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6955 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6956 			nrsm->r_flags |= BBR_MARKED_LOST;
6957 		}
6958 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6959 	}
6960 }
6961 
6962 /*
6963  * Returns the number of bytes that were
6964  * newly ack'd by sack blocks.
6965  */
6966 static uint32_t
6967 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6968     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6969 {
6970 	int32_t times = 0;
6971 	uint32_t start, end, changed = 0;
6972 	struct bbr_sendmap *rsm, *nrsm;
6973 	int32_t used_ref = 1;
6974 	uint8_t went_back = 0, went_fwd = 0;
6975 
6976 	start = sack->start;
6977 	end = sack->end;
6978 	rsm = *prsm;
6979 	if (rsm == NULL)
6980 		used_ref = 0;
6981 
6982 	/* Do we locate the block behind where we last were? */
6983 	if (rsm && SEQ_LT(start, rsm->r_start)) {
6984 		went_back = 1;
6985 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
6986 			if (SEQ_GEQ(start, rsm->r_start) &&
6987 			    SEQ_LT(start, rsm->r_end)) {
6988 				goto do_rest_ofb;
6989 			}
6990 		}
6991 	}
6992 start_at_beginning:
6993 	went_fwd = 1;
6994 	/*
6995 	 * Ok lets locate the block where this guy is fwd from rsm (if its
6996 	 * set)
6997 	 */
6998 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
6999 		if (SEQ_GEQ(start, rsm->r_start) &&
7000 		    SEQ_LT(start, rsm->r_end)) {
7001 			break;
7002 		}
7003 	}
7004 do_rest_ofb:
7005 	if (rsm == NULL) {
7006 		/*
7007 		 * This happens when we get duplicate sack blocks with the
7008 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7009 		 * will not change there location so we would just start at
7010 		 * the end of the first one and get lost.
7011 		 */
7012 		if (tp->t_flags & TF_SENTFIN) {
7013 			/*
7014 			 * Check to see if we have not logged the FIN that
7015 			 * went out.
7016 			 */
7017 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7018 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7019 				/*
7020 				 * Ok we did not get the FIN logged.
7021 				 */
7022 				nrsm->r_end++;
7023 				rsm = nrsm;
7024 				goto do_rest_ofb;
7025 			}
7026 		}
7027 		if (times == 1) {
7028 #ifdef BBR_INVARIANTS
7029 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7030 			    tp, bbr, sack, to, prsm);
7031 #else
7032 			goto out;
7033 #endif
7034 		}
7035 		times++;
7036 		BBR_STAT_INC(bbr_sack_proc_restart);
7037 		rsm = NULL;
7038 		goto start_at_beginning;
7039 	}
7040 	/* Ok we have an ACK for some piece of rsm */
7041 	if (rsm->r_start != start) {
7042 		/*
7043 		 * Need to split this in two pieces the before and after.
7044 		 */
7045 		if (bbr_sack_mergable(rsm, start, end))
7046 			nrsm = bbr_alloc_full_limit(bbr);
7047 		else
7048 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7049 		if (nrsm == NULL) {
7050 			/* We could not allocate ignore the sack */
7051 			struct sackblk blk;
7052 
7053 			blk.start = start;
7054 			blk.end = end;
7055 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7056 			goto out;
7057 		}
7058 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7059 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7060 		if (rsm->r_in_tmap) {
7061 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7062 			nrsm->r_in_tmap = 1;
7063 		}
7064 		rsm->r_flags &= (~BBR_HAS_FIN);
7065 		rsm = nrsm;
7066 	}
7067 	if (SEQ_GEQ(end, rsm->r_end)) {
7068 		/*
7069 		 * The end of this block is either beyond this guy or right
7070 		 * at this guy.
7071 		 */
7072 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7073 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7074 			changed += (rsm->r_end - rsm->r_start);
7075 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7076 			bbr_log_sack_passed(tp, bbr, rsm);
7077 			if (rsm->r_flags & BBR_MARKED_LOST) {
7078 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7079 			}
7080 			/* Is Reordering occuring? */
7081 			if (rsm->r_flags & BBR_SACK_PASSED) {
7082 				BBR_STAT_INC(bbr_reorder_seen);
7083 				bbr->r_ctl.rc_reorder_ts = cts;
7084 				if (rsm->r_flags & BBR_MARKED_LOST) {
7085 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7086 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7087 						/* LT sampling also needs adjustment */
7088 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7089 				}
7090 			}
7091 			rsm->r_flags |= BBR_ACKED;
7092 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7093 			if (rsm->r_in_tmap) {
7094 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7095 				rsm->r_in_tmap = 0;
7096 			}
7097 		}
7098 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7099 		if (end == rsm->r_end) {
7100 			/* This block only - done */
7101 			goto out;
7102 		}
7103 		/* There is more not coverend by this rsm move on */
7104 		start = rsm->r_end;
7105 		nrsm = TAILQ_NEXT(rsm, r_next);
7106 		rsm = nrsm;
7107 		times = 0;
7108 		goto do_rest_ofb;
7109 	}
7110 	if (rsm->r_flags & BBR_ACKED) {
7111 		/* Been here done that */
7112 		goto out;
7113 	}
7114 	/* Ok we need to split off this one at the tail */
7115 	if (bbr_sack_mergable(rsm, start, end))
7116 		nrsm = bbr_alloc_full_limit(bbr);
7117 	else
7118 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7119 	if (nrsm == NULL) {
7120 		/* failed XXXrrs what can we do but loose the sack info? */
7121 		struct sackblk blk;
7122 
7123 		blk.start = start;
7124 		blk.end = end;
7125 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7126 		goto out;
7127 	}
7128 	/* Clone it */
7129 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7130 	/* The sack block does not cover this guy fully */
7131 	rsm->r_flags &= (~BBR_HAS_FIN);
7132 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7133 	if (rsm->r_in_tmap) {
7134 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7135 		nrsm->r_in_tmap = 1;
7136 	}
7137 	nrsm->r_dupack = 0;
7138 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7139 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7140 	changed += (rsm->r_end - rsm->r_start);
7141 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7142 	bbr_log_sack_passed(tp, bbr, rsm);
7143 	/* Is Reordering occuring? */
7144 	if (rsm->r_flags & BBR_MARKED_LOST) {
7145 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7146 	}
7147 	if (rsm->r_flags & BBR_SACK_PASSED) {
7148 		BBR_STAT_INC(bbr_reorder_seen);
7149 		bbr->r_ctl.rc_reorder_ts = cts;
7150 		if (rsm->r_flags & BBR_MARKED_LOST) {
7151 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7152 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7153 				/* LT sampling also needs adjustment */
7154 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7155 		}
7156 	}
7157 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7158 	rsm->r_flags |= BBR_ACKED;
7159 	if (rsm->r_in_tmap) {
7160 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7161 		rsm->r_in_tmap = 0;
7162 	}
7163 out:
7164 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7165 		/*
7166 		 * Now can we merge this newly acked
7167 		 * block with either the previous or
7168 		 * next block?
7169 		 */
7170 		nrsm = TAILQ_NEXT(rsm, r_next);
7171 		if (nrsm &&
7172 		    (nrsm->r_flags & BBR_ACKED)) {
7173 			/* yep this and next can be merged */
7174 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7175 		}
7176 		/* Now what about the previous? */
7177 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7178 		if (nrsm &&
7179 		    (nrsm->r_flags & BBR_ACKED)) {
7180 			/* yep the previous and this can be merged */
7181 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7182 		}
7183 	}
7184 	if (used_ref == 0) {
7185 		BBR_STAT_INC(bbr_sack_proc_all);
7186 	} else {
7187 		BBR_STAT_INC(bbr_sack_proc_short);
7188 	}
7189 	if (went_fwd && went_back) {
7190 		BBR_STAT_INC(bbr_sack_search_both);
7191 	} else if (went_fwd) {
7192 		BBR_STAT_INC(bbr_sack_search_fwd);
7193 	} else if (went_back) {
7194 		BBR_STAT_INC(bbr_sack_search_back);
7195 	}
7196 	/* Save off where the next seq is */
7197 	if (rsm)
7198 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7199 	else
7200 		bbr->r_ctl.rc_sacklast = NULL;
7201 	*prsm = rsm;
7202 	return (changed);
7203 }
7204 
7205 static void inline
7206 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7207 {
7208 	struct bbr_sendmap *tmap;
7209 
7210 	BBR_STAT_INC(bbr_reneges_seen);
7211 	tmap = NULL;
7212 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7213 		/* Its no longer sacked, mark it so */
7214 		uint32_t oflags;
7215 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7216 #ifdef BBR_INVARIANTS
7217 		if (rsm->r_in_tmap) {
7218 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7219 			    bbr, rsm, rsm->r_flags);
7220 		}
7221 #endif
7222 		oflags = rsm->r_flags;
7223 		if (rsm->r_flags & BBR_MARKED_LOST) {
7224 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7225 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7226 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7227 				/* LT sampling also needs adjustment */
7228 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7229 		}
7230 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7231 		rsm->r_flags |= BBR_WAS_RENEGED;
7232 		rsm->r_flags |= BBR_RXT_CLEARED;
7233 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7234 		/* Rebuild it into our tmap */
7235 		if (tmap == NULL) {
7236 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7237 			tmap = rsm;
7238 		} else {
7239 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7240 			tmap = rsm;
7241 		}
7242 		tmap->r_in_tmap = 1;
7243 		/*
7244 		 * XXXrrs Delivered? Should we do anything here?
7245 		 *
7246 		 * Of course we don't on a rxt timeout so maybe its ok that
7247 		 * we don't?
7248 		 *
7249 		 * For now lets not.
7250 		 */
7251 		rsm = TAILQ_NEXT(rsm, r_next);
7252 	}
7253 	/*
7254 	 * Now lets possibly clear the sack filter so we start recognizing
7255 	 * sacks that cover this area.
7256 	 */
7257 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7258 }
7259 
7260 static void
7261 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7262 {
7263 	struct tcp_bbr *bbr;
7264 	struct bbr_sendmap *rsm;
7265 	uint32_t cts;
7266 
7267 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7268 	cts = bbr->r_ctl.rc_rcvtime;
7269 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7270 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7271 		if ((rsm->r_end - rsm->r_start) <= 1) {
7272 			/* Log out the SYN completely */
7273 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7274 			rsm->r_rtr_bytes = 0;
7275 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7276 			if (rsm->r_in_tmap) {
7277 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7278 				rsm->r_in_tmap = 0;
7279 			}
7280 			if (bbr->r_ctl.rc_next == rsm) {
7281 				/* scoot along the marker */
7282 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7283 			}
7284 			if (to != NULL)
7285 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7286 			bbr_free(bbr, rsm);
7287 		} else {
7288 			/* There is more (Fast open)? strip out SYN. */
7289 			rsm->r_flags &= ~BBR_HAS_SYN;
7290 			rsm->r_start++;
7291 		}
7292 	}
7293 }
7294 
7295 /*
7296  * Returns the number of bytes that were
7297  * acknowledged by SACK blocks.
7298  */
7299 
7300 static uint32_t
7301 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7302     uint32_t *prev_acked)
7303 {
7304 	uint32_t changed, last_seq, entered_recovery = 0;
7305 	struct tcp_bbr *bbr;
7306 	struct bbr_sendmap *rsm;
7307 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7308 	register uint32_t th_ack;
7309 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7310 	uint32_t cts, acked, ack_point, sack_changed = 0;
7311 	uint32_t p_maxseg, maxseg, p_acked = 0;
7312 
7313 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7314 	if (tcp_get_flags(th) & TH_RST) {
7315 		/* We don't log resets */
7316 		return (0);
7317 	}
7318 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7319 	cts = bbr->r_ctl.rc_rcvtime;
7320 
7321 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7322 	changed = 0;
7323 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7324 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7325 	th_ack = th->th_ack;
7326 	if (SEQ_GT(th_ack, tp->snd_una)) {
7327 		acked = th_ack - tp->snd_una;
7328 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7329 		bbr->rc_tp->t_acktime = ticks;
7330 	} else
7331 		acked = 0;
7332 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7333 		/* Only sent here for sack processing */
7334 		goto proc_sack;
7335 	}
7336 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7337 		changed = th_ack - rsm->r_start;
7338 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7339 		/*
7340 		 * For the SYN incoming case we will not have called
7341 		 * tcp_output for the sending of the SYN, so there will be
7342 		 * no map. All other cases should probably be a panic.
7343 		 */
7344 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7345 			/*
7346 			 * We have a timestamp that can be used to generate
7347 			 * an initial RTT.
7348 			 */
7349 			uint32_t ts, now, rtt;
7350 
7351 			ts = bbr_ts_convert(to->to_tsecr);
7352 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7353 			rtt = now - ts;
7354 			if (rtt < 1)
7355 				rtt = 1;
7356 			bbr_log_type_bbrrttprop(bbr, rtt,
7357 						tp->iss, 0, cts,
7358 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7359 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7360 			changed = 1;
7361 			bbr->r_wanted_output = 1;
7362 			goto out;
7363 		}
7364 		goto proc_sack;
7365 	} else if (rsm == NULL) {
7366 		goto out;
7367 	}
7368 	if (changed) {
7369 		/*
7370 		 * The ACK point is advancing to th_ack, we must drop off
7371 		 * the packets in the rack log and calculate any eligble
7372 		 * RTT's.
7373 		 */
7374 		bbr->r_wanted_output = 1;
7375 more:
7376 		if (rsm == NULL) {
7377 			if (tp->t_flags & TF_SENTFIN) {
7378 				/* if we send a FIN we will not hav a map */
7379 				goto proc_sack;
7380 			}
7381 #ifdef BBR_INVARIANTS
7382 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7383 			    tp,
7384 			    th, tp->t_state, bbr,
7385 			    tp->snd_una, tp->snd_max, changed);
7386 #endif
7387 			goto proc_sack;
7388 		}
7389 	}
7390 	if (SEQ_LT(th_ack, rsm->r_start)) {
7391 		/* Huh map is missing this */
7392 #ifdef BBR_INVARIANTS
7393 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7394 		    rsm->r_start,
7395 		    th_ack, tp->t_state,
7396 		    bbr->r_state, bbr);
7397 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7398 #endif
7399 		goto proc_sack;
7400 	} else if (th_ack == rsm->r_start) {
7401 		/* None here to ack */
7402 		goto proc_sack;
7403 	}
7404 	/*
7405 	 * Clear the dup ack counter, it will
7406 	 * either be freed or if there is some
7407 	 * remaining we need to start it at zero.
7408 	 */
7409 	rsm->r_dupack = 0;
7410 	/* Now do we consume the whole thing? */
7411 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7412 		/* Its all consumed. */
7413 		uint32_t left;
7414 
7415 		if (rsm->r_flags & BBR_ACKED) {
7416 			/*
7417 			 * It was acked on the scoreboard -- remove it from
7418 			 * total
7419 			 */
7420 			p_acked += (rsm->r_end - rsm->r_start);
7421 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7422 			if (bbr->r_ctl.rc_sacked == 0)
7423 				bbr->r_ctl.rc_sacklast = NULL;
7424 		} else {
7425 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7426 			if (rsm->r_flags & BBR_MARKED_LOST) {
7427 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7428 			}
7429 			if (rsm->r_flags & BBR_SACK_PASSED) {
7430 				/*
7431 				 * There are acked segments ACKED on the
7432 				 * scoreboard further up. We are seeing
7433 				 * reordering.
7434 				 */
7435 				BBR_STAT_INC(bbr_reorder_seen);
7436 				bbr->r_ctl.rc_reorder_ts = cts;
7437 				if (rsm->r_flags & BBR_MARKED_LOST) {
7438 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7439 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7440 						/* LT sampling also needs adjustment */
7441 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7442 				}
7443 			}
7444 			rsm->r_flags &= ~BBR_MARKED_LOST;
7445 		}
7446 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7447 		rsm->r_rtr_bytes = 0;
7448 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7449 		if (rsm->r_in_tmap) {
7450 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7451 			rsm->r_in_tmap = 0;
7452 		}
7453 		if (bbr->r_ctl.rc_next == rsm) {
7454 			/* scoot along the marker */
7455 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7456 		}
7457 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7458 		/* Adjust the packet counts */
7459 		left = th_ack - rsm->r_end;
7460 		/* Free back to zone */
7461 		bbr_free(bbr, rsm);
7462 		if (left) {
7463 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7464 			goto more;
7465 		}
7466 		goto proc_sack;
7467 	}
7468 	if (rsm->r_flags & BBR_ACKED) {
7469 		/*
7470 		 * It was acked on the scoreboard -- remove it from total
7471 		 * for the part being cum-acked.
7472 		 */
7473 		p_acked += (rsm->r_end - rsm->r_start);
7474 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7475 		if (bbr->r_ctl.rc_sacked == 0)
7476 			bbr->r_ctl.rc_sacklast = NULL;
7477 	} else {
7478 		/*
7479 		 * It was acked up to th_ack point for the first time
7480 		 */
7481 		struct bbr_sendmap lrsm;
7482 
7483 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7484 		lrsm.r_end = th_ack;
7485 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7486 	}
7487 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7488 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7489 		/*
7490 		 * It was marked lost and partly ack'd now
7491 		 * for the first time. We lower the rc_lost_bytes
7492 		 * and still leave it MARKED.
7493 		 */
7494 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7495 	}
7496 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7497 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7498 	rsm->r_rtr_bytes = 0;
7499 	/* adjust packet count */
7500 	rsm->r_start = th_ack;
7501 proc_sack:
7502 	/* Check for reneging */
7503 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7504 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7505 		/*
7506 		 * The peer has moved snd_una up to the edge of this send,
7507 		 * i.e. one that it had previously acked. The only way that
7508 		 * can be true if the peer threw away data (space issues)
7509 		 * that it had previously sacked (else it would have given
7510 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7511 		 * markings here.
7512 		 *
7513 		 * Note we have to look to make sure th_ack is our
7514 		 * rsm->r_start in case we get an old ack where th_ack is
7515 		 * behind snd_una.
7516 		 */
7517 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7518 	}
7519 	if ((to->to_flags & TOF_SACK) == 0) {
7520 		/* We are done nothing left to log */
7521 		goto out;
7522 	}
7523 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7524 	if (rsm) {
7525 		last_seq = rsm->r_end;
7526 	} else {
7527 		last_seq = tp->snd_max;
7528 	}
7529 	/* Sack block processing */
7530 	if (SEQ_GT(th_ack, tp->snd_una))
7531 		ack_point = th_ack;
7532 	else
7533 		ack_point = tp->snd_una;
7534 	for (i = 0; i < to->to_nsacks; i++) {
7535 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7536 		    &sack, sizeof(sack));
7537 		sack.start = ntohl(sack.start);
7538 		sack.end = ntohl(sack.end);
7539 		if (SEQ_GT(sack.end, sack.start) &&
7540 		    SEQ_GT(sack.start, ack_point) &&
7541 		    SEQ_LT(sack.start, tp->snd_max) &&
7542 		    SEQ_GT(sack.end, ack_point) &&
7543 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7544 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7545 			    (SEQ_LT(sack.end, last_seq)) &&
7546 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7547 				/*
7548 				 * Not the last piece and its smaller than
7549 				 * 1/8th of a p_maxseg. We ignore this.
7550 				 */
7551 				BBR_STAT_INC(bbr_runt_sacks);
7552 				continue;
7553 			}
7554 			sack_blocks[num_sack_blks] = sack;
7555 			num_sack_blks++;
7556 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7557 		    SEQ_LEQ(sack.end, th_ack)) {
7558 			/*
7559 			 * Its a D-SACK block.
7560 			 */
7561 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7562 		}
7563 	}
7564 	if (num_sack_blks == 0)
7565 		goto out;
7566 	/*
7567 	 * Sort the SACK blocks so we can update the rack scoreboard with
7568 	 * just one pass.
7569 	 */
7570 	new_sb = sack_filter_blks(tp, &bbr->r_ctl.bbr_sf, sack_blocks,
7571 				  num_sack_blks, th->th_ack);
7572 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7573 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7574 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7575 	num_sack_blks = new_sb;
7576 	if (num_sack_blks < 2) {
7577 		goto do_sack_work;
7578 	}
7579 	/* Sort the sacks */
7580 	for (i = 0; i < num_sack_blks; i++) {
7581 		for (j = i + 1; j < num_sack_blks; j++) {
7582 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7583 				sack = sack_blocks[i];
7584 				sack_blocks[i] = sack_blocks[j];
7585 				sack_blocks[j] = sack;
7586 			}
7587 		}
7588 	}
7589 	/*
7590 	 * Now are any of the sack block ends the same (yes some
7591 	 * implememtations send these)?
7592 	 */
7593 again:
7594 	if (num_sack_blks > 1) {
7595 		for (i = 0; i < num_sack_blks; i++) {
7596 			for (j = i + 1; j < num_sack_blks; j++) {
7597 				if (sack_blocks[i].end == sack_blocks[j].end) {
7598 					/*
7599 					 * Ok these two have the same end we
7600 					 * want the smallest end and then
7601 					 * throw away the larger and start
7602 					 * again.
7603 					 */
7604 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7605 						/*
7606 						 * The second block covers
7607 						 * more area use that
7608 						 */
7609 						sack_blocks[i].start = sack_blocks[j].start;
7610 					}
7611 					/*
7612 					 * Now collapse out the dup-sack and
7613 					 * lower the count
7614 					 */
7615 					for (k = (j + 1); k < num_sack_blks; k++) {
7616 						sack_blocks[j].start = sack_blocks[k].start;
7617 						sack_blocks[j].end = sack_blocks[k].end;
7618 						j++;
7619 					}
7620 					num_sack_blks--;
7621 					goto again;
7622 				}
7623 			}
7624 		}
7625 	}
7626 do_sack_work:
7627 	rsm = bbr->r_ctl.rc_sacklast;
7628 	for (i = 0; i < num_sack_blks; i++) {
7629 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7630 		if (acked) {
7631 			bbr->r_wanted_output = 1;
7632 			changed += acked;
7633 			sack_changed += acked;
7634 		}
7635 	}
7636 out:
7637 	*prev_acked = p_acked;
7638 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7639 		/*
7640 		 * Ok we have a high probability that we need to go in to
7641 		 * recovery since we have data sack'd
7642 		 */
7643 		struct bbr_sendmap *rsm;
7644 
7645 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7646 		if (rsm) {
7647 			/* Enter recovery */
7648 			entered_recovery = 1;
7649 			bbr->r_wanted_output = 1;
7650 			/*
7651 			 * When we enter recovery we need to assure we send
7652 			 * one packet.
7653 			 */
7654 			if (bbr->r_ctl.rc_resend == NULL) {
7655 				bbr->r_ctl.rc_resend = rsm;
7656 			}
7657 		}
7658 	}
7659 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7660 		/*
7661 		 * See if we need to rack-retransmit anything if so set it
7662 		 * up as the thing to resend assuming something else is not
7663 		 * already in that position.
7664 		 */
7665 		if (bbr->r_ctl.rc_resend == NULL) {
7666 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7667 		}
7668 	}
7669 	/*
7670 	 * We return the amount that changed via sack, this is used by the
7671 	 * ack-received code to augment what was changed between th_ack <->
7672 	 * snd_una.
7673 	 */
7674 	return (sack_changed);
7675 }
7676 
7677 static void
7678 bbr_strike_dupack(struct tcp_bbr *bbr)
7679 {
7680 	struct bbr_sendmap *rsm;
7681 
7682 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7683 	if (rsm && (rsm->r_dupack < 0xff)) {
7684 		rsm->r_dupack++;
7685 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7686 			bbr->r_wanted_output = 1;
7687 	}
7688 }
7689 
7690 /*
7691  * Return value of 1, we do not need to call bbr_process_data().
7692  * return value of 0, bbr_process_data can be called.
7693  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7694  * its unlocked and probably unsafe to touch the TCB.
7695  */
7696 static int
7697 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7698     struct tcpcb *tp, struct tcpopt *to,
7699     uint32_t tiwin, int32_t tlen,
7700     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7701 {
7702 	int32_t ourfinisacked = 0;
7703 	int32_t acked_amount;
7704 	uint16_t nsegs;
7705 	int32_t acked;
7706 	uint32_t lost, sack_changed = 0;
7707 	struct mbuf *mfree;
7708 	struct tcp_bbr *bbr;
7709 	uint32_t prev_acked = 0;
7710 
7711 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7712 	lost = bbr->r_ctl.rc_lost;
7713 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7714 	if (SEQ_GEQ(tp->snd_una, tp->iss + (65535 << tp->snd_scale))) {
7715 		/* Checking SEG.ACK against ISS is definitely redundant. */
7716 		tp->t_flags2 |= TF2_NO_ISS_CHECK;
7717 	}
7718 	if (!V_tcp_insecure_ack) {
7719 		tcp_seq seq_min;
7720 		bool ghost_ack_check;
7721 
7722 		if (tp->t_flags2 & TF2_NO_ISS_CHECK) {
7723 			/* Check for too old ACKs (RFC 5961, Section 5.2). */
7724 			seq_min = tp->snd_una - tp->max_sndwnd;
7725 			ghost_ack_check = false;
7726 		} else {
7727 			if (SEQ_GT(tp->iss + 1, tp->snd_una - tp->max_sndwnd)) {
7728 				/* Checking for ghost ACKs is stricter. */
7729 				seq_min = tp->iss + 1;
7730 				ghost_ack_check = true;
7731 			} else {
7732 				/*
7733 				 * Checking for too old ACKs (RFC 5961,
7734 				 * Section 5.2) is stricter.
7735 				 */
7736 				seq_min = tp->snd_una - tp->max_sndwnd;
7737 				ghost_ack_check = false;
7738 			}
7739 		}
7740 		if (SEQ_LT(th->th_ack, seq_min)) {
7741 			if (ghost_ack_check)
7742 				TCPSTAT_INC(tcps_rcvghostack);
7743 			else
7744 				TCPSTAT_INC(tcps_rcvacktooold);
7745 			/* Send challenge ACK. */
7746 			ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7747 			bbr->r_wanted_output = 1;
7748 			return (1);
7749 		}
7750 	}
7751 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7752 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7753 		bbr->r_wanted_output = 1;
7754 		return (1);
7755 	}
7756 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7757 		/* Process the ack */
7758 		if (bbr->rc_in_persist)
7759 			tp->t_rxtshift = 0;
7760 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7761 			bbr_strike_dupack(bbr);
7762 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7763 	}
7764 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7765 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7766 		/*
7767 		 * Old ack, behind the last one rcv'd or a duplicate ack
7768 		 * with SACK info.
7769 		 */
7770 		if (th->th_ack == tp->snd_una) {
7771 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7772 			if (bbr->r_state == TCPS_SYN_SENT) {
7773 				/*
7774 				 * Special case on where we sent SYN. When
7775 				 * the SYN-ACK is processed in syn_sent
7776 				 * state it bumps the snd_una. This causes
7777 				 * us to hit here even though we did ack 1
7778 				 * byte.
7779 				 *
7780 				 * Go through the nothing left case so we
7781 				 * send data.
7782 				 */
7783 				goto nothing_left;
7784 			}
7785 		}
7786 		return (0);
7787 	}
7788 	/*
7789 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7790 	 * something we sent.
7791 	 */
7792 	if (tp->t_flags & TF_NEEDSYN) {
7793 		/*
7794 		 * T/TCP: Connection was half-synchronized, and our SYN has
7795 		 * been ACK'd (so connection is now fully synchronized).  Go
7796 		 * to non-starred state, increment snd_una for ACK of SYN,
7797 		 * and check if we can do window scaling.
7798 		 */
7799 		tp->t_flags &= ~TF_NEEDSYN;
7800 		tp->snd_una++;
7801 		/* Do window scaling? */
7802 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7803 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7804 			tp->rcv_scale = tp->request_r_scale;
7805 			/* Send window already scaled. */
7806 		}
7807 	}
7808 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7809 
7810 	acked = BYTES_THIS_ACK(tp, th);
7811 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7812 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7813 
7814 	/*
7815 	 * If we just performed our first retransmit, and the ACK arrives
7816 	 * within our recovery window, then it was a mistake to do the
7817 	 * retransmit in the first place.  Recover our original cwnd and
7818 	 * ssthresh, and proceed to transmit where we left off.
7819 	 */
7820 	if (tp->t_flags & TF_PREVVALID) {
7821 		tp->t_flags &= ~TF_PREVVALID;
7822 		if (tp->t_rxtshift == 1 &&
7823 		    (int)(ticks - tp->t_badrxtwin) < 0)
7824 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7825 	}
7826 	SOCK_SENDBUF_LOCK(so);
7827 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7828 	tp->snd_wnd -= acked_amount;
7829 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7830 	/* NB: sowwakeup_locked() does an implicit unlock. */
7831 	sowwakeup_locked(so);
7832 	m_freem(mfree);
7833 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7834 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7835 	}
7836 	tp->snd_una = th->th_ack;
7837 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7838 	if (IN_RECOVERY(tp->t_flags)) {
7839 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7840 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7841 			tcp_bbr_partialack(tp);
7842 		} else {
7843 			bbr_post_recovery(tp);
7844 		}
7845 	}
7846 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7847 		tp->snd_recover = tp->snd_una;
7848 	}
7849 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7850 		tp->snd_nxt = tp->snd_max;
7851 	}
7852 	if (tp->snd_una == tp->snd_max) {
7853 		/* Nothing left outstanding */
7854 nothing_left:
7855 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7856 		if (sbavail(&so->so_snd) == 0)
7857 			bbr->rc_tp->t_acktime = 0;
7858 		if ((sbused(&so->so_snd) == 0) &&
7859 		    (tp->t_flags & TF_SENTFIN)) {
7860 			ourfinisacked = 1;
7861 		}
7862 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7863 		if (bbr->rc_in_persist == 0) {
7864 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7865 		}
7866 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7867 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7868 		/*
7869 		 * We invalidate the last ack here since we
7870 		 * don't want to transfer forward the time
7871 		 * for our sum's calculations.
7872 		 */
7873 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7874 		    (sbavail(&so->so_snd) == 0) &&
7875 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7876 			/*
7877 			 * The socket was gone and the peer sent data, time
7878 			 * to reset him.
7879 			 */
7880 			*ret_val = 1;
7881 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7882 			/* tcp_close will kill the inp pre-log the Reset */
7883 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7884 			tp = tcp_close(tp);
7885 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7886 			BBR_STAT_INC(bbr_dropped_af_data);
7887 			return (1);
7888 		}
7889 		/* Set need output so persist might get set */
7890 		bbr->r_wanted_output = 1;
7891 	}
7892 	if (ofia)
7893 		*ofia = ourfinisacked;
7894 	return (0);
7895 }
7896 
7897 static void
7898 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7899 {
7900 	if (bbr->rc_in_persist == 0) {
7901 		bbr_timer_cancel(bbr, __LINE__, cts);
7902 		bbr->r_ctl.rc_last_delay_val = 0;
7903 		tp->t_rxtshift = 0;
7904 		bbr->rc_in_persist = 1;
7905 		bbr->r_ctl.rc_went_idle_time = cts;
7906 		/* We should be capped when rw went to 0 but just in case */
7907 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7908 		/* Time freezes for the state, so do the accounting now */
7909 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7910 			uint32_t time_in;
7911 
7912 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7913 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7914 				int32_t idx;
7915 
7916 				idx = bbr_state_val(bbr);
7917 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7918 			} else {
7919 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7920 			}
7921 		}
7922 		bbr->r_ctl.rc_bbr_state_time = cts;
7923 	}
7924 }
7925 
7926 static void
7927 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7928 {
7929 	/*
7930 	 * Note that if idle time does not exceed our
7931 	 * threshold, we do nothing continuing the state
7932 	 * transitions we were last walking through.
7933 	 */
7934 	if (idle_time >= bbr_idle_restart_threshold) {
7935 		if (bbr->rc_use_idle_restart) {
7936 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7937 			/*
7938 			 * Set our target using BBR_UNIT, so
7939 			 * we increase at a dramatic rate but
7940 			 * we stop when we get the pipe
7941 			 * full again for our current b/w estimate.
7942 			 */
7943 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7944 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7945 			bbr_set_state_target(bbr, __LINE__);
7946 			/* Now setup our gains to ramp up */
7947 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7948 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7949 			bbr_log_type_statechange(bbr, cts, __LINE__);
7950 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7951 			bbr_substate_change(bbr, cts, __LINE__, 1);
7952 		}
7953 	}
7954 }
7955 
7956 static void
7957 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7958 {
7959 	uint32_t idle_time;
7960 
7961 	if (bbr->rc_in_persist == 0)
7962 		return;
7963 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7964 	bbr->rc_in_persist = 0;
7965 	bbr->rc_hit_state_1 = 0;
7966 	bbr->r_ctl.rc_del_time = cts;
7967 	/*
7968 	 * We invalidate the last ack here since we
7969 	 * don't want to transfer forward the time
7970 	 * for our sum's calculations.
7971 	 */
7972 	if (tcp_in_hpts(bbr->rc_tp)) {
7973 		tcp_hpts_remove(bbr->rc_tp);
7974 		bbr->rc_timer_first = 0;
7975 		bbr->r_ctl.rc_hpts_flags = 0;
7976 		bbr->r_ctl.rc_last_delay_val = 0;
7977 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7978 		bbr->r_agg_early_set = 0;
7979 		bbr->r_ctl.rc_agg_early = 0;
7980 	}
7981 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7982 	if (idle_time >= bbr_rtt_probe_time) {
7983 		/*
7984 		 * This qualifies as a RTT_PROBE session since we drop the
7985 		 * data outstanding to nothing and waited more than
7986 		 * bbr_rtt_probe_time.
7987 		 */
7988 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7989 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7990 	}
7991 	tp->t_rxtshift = 0;
7992 	/*
7993 	 * If in probeBW and we have persisted more than an RTT lets do
7994 	 * special handling.
7995 	 */
7996 	/* Force a time based epoch */
7997 	bbr_set_epoch(bbr, cts, __LINE__);
7998 	/*
7999 	 * Setup the lost so we don't count anything against the guy
8000 	 * we have been stuck with during persists.
8001 	 */
8002 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
8003 	/* Time un-freezes for the state */
8004 	bbr->r_ctl.rc_bbr_state_time = cts;
8005 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
8006 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
8007 		/*
8008 		 * If we are going back to probe-bw
8009 		 * or probe_rtt, we may need to possibly
8010 		 * do a fast restart.
8011 		 */
8012 		bbr_restart_after_idle(bbr, cts, idle_time);
8013 	}
8014 }
8015 
8016 static void
8017 bbr_collapsed_window(struct tcp_bbr *bbr)
8018 {
8019 	/*
8020 	 * Now we must walk the
8021 	 * send map and divide the
8022 	 * ones left stranded. These
8023 	 * guys can't cause us to abort
8024 	 * the connection and are really
8025 	 * "unsent". However if a buggy
8026 	 * client actually did keep some
8027 	 * of the data i.e. collapsed the win
8028 	 * and refused to ack and then opened
8029 	 * the win and acked that data. We would
8030 	 * get into an ack war, the simplier
8031 	 * method then of just pretending we
8032 	 * did not send those segments something
8033 	 * won't work.
8034 	 */
8035 	struct bbr_sendmap *rsm, *nrsm;
8036 	tcp_seq max_seq;
8037 	uint32_t maxseg;
8038 	int can_split = 0;
8039 	int fnd = 0;
8040 
8041 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8042 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8043 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8044 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8045 		/* Find the first seq past or at maxseq */
8046 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8047 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8048 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8049 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8050 			fnd = 1;
8051 			break;
8052 		}
8053 	}
8054 	bbr->rc_has_collapsed = 0;
8055 	if (!fnd) {
8056 		/* Nothing to do strange */
8057 		return;
8058 	}
8059 	/*
8060 	 * Now can we split?
8061 	 *
8062 	 * We don't want to split if splitting
8063 	 * would generate too many small segments
8064 	 * less we let an attacker fragment our
8065 	 * send_map and leave us out of memory.
8066 	 */
8067 	if ((max_seq != rsm->r_start) &&
8068 	    (max_seq != rsm->r_end)){
8069 		/* can we split? */
8070 		int res1, res2;
8071 
8072 		res1 = max_seq - rsm->r_start;
8073 		res2 = rsm->r_end - max_seq;
8074 		if ((res1 >= (maxseg/8)) &&
8075 		    (res2 >= (maxseg/8))) {
8076 			/* No small pieces here */
8077 			can_split = 1;
8078 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8079 			/* We are under the limit */
8080 			can_split = 1;
8081 		}
8082 	}
8083 	/* Ok do we need to split this rsm? */
8084 	if (max_seq == rsm->r_start) {
8085 		/* It's this guy no split required */
8086 		nrsm = rsm;
8087 	} else if (max_seq == rsm->r_end) {
8088 		/* It's the next one no split required. */
8089 		nrsm = TAILQ_NEXT(rsm, r_next);
8090 		if (nrsm == NULL) {
8091 			/* Huh? */
8092 			return;
8093 		}
8094 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8095 		/* yep we need to split it */
8096 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8097 		if (nrsm == NULL) {
8098 			/* failed XXXrrs what can we do mark the whole? */
8099 			nrsm = rsm;
8100 			goto no_split;
8101 		}
8102 		/* Clone it */
8103 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8104 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8105 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8106 		if (rsm->r_in_tmap) {
8107 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8108 			nrsm->r_in_tmap = 1;
8109 		}
8110 	} else {
8111 		/*
8112 		 * Split not allowed just start here just
8113 		 * use this guy.
8114 		 */
8115 		nrsm = rsm;
8116 	}
8117 no_split:
8118 	BBR_STAT_INC(bbr_collapsed_win);
8119 	/* reuse fnd as a count */
8120 	fnd = 0;
8121 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8122 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8123 		fnd++;
8124 		bbr->rc_has_collapsed = 1;
8125 	}
8126 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8127 }
8128 
8129 static void
8130 bbr_un_collapse_window(struct tcp_bbr *bbr)
8131 {
8132 	struct bbr_sendmap *rsm;
8133 	int cleared = 0;
8134 
8135 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8136 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8137 			/* Clear the flag */
8138 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8139 			cleared++;
8140 		} else
8141 			break;
8142 	}
8143 	bbr_log_type_rwnd_collapse(bbr,
8144 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8145 	bbr->rc_has_collapsed = 0;
8146 }
8147 
8148 /*
8149  * Return value of 1, the TCB is unlocked and most
8150  * likely gone, return value of 0, the TCB is still
8151  * locked.
8152  */
8153 static int
8154 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8155     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8156     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8157 {
8158 	/*
8159 	 * Update window information. Don't look at window if no ACK: TAC's
8160 	 * send garbage on first SYN.
8161 	 */
8162 	uint16_t nsegs;
8163 	int32_t tfo_syn;
8164 	struct tcp_bbr *bbr;
8165 
8166 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8167 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8168 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8169 	if ((thflags & TH_ACK) &&
8170 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8171 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8172 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8173 		/* keep track of pure window updates */
8174 		if (tlen == 0 &&
8175 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8176 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8177 		tp->snd_wnd = tiwin;
8178 		tp->snd_wl1 = th->th_seq;
8179 		tp->snd_wl2 = th->th_ack;
8180 		if (tp->snd_wnd > tp->max_sndwnd)
8181 			tp->max_sndwnd = tp->snd_wnd;
8182 		bbr->r_wanted_output = 1;
8183 	} else if (thflags & TH_ACK) {
8184 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8185 			tp->snd_wnd = tiwin;
8186 			tp->snd_wl1 = th->th_seq;
8187 			tp->snd_wl2 = th->th_ack;
8188 		}
8189 	}
8190 	if (tp->snd_wnd < ctf_outstanding(tp))
8191 		/* The peer collapsed its window on us */
8192 		bbr_collapsed_window(bbr);
8193  	else if (bbr->rc_has_collapsed)
8194 		bbr_un_collapse_window(bbr);
8195 	/* Was persist timer active and now we have window space? */
8196 	if ((bbr->rc_in_persist != 0) &&
8197 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8198 				bbr_minseg(bbr)))) {
8199 		/*
8200 		 * Make the rate persist at end of persist mode if idle long
8201 		 * enough
8202 		 */
8203 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8204 
8205 		/* Make sure we output to start the timer */
8206 		bbr->r_wanted_output = 1;
8207 	}
8208 	/* Do we need to enter persist? */
8209 	if ((bbr->rc_in_persist == 0) &&
8210 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8211 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8212 	    (tp->snd_max == tp->snd_una) &&
8213 	    sbavail(&so->so_snd) &&
8214 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8215 		/* No send window.. we must enter persist */
8216 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8217 	}
8218 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8219 		m_freem(m);
8220 		return (0);
8221 	}
8222 	/*
8223 	 * We don't support urgent data but
8224 	 * drag along the up just to make sure
8225 	 * if there is a stack switch no one
8226 	 * is surprised.
8227 	 */
8228 	tp->rcv_up = tp->rcv_nxt;
8229 
8230 	/*
8231 	 * Process the segment text, merging it into the TCP sequencing
8232 	 * queue, and arranging for acknowledgment of receipt if necessary.
8233 	 * This process logically involves adjusting tp->rcv_wnd as data is
8234 	 * presented to the user (this happens in tcp_usrreq.c, case
8235 	 * PRU_RCVD).  If a FIN has already been received on this connection
8236 	 * then we just ignore the text.
8237 	 */
8238 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8239 	    (tp->t_flags & TF_FASTOPEN));
8240 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8241 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8242 		tcp_seq save_start = th->th_seq;
8243 		tcp_seq save_rnxt  = tp->rcv_nxt;
8244 		int     save_tlen  = tlen;
8245 
8246 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8247 		/*
8248 		 * Insert segment which includes th into TCP reassembly
8249 		 * queue with control block tp.  Set thflags to whether
8250 		 * reassembly now includes a segment with FIN.  This handles
8251 		 * the common case inline (segment is the next to be
8252 		 * received on an established connection, and the queue is
8253 		 * empty), avoiding linkage into and removal from the queue
8254 		 * and repetition of various conversions. Set DELACK for
8255 		 * segments received in order, but ack immediately when
8256 		 * segments are out of order (so fast retransmit can work).
8257 		 */
8258 		if (th->th_seq == tp->rcv_nxt &&
8259 		    SEGQ_EMPTY(tp) &&
8260 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8261 		    tfo_syn)) {
8262 #ifdef NETFLIX_SB_LIMITS
8263 			u_int mcnt, appended;
8264 
8265 			if (so->so_rcv.sb_shlim) {
8266 				mcnt = m_memcnt(m);
8267 				appended = 0;
8268 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8269 				    CFO_NOSLEEP, NULL) == false) {
8270 					counter_u64_add(tcp_sb_shlim_fails, 1);
8271 					m_freem(m);
8272 					return (0);
8273 				}
8274 			}
8275 
8276 #endif
8277 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8278 				bbr->bbr_segs_rcvd += max(1, nsegs);
8279 				tp->t_flags |= TF_DELACK;
8280 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8281 			} else {
8282 				bbr->r_wanted_output = 1;
8283 				tp->t_flags |= TF_ACKNOW;
8284 			}
8285 			tp->rcv_nxt += tlen;
8286 			if (tlen &&
8287 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8288 			    (tp->t_fbyte_in == 0)) {
8289 				tp->t_fbyte_in = ticks;
8290 				if (tp->t_fbyte_in == 0)
8291 					tp->t_fbyte_in = 1;
8292 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8293 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8294 			}
8295 			thflags = tcp_get_flags(th) & TH_FIN;
8296 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8297 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8298 			SOCK_RECVBUF_LOCK(so);
8299 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8300 				m_freem(m);
8301 			else
8302 #ifdef NETFLIX_SB_LIMITS
8303 				appended =
8304 #endif
8305 					sbappendstream_locked(&so->so_rcv, m, 0);
8306 			/* NB: sorwakeup_locked() does an implicit unlock. */
8307 			sorwakeup_locked(so);
8308 #ifdef NETFLIX_SB_LIMITS
8309 			if (so->so_rcv.sb_shlim && appended != mcnt)
8310 				counter_fo_release(so->so_rcv.sb_shlim,
8311 				    mcnt - appended);
8312 #endif
8313 
8314 		} else {
8315 			/*
8316 			 * XXX: Due to the header drop above "th" is
8317 			 * theoretically invalid by now.  Fortunately
8318 			 * m_adj() doesn't actually frees any mbufs when
8319 			 * trimming from the head.
8320 			 */
8321 			tcp_seq temp = save_start;
8322 
8323 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8324 			tp->t_flags |= TF_ACKNOW;
8325 			if (tp->t_flags & TF_WAKESOR) {
8326 				tp->t_flags &= ~TF_WAKESOR;
8327 				/* NB: sorwakeup_locked() does an implicit unlock. */
8328 				sorwakeup_locked(so);
8329 			}
8330 		}
8331 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8332 		    (save_tlen > 0) &&
8333 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8334 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8335 				/*
8336 				 * DSACK actually handled in the fastpath
8337 				 * above.
8338 				 */
8339 				tcp_update_sack_list(tp, save_start,
8340 				    save_start + save_tlen);
8341 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8342 				if ((tp->rcv_numsacks >= 1) &&
8343 				    (tp->sackblks[0].end == save_start)) {
8344 					/*
8345 					 * Partial overlap, recorded at todrop
8346 					 * above.
8347 					 */
8348 					tcp_update_sack_list(tp,
8349 					    tp->sackblks[0].start,
8350 					    tp->sackblks[0].end);
8351 				} else {
8352 					tcp_update_dsack_list(tp, save_start,
8353 					    save_start + save_tlen);
8354 				}
8355 			} else if (tlen >= save_tlen) {
8356 				/* Update of sackblks. */
8357 				tcp_update_dsack_list(tp, save_start,
8358 				    save_start + save_tlen);
8359 			} else if (tlen > 0) {
8360 				tcp_update_dsack_list(tp, save_start,
8361 				    save_start + tlen);
8362 			}
8363 		}
8364 	} else {
8365 		m_freem(m);
8366 		thflags &= ~TH_FIN;
8367 	}
8368 
8369 	/*
8370 	 * If FIN is received ACK the FIN and let the user know that the
8371 	 * connection is closing.
8372 	 */
8373 	if (thflags & TH_FIN) {
8374 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8375 			/* The socket upcall is handled by socantrcvmore. */
8376 			socantrcvmore(so);
8377 			/*
8378 			 * If connection is half-synchronized (ie NEEDSYN
8379 			 * flag on) then delay ACK, so it may be piggybacked
8380 			 * when SYN is sent. Otherwise, since we received a
8381 			 * FIN then no more input can be expected, send ACK
8382 			 * now.
8383 			 */
8384 			if (tp->t_flags & TF_NEEDSYN) {
8385 				tp->t_flags |= TF_DELACK;
8386 				bbr_timer_cancel(bbr,
8387 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8388 			} else {
8389 				tp->t_flags |= TF_ACKNOW;
8390 			}
8391 			tp->rcv_nxt++;
8392 		}
8393 		switch (tp->t_state) {
8394 			/*
8395 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8396 			 * CLOSE_WAIT state.
8397 			 */
8398 		case TCPS_SYN_RECEIVED:
8399 			tp->t_starttime = ticks;
8400 			/* FALLTHROUGH */
8401 		case TCPS_ESTABLISHED:
8402 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8403 			break;
8404 
8405 			/*
8406 			 * If still in FIN_WAIT_1 STATE FIN has not been
8407 			 * acked so enter the CLOSING state.
8408 			 */
8409 		case TCPS_FIN_WAIT_1:
8410 			tcp_state_change(tp, TCPS_CLOSING);
8411 			break;
8412 
8413 			/*
8414 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8415 			 * starting the time-wait timer, turning off the
8416 			 * other standard timers.
8417 			 */
8418 		case TCPS_FIN_WAIT_2:
8419 			bbr->rc_timer_first = 1;
8420 			bbr_timer_cancel(bbr,
8421 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8422 			tcp_twstart(tp);
8423 			return (1);
8424 		}
8425 	}
8426 	/*
8427 	 * Return any desired output.
8428 	 */
8429 	if ((tp->t_flags & TF_ACKNOW) ||
8430 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8431 		bbr->r_wanted_output = 1;
8432 	}
8433 	return (0);
8434 }
8435 
8436 /*
8437  * Here nothing is really faster, its just that we
8438  * have broken out the fast-data path also just like
8439  * the fast-ack. Return 1 if we processed the packet
8440  * return 0 if you need to take the "slow-path".
8441  */
8442 static int
8443 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8444     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8445     uint32_t tiwin, int32_t nxt_pkt)
8446 {
8447 	uint16_t nsegs;
8448 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8449 	struct tcp_bbr *bbr;
8450 #ifdef NETFLIX_SB_LIMITS
8451 	u_int mcnt, appended;
8452 #endif
8453 
8454 	/* On the hpts and we would have called output */
8455 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8456 
8457 	/*
8458 	 * If last ACK falls within this segment's sequence numbers, record
8459 	 * the timestamp. NOTE that the test is modified according to the
8460 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8461 	 */
8462 	if (bbr->r_ctl.rc_resend != NULL) {
8463 		return (0);
8464 	}
8465 	if (tiwin && tiwin != tp->snd_wnd) {
8466 		return (0);
8467 	}
8468 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8469 		return (0);
8470 	}
8471 	if (__predict_false((to->to_flags & TOF_TS) &&
8472 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8473 		return (0);
8474 	}
8475 	if (__predict_false((th->th_ack != tp->snd_una))) {
8476 		return (0);
8477 	}
8478 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8479 		return (0);
8480 	}
8481 	if ((to->to_flags & TOF_TS) != 0 &&
8482 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8483 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8484 		tp->ts_recent = to->to_tsval;
8485 	}
8486 	/*
8487 	 * This is a pure, in-sequence data packet with nothing on the
8488 	 * reassembly queue and we have enough buffer space to take it.
8489 	 */
8490 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8491 
8492 #ifdef NETFLIX_SB_LIMITS
8493 	if (so->so_rcv.sb_shlim) {
8494 		mcnt = m_memcnt(m);
8495 		appended = 0;
8496 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8497 		    CFO_NOSLEEP, NULL) == false) {
8498 			counter_u64_add(tcp_sb_shlim_fails, 1);
8499 			m_freem(m);
8500 			return (1);
8501 		}
8502 	}
8503 #endif
8504 	/* Clean receiver SACK report if present */
8505 	if (tp->rcv_numsacks)
8506 		tcp_clean_sackreport(tp);
8507 	KMOD_TCPSTAT_INC(tcps_preddat);
8508 	tp->rcv_nxt += tlen;
8509 	if (tlen &&
8510 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8511 	    (tp->t_fbyte_in == 0)) {
8512 		tp->t_fbyte_in = ticks;
8513 		if (tp->t_fbyte_in == 0)
8514 			tp->t_fbyte_in = 1;
8515 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8516 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8517 	}
8518 	/*
8519 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8520 	 */
8521 	tp->snd_wl1 = th->th_seq;
8522 	/*
8523 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8524 	 */
8525 	tp->rcv_up = tp->rcv_nxt;
8526 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8527 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8528 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8529 
8530 	/* Add data to socket buffer. */
8531 	SOCK_RECVBUF_LOCK(so);
8532 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8533 		m_freem(m);
8534 	} else {
8535 		/*
8536 		 * Set new socket buffer size. Give up when limit is
8537 		 * reached.
8538 		 */
8539 		if (newsize)
8540 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8541 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8542 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8543 
8544 #ifdef NETFLIX_SB_LIMITS
8545 		appended =
8546 #endif
8547 			sbappendstream_locked(&so->so_rcv, m, 0);
8548 		ctf_calc_rwin(so, tp);
8549 	}
8550 	/* NB: sorwakeup_locked() does an implicit unlock. */
8551 	sorwakeup_locked(so);
8552 #ifdef NETFLIX_SB_LIMITS
8553 	if (so->so_rcv.sb_shlim && mcnt != appended)
8554 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8555 #endif
8556 	if (DELAY_ACK(tp, bbr, nsegs)) {
8557 		bbr->bbr_segs_rcvd += max(1, nsegs);
8558 		tp->t_flags |= TF_DELACK;
8559 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8560 	} else {
8561 		bbr->r_wanted_output = 1;
8562 		tp->t_flags |= TF_ACKNOW;
8563 	}
8564 	return (1);
8565 }
8566 
8567 /*
8568  * This subfunction is used to try to highly optimize the
8569  * fast path. We again allow window updates that are
8570  * in sequence to remain in the fast-path. We also add
8571  * in the __predict's to attempt to help the compiler.
8572  * Note that if we return a 0, then we can *not* process
8573  * it and the caller should push the packet into the
8574  * slow-path. If we return 1, then all is well and
8575  * the packet is fully processed.
8576  */
8577 static int
8578 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8579     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8580     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8581 {
8582 	int32_t acked;
8583 	uint16_t nsegs;
8584 	uint32_t sack_changed;
8585 	uint32_t prev_acked = 0;
8586 	struct tcp_bbr *bbr;
8587 
8588 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8589 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8590 		return (0);
8591 	}
8592 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8593 		/* Above what we have sent? */
8594 		return (0);
8595 	}
8596 	if (__predict_false(tiwin == 0)) {
8597 		/* zero window */
8598 		return (0);
8599 	}
8600 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8601 		/* We need a SYN or a FIN, unlikely.. */
8602 		return (0);
8603 	}
8604 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8605 		/* Timestamp is behind .. old ack with seq wrap? */
8606 		return (0);
8607 	}
8608 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8609 		/* Still recovering */
8610 		return (0);
8611 	}
8612 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8613 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8614 		/* We are retransmitting */
8615 		return (0);
8616 	}
8617 	if (__predict_false(bbr->rc_in_persist != 0)) {
8618 		/* In persist mode */
8619 		return (0);
8620 	}
8621 	if (bbr->r_ctl.rc_sacked) {
8622 		/* We have sack holes on our scoreboard */
8623 		return (0);
8624 	}
8625 	/* Ok if we reach here, we can process a fast-ack */
8626 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8627 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8628 	/*
8629 	 * We never detect loss in fast ack [we can't
8630 	 * have a sack and can't be in recovery so
8631 	 * we always pass 0 (nothing detected)].
8632 	 */
8633 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8634 	/* Did the window get updated? */
8635 	if (tiwin != tp->snd_wnd) {
8636 		tp->snd_wnd = tiwin;
8637 		tp->snd_wl1 = th->th_seq;
8638 		if (tp->snd_wnd > tp->max_sndwnd)
8639 			tp->max_sndwnd = tp->snd_wnd;
8640 	}
8641 	/* Do we need to exit persists? */
8642 	if ((bbr->rc_in_persist != 0) &&
8643 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8644 			       bbr_minseg(bbr)))) {
8645 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8646 		bbr->r_wanted_output = 1;
8647 	}
8648 	/* Do we need to enter persists? */
8649 	if ((bbr->rc_in_persist == 0) &&
8650 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8651 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8652 	    (tp->snd_max == tp->snd_una) &&
8653 	    sbavail(&so->so_snd) &&
8654 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8655 		/* No send window.. we must enter persist */
8656 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8657 	}
8658 	/*
8659 	 * If last ACK falls within this segment's sequence numbers, record
8660 	 * the timestamp. NOTE that the test is modified according to the
8661 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8662 	 */
8663 	if ((to->to_flags & TOF_TS) != 0 &&
8664 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8665 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8666 		tp->ts_recent = to->to_tsval;
8667 	}
8668 	/*
8669 	 * This is a pure ack for outstanding data.
8670 	 */
8671 	KMOD_TCPSTAT_INC(tcps_predack);
8672 
8673 	/*
8674 	 * "bad retransmit" recovery.
8675 	 */
8676 	if (tp->t_flags & TF_PREVVALID) {
8677 		tp->t_flags &= ~TF_PREVVALID;
8678 		if (tp->t_rxtshift == 1 &&
8679 		    (int)(ticks - tp->t_badrxtwin) < 0)
8680 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8681 	}
8682 	/*
8683 	 * Recalculate the transmit timer / rtt.
8684 	 *
8685 	 * Some boxes send broken timestamp replies during the SYN+ACK
8686 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8687 	 * and blow up the retransmit timer.
8688 	 */
8689 	acked = BYTES_THIS_ACK(tp, th);
8690 
8691 #ifdef TCP_HHOOK
8692 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8693 	hhook_run_tcp_est_in(tp, th, to);
8694 #endif
8695 
8696 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8697 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8698 	sbdrop(&so->so_snd, acked);
8699 
8700 	if (SEQ_GT(th->th_ack, tp->snd_una))
8701 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8702 	tp->snd_una = th->th_ack;
8703 	if (tp->snd_wnd < ctf_outstanding(tp))
8704 		/* The peer collapsed its window on us */
8705 		bbr_collapsed_window(bbr);
8706 	else if (bbr->rc_has_collapsed)
8707 		bbr_un_collapse_window(bbr);
8708 
8709 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8710 		tp->snd_recover = tp->snd_una;
8711 	}
8712 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8713 	/*
8714 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8715 	 */
8716 	tp->snd_wl2 = th->th_ack;
8717 	m_freem(m);
8718 	/*
8719 	 * If all outstanding data are acked, stop retransmit timer,
8720 	 * otherwise restart timer using current (possibly backed-off)
8721 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8722 	 * If data are ready to send, let tcp_output decide between more
8723 	 * output or persist.
8724 	 * Wake up the socket if we have room to write more.
8725 	 */
8726 	sowwakeup(so);
8727 	if (tp->snd_una == tp->snd_max) {
8728 		/* Nothing left outstanding */
8729 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8730 		if (sbavail(&so->so_snd) == 0)
8731 			bbr->rc_tp->t_acktime = 0;
8732 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8733 		if (bbr->rc_in_persist == 0) {
8734 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8735 		}
8736 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8737 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8738 		/*
8739 		 * We invalidate the last ack here since we
8740 		 * don't want to transfer forward the time
8741 		 * for our sum's calculations.
8742 		 */
8743 		bbr->r_wanted_output = 1;
8744 	}
8745 	if (sbavail(&so->so_snd)) {
8746 		bbr->r_wanted_output = 1;
8747 	}
8748 	return (1);
8749 }
8750 
8751 /*
8752  * Return value of 1, the TCB is unlocked and most
8753  * likely gone, return value of 0, the TCB is still
8754  * locked.
8755  */
8756 static int
8757 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8758     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8759     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8760 {
8761 	int32_t todrop;
8762 	int32_t ourfinisacked = 0;
8763 	struct tcp_bbr *bbr;
8764 	int32_t ret_val = 0;
8765 
8766 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8767 
8768 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8769 	ctf_calc_rwin(so, tp);
8770 	/*
8771 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8772 	 * SYN, drop the input. if seg contains a RST, then drop the
8773 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8774 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8775 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8776 	 * not support ECN so we will not say we are capable. if SYN has
8777 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8778 	 * segment to be acked (eventually) continue processing rest of
8779 	 * data/controls, beginning with URG
8780 	 */
8781 	if ((thflags & TH_ACK) &&
8782 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8783 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8784 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8785 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8786 		return (1);
8787 	}
8788 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8789 		TCP_PROBE5(connect__refused, NULL, tp,
8790 		    mtod(m, const char *), tp, th);
8791 		tp = tcp_drop(tp, ECONNREFUSED);
8792 		ctf_do_drop(m, tp);
8793 		return (1);
8794 	}
8795 	if (thflags & TH_RST) {
8796 		ctf_do_drop(m, tp);
8797 		return (1);
8798 	}
8799 	if (!(thflags & TH_SYN)) {
8800 		ctf_do_drop(m, tp);
8801 		return (1);
8802 	}
8803 	tp->irs = th->th_seq;
8804 	tcp_rcvseqinit(tp);
8805 	if (thflags & TH_ACK) {
8806 		int tfo_partial = 0;
8807 
8808 		KMOD_TCPSTAT_INC(tcps_connects);
8809 		soisconnected(so);
8810 #ifdef MAC
8811 		mac_socketpeer_set_from_mbuf(m, so);
8812 #endif
8813 		/* Do window scaling on this connection? */
8814 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8815 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8816 			tp->rcv_scale = tp->request_r_scale;
8817 		}
8818 		tp->rcv_adv += min(tp->rcv_wnd,
8819 		    TCP_MAXWIN << tp->rcv_scale);
8820 		/*
8821 		 * If not all the data that was sent in the TFO SYN
8822 		 * has been acked, resend the remainder right away.
8823 		 */
8824 		if ((tp->t_flags & TF_FASTOPEN) &&
8825 		    (tp->snd_una != tp->snd_max)) {
8826 			tp->snd_nxt = th->th_ack;
8827 			tfo_partial = 1;
8828 		}
8829 		/*
8830 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8831 		 * will be turned on later.
8832 		 */
8833 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8834 			bbr->bbr_segs_rcvd += 1;
8835 			tp->t_flags |= TF_DELACK;
8836 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8837 		} else {
8838 			bbr->r_wanted_output = 1;
8839 			tp->t_flags |= TF_ACKNOW;
8840 		}
8841 		if (SEQ_GT(th->th_ack, tp->iss)) {
8842 			/*
8843 			 * The SYN is acked
8844 			 * handle it specially.
8845 			 */
8846 			bbr_log_syn(tp, to);
8847 		}
8848 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8849 			/*
8850 			 * We advance snd_una for the
8851 			 * fast open case. If th_ack is
8852 			 * acknowledging data beyond
8853 			 * snd_una we can't just call
8854 			 * ack-processing since the
8855 			 * data stream in our send-map
8856 			 * will start at snd_una + 1 (one
8857 			 * beyond the SYN). If its just
8858 			 * equal we don't need to do that
8859 			 * and there is no send_map.
8860 			 */
8861 			tp->snd_una++;
8862 		}
8863 		/*
8864 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8865 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8866 		 */
8867 		tp->t_starttime = ticks;
8868 		if (tp->t_flags & TF_NEEDFIN) {
8869 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8870 			tp->t_flags &= ~TF_NEEDFIN;
8871 			thflags &= ~TH_SYN;
8872 		} else {
8873 			tcp_state_change(tp, TCPS_ESTABLISHED);
8874 			TCP_PROBE5(connect__established, NULL, tp,
8875 			    mtod(m, const char *), tp, th);
8876 			cc_conn_init(tp);
8877 		}
8878 	} else {
8879 		/*
8880 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8881 		 * open.  If segment contains CC option and there is a
8882 		 * cached CC, apply TAO test. If it succeeds, connection is *
8883 		 * half-synchronized. Otherwise, do 3-way handshake:
8884 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8885 		 * there was no CC option, clear cached CC value.
8886 		 */
8887 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
8888 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8889 	}
8890 	/*
8891 	 * Advance th->th_seq to correspond to first data byte. If data,
8892 	 * trim to stay within window, dropping FIN if necessary.
8893 	 */
8894 	th->th_seq++;
8895 	if (tlen > tp->rcv_wnd) {
8896 		todrop = tlen - tp->rcv_wnd;
8897 		m_adj(m, -todrop);
8898 		tlen = tp->rcv_wnd;
8899 		thflags &= ~TH_FIN;
8900 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8901 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8902 	}
8903 	tp->snd_wl1 = th->th_seq - 1;
8904 	tp->rcv_up = th->th_seq;
8905 	/*
8906 	 * Client side of transaction: already sent SYN and data. If the
8907 	 * remote host used T/TCP to validate the SYN, our data will be
8908 	 * ACK'd; if so, enter normal data segment processing in the middle
8909 	 * of step 5, ack processing. Otherwise, goto step 6.
8910 	 */
8911 	if (thflags & TH_ACK) {
8912 		if ((to->to_flags & TOF_TS) != 0) {
8913 			uint32_t t, rtt;
8914 
8915 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8916 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8917 				rtt = t - to->to_tsecr;
8918 				if (rtt == 0) {
8919 					rtt = 1;
8920 				}
8921 				rtt *= MS_IN_USEC;
8922 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8923 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8924 						       rtt, bbr->r_ctl.rc_rcvtime);
8925 			}
8926 		}
8927 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8928 			return (ret_val);
8929 		/* We may have changed to FIN_WAIT_1 above */
8930 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8931 			/*
8932 			 * In FIN_WAIT_1 STATE in addition to the processing
8933 			 * for the ESTABLISHED state if our FIN is now
8934 			 * acknowledged then enter FIN_WAIT_2.
8935 			 */
8936 			if (ourfinisacked) {
8937 				/*
8938 				 * If we can't receive any more data, then
8939 				 * closing user can proceed. Starting the
8940 				 * timer is contrary to the specification,
8941 				 * but if we don't get a FIN we'll hang
8942 				 * forever.
8943 				 *
8944 				 * XXXjl: we should release the tp also, and
8945 				 * use a compressed state.
8946 				 */
8947 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8948 					soisdisconnected(so);
8949 					tcp_timer_activate(tp, TT_2MSL,
8950 					    (tcp_fast_finwait2_recycle ?
8951 					    tcp_finwait2_timeout :
8952 					    TP_MAXIDLE(tp)));
8953 				}
8954 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8955 			}
8956 		}
8957 	}
8958 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8959 	    tiwin, thflags, nxt_pkt));
8960 }
8961 
8962 /*
8963  * Return value of 1, the TCB is unlocked and most
8964  * likely gone, return value of 0, the TCB is still
8965  * locked.
8966  */
8967 static int
8968 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8969 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8970 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8971 {
8972 	int32_t ourfinisacked = 0;
8973 	int32_t ret_val;
8974 	struct tcp_bbr *bbr;
8975 
8976 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8977 
8978 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8979 	ctf_calc_rwin(so, tp);
8980 	if ((thflags & TH_RST) ||
8981 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
8982 		return (ctf_process_rst(m, th, so, tp));
8983 	if ((thflags & TH_ACK) &&
8984 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8985 	     SEQ_GT(th->th_ack, tp->snd_max))) {
8986 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8987 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8988 		return (1);
8989 	}
8990 	if (tp->t_flags & TF_FASTOPEN) {
8991 		/*
8992 		 * When a TFO connection is in SYN_RECEIVED, the only valid
8993 		 * packets are the initial SYN, a retransmit/copy of the
8994 		 * initial SYN (possibly with a subset of the original
8995 		 * data), a valid ACK, a FIN, or a RST.
8996 		 */
8997 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
8998 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8999 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9000 			return (1);
9001 		} else if (thflags & TH_SYN) {
9002 			/* non-initial SYN is ignored */
9003 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
9004 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
9005 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
9006 				ctf_do_drop(m, NULL);
9007 				return (0);
9008 			}
9009 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
9010 			ctf_do_drop(m, NULL);
9011 			return (0);
9012 		}
9013 	}
9014 	/*
9015 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9016 	 * it's less than ts_recent, drop it.
9017 	 */
9018 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9019 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9020 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9021 			return (ret_val);
9022 	}
9023 	/*
9024 	 * In the SYN-RECEIVED state, validate that the packet belongs to
9025 	 * this connection before trimming the data to fit the receive
9026 	 * window.  Check the sequence number versus IRS since we know the
9027 	 * sequence numbers haven't wrapped.  This is a partial fix for the
9028 	 * "LAND" DoS attack.
9029 	 */
9030 	if (SEQ_LT(th->th_seq, tp->irs)) {
9031 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9032 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9033 		return (1);
9034 	}
9035 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9036 		return (ret_val);
9037 	}
9038 	/*
9039 	 * If last ACK falls within this segment's sequence numbers, record
9040 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9041 	 * from the latest proposal of the tcplw@cray.com list (Braden
9042 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9043 	 * with our earlier PAWS tests, so this check should be solely
9044 	 * predicated on the sequence space of this segment. 3) That we
9045 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9046 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9047 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9048 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9049 	 * p.869. In such cases, we can still calculate the RTT correctly
9050 	 * when RCV.NXT == Last.ACK.Sent.
9051 	 */
9052 	if ((to->to_flags & TOF_TS) != 0 &&
9053 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9054 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9055 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9056 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9057 		tp->ts_recent = to->to_tsval;
9058 	}
9059 	tp->snd_wnd = tiwin;
9060 	/*
9061 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9062 	 * is on (half-synchronized state), then queue data for later
9063 	 * processing; else drop segment and return.
9064 	 */
9065 	if ((thflags & TH_ACK) == 0) {
9066 		if (tp->t_flags & TF_FASTOPEN) {
9067 			cc_conn_init(tp);
9068 		}
9069 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9070 					 tiwin, thflags, nxt_pkt));
9071 	}
9072 	KMOD_TCPSTAT_INC(tcps_connects);
9073 	if (tp->t_flags & TF_SONOTCONN) {
9074 		tp->t_flags &= ~TF_SONOTCONN;
9075 		soisconnected(so);
9076 	}
9077 	/* Do window scaling? */
9078 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9079 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9080 		tp->rcv_scale = tp->request_r_scale;
9081 	}
9082 	/*
9083 	 * ok for the first time in lets see if we can use the ts to figure
9084 	 * out what the initial RTT was.
9085 	 */
9086 	if ((to->to_flags & TOF_TS) != 0) {
9087 		uint32_t t, rtt;
9088 
9089 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9090 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9091 			rtt = t - to->to_tsecr;
9092 			if (rtt == 0) {
9093 				rtt = 1;
9094 			}
9095 			rtt *= MS_IN_USEC;
9096 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9097 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9098 		}
9099 	}
9100 	/* Drop off any SYN in the send map (probably not there)  */
9101 	if (thflags & TH_ACK)
9102 		bbr_log_syn(tp, to);
9103 	if ((tp->t_flags & TF_FASTOPEN) && tp->t_tfo_pending) {
9104 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9105 		tp->t_tfo_pending = NULL;
9106 	}
9107 	/*
9108 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9109 	 * FIN-WAIT-1
9110 	 */
9111 	tp->t_starttime = ticks;
9112 	if (tp->t_flags & TF_NEEDFIN) {
9113 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9114 		tp->t_flags &= ~TF_NEEDFIN;
9115 	} else {
9116 		tcp_state_change(tp, TCPS_ESTABLISHED);
9117 		TCP_PROBE5(accept__established, NULL, tp,
9118 			   mtod(m, const char *), tp, th);
9119 		/*
9120 		 * TFO connections call cc_conn_init() during SYN
9121 		 * processing.  Calling it again here for such connections
9122 		 * is not harmless as it would undo the snd_cwnd reduction
9123 		 * that occurs when a TFO SYN|ACK is retransmitted.
9124 		 */
9125 		if (!(tp->t_flags & TF_FASTOPEN))
9126 			cc_conn_init(tp);
9127 	}
9128 	/*
9129 	 * Account for the ACK of our SYN prior to
9130 	 * regular ACK processing below, except for
9131 	 * simultaneous SYN, which is handled later.
9132 	 */
9133 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9134 		tp->snd_una++;
9135 	/*
9136 	 * If segment contains data or ACK, will call tcp_reass() later; if
9137 	 * not, do so now to pass queued data to user.
9138 	 */
9139 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9140 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9141 			(struct mbuf *)0);
9142 		if (tp->t_flags & TF_WAKESOR) {
9143 			tp->t_flags &= ~TF_WAKESOR;
9144 			/* NB: sorwakeup_locked() does an implicit unlock. */
9145 			sorwakeup_locked(so);
9146 		}
9147 	}
9148 	tp->snd_wl1 = th->th_seq - 1;
9149 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9150 		return (ret_val);
9151 	}
9152 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9153 		/* We could have went to FIN_WAIT_1 (or EST) above */
9154 		/*
9155 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9156 		 * ESTABLISHED state if our FIN is now acknowledged then
9157 		 * enter FIN_WAIT_2.
9158 		 */
9159 		if (ourfinisacked) {
9160 			/*
9161 			 * If we can't receive any more data, then closing
9162 			 * user can proceed. Starting the timer is contrary
9163 			 * to the specification, but if we don't get a FIN
9164 			 * we'll hang forever.
9165 			 *
9166 			 * XXXjl: we should release the tp also, and use a
9167 			 * compressed state.
9168 			 */
9169 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9170 				soisdisconnected(so);
9171 				tcp_timer_activate(tp, TT_2MSL,
9172 						   (tcp_fast_finwait2_recycle ?
9173 						    tcp_finwait2_timeout :
9174 						    TP_MAXIDLE(tp)));
9175 			}
9176 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9177 		}
9178 	}
9179 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9180 				 tiwin, thflags, nxt_pkt));
9181 }
9182 
9183 /*
9184  * Return value of 1, the TCB is unlocked and most
9185  * likely gone, return value of 0, the TCB is still
9186  * locked.
9187  */
9188 static int
9189 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9190     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9191     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9192 {
9193 	struct tcp_bbr *bbr;
9194 	int32_t ret_val;
9195 
9196 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9197 
9198 	/*
9199 	 * Header prediction: check for the two common cases of a
9200 	 * uni-directional data xfer.  If the packet has no control flags,
9201 	 * is in-sequence, the window didn't change and we're not
9202 	 * retransmitting, it's a candidate.  If the length is zero and the
9203 	 * ack moved forward, we're the sender side of the xfer.  Just free
9204 	 * the data acked & wake any higher level process that was blocked
9205 	 * waiting for space.  If the length is non-zero and the ack didn't
9206 	 * move, we're the receiver side.  If we're getting packets in-order
9207 	 * (the reassembly queue is empty), add the data toc The socket
9208 	 * buffer and note that we need a delayed ack. Make sure that the
9209 	 * hidden state-flags are also off. Since we check for
9210 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9211 	 */
9212 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9213 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9214 		/*
9215 		 * If we have delived under 4 segments increase the initial
9216 		 * window if raised by the peer. We use this to determine
9217 		 * dynamic and static rwnd's at the end of a connection.
9218 		 */
9219 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9220 	}
9221 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9222 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9223 	    __predict_true(SEGQ_EMPTY(tp)) &&
9224 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9225 		if (tlen == 0) {
9226 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9227 			    tiwin, nxt_pkt, iptos)) {
9228 				return (0);
9229 			}
9230 		} else {
9231 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9232 			    tiwin, nxt_pkt)) {
9233 				return (0);
9234 			}
9235 		}
9236 	}
9237 	ctf_calc_rwin(so, tp);
9238 
9239 	if ((thflags & TH_RST) ||
9240 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9241 		return (ctf_process_rst(m, th, so, tp));
9242 	/*
9243 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9244 	 * synchronized state.
9245 	 */
9246 	if (thflags & TH_SYN) {
9247 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9248 		return (ret_val);
9249 	}
9250 	/*
9251 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9252 	 * it's less than ts_recent, drop it.
9253 	 */
9254 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9255 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9256 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9257 			return (ret_val);
9258 	}
9259 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9260 		return (ret_val);
9261 	}
9262 	/*
9263 	 * If last ACK falls within this segment's sequence numbers, record
9264 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9265 	 * from the latest proposal of the tcplw@cray.com list (Braden
9266 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9267 	 * with our earlier PAWS tests, so this check should be solely
9268 	 * predicated on the sequence space of this segment. 3) That we
9269 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9270 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9271 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9272 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9273 	 * p.869. In such cases, we can still calculate the RTT correctly
9274 	 * when RCV.NXT == Last.ACK.Sent.
9275 	 */
9276 	if ((to->to_flags & TOF_TS) != 0 &&
9277 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9278 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9279 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9280 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9281 		tp->ts_recent = to->to_tsval;
9282 	}
9283 	/*
9284 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9285 	 * is on (half-synchronized state), then queue data for later
9286 	 * processing; else drop segment and return.
9287 	 */
9288 	if ((thflags & TH_ACK) == 0) {
9289 		if (tp->t_flags & TF_NEEDSYN) {
9290 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9291 			    tiwin, thflags, nxt_pkt));
9292 		} else if (tp->t_flags & TF_ACKNOW) {
9293 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9294 			bbr->r_wanted_output = 1;
9295 			return (ret_val);
9296 		} else {
9297 			ctf_do_drop(m, NULL);
9298 			return (0);
9299 		}
9300 	}
9301 	/*
9302 	 * Ack processing.
9303 	 */
9304 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9305 		return (ret_val);
9306 	}
9307 	if (sbavail(&so->so_snd)) {
9308 		if (ctf_progress_timeout_check(tp, true)) {
9309 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9310 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9311 			return (1);
9312 		}
9313 	}
9314 	/* State changes only happen in bbr_process_data() */
9315 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9316 	    tiwin, thflags, nxt_pkt));
9317 }
9318 
9319 /*
9320  * Return value of 1, the TCB is unlocked and most
9321  * likely gone, return value of 0, the TCB is still
9322  * locked.
9323  */
9324 static int
9325 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9326     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9327     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9328 {
9329 	struct tcp_bbr *bbr;
9330 	int32_t ret_val;
9331 
9332 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9333 
9334 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9335 	ctf_calc_rwin(so, tp);
9336 	if ((thflags & TH_RST) ||
9337 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9338 		return (ctf_process_rst(m, th, so, tp));
9339 	/*
9340 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9341 	 * synchronized state.
9342 	 */
9343 	if (thflags & TH_SYN) {
9344 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9345 		return (ret_val);
9346 	}
9347 	/*
9348 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9349 	 * it's less than ts_recent, drop it.
9350 	 */
9351 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9352 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9353 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9354 			return (ret_val);
9355 	}
9356 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9357 		return (ret_val);
9358 	}
9359 	/*
9360 	 * If last ACK falls within this segment's sequence numbers, record
9361 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9362 	 * from the latest proposal of the tcplw@cray.com list (Braden
9363 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9364 	 * with our earlier PAWS tests, so this check should be solely
9365 	 * predicated on the sequence space of this segment. 3) That we
9366 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9367 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9368 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9369 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9370 	 * p.869. In such cases, we can still calculate the RTT correctly
9371 	 * when RCV.NXT == Last.ACK.Sent.
9372 	 */
9373 	if ((to->to_flags & TOF_TS) != 0 &&
9374 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9375 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9376 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9377 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9378 		tp->ts_recent = to->to_tsval;
9379 	}
9380 	/*
9381 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9382 	 * is on (half-synchronized state), then queue data for later
9383 	 * processing; else drop segment and return.
9384 	 */
9385 	if ((thflags & TH_ACK) == 0) {
9386 		if (tp->t_flags & TF_NEEDSYN) {
9387 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9388 			    tiwin, thflags, nxt_pkt));
9389 		} else if (tp->t_flags & TF_ACKNOW) {
9390 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9391 			bbr->r_wanted_output = 1;
9392 			return (ret_val);
9393 		} else {
9394 			ctf_do_drop(m, NULL);
9395 			return (0);
9396 		}
9397 	}
9398 	/*
9399 	 * Ack processing.
9400 	 */
9401 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9402 		return (ret_val);
9403 	}
9404 	if (sbavail(&so->so_snd)) {
9405 		if (ctf_progress_timeout_check(tp, true)) {
9406 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9407 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9408 			return (1);
9409 		}
9410 	}
9411 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9412 	    tiwin, thflags, nxt_pkt));
9413 }
9414 
9415 static int
9416 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9417     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9418 {
9419 
9420 	if (bbr->rc_allow_data_af_clo == 0) {
9421 close_now:
9422 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9423 		/* tcp_close will kill the inp pre-log the Reset */
9424 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9425 		tp = tcp_close(tp);
9426 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9427 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9428 		return (1);
9429 	}
9430 	if (sbavail(&so->so_snd) == 0)
9431 		goto close_now;
9432 	/* Ok we allow data that is ignored and a followup reset */
9433 	tp->rcv_nxt = th->th_seq + *tlen;
9434 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9435 	bbr->r_wanted_output = 1;
9436 	*tlen = 0;
9437 	return (0);
9438 }
9439 
9440 /*
9441  * Return value of 1, the TCB is unlocked and most
9442  * likely gone, return value of 0, the TCB is still
9443  * locked.
9444  */
9445 static int
9446 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9447     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9448     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9449 {
9450 	int32_t ourfinisacked = 0;
9451 	int32_t ret_val;
9452 	struct tcp_bbr *bbr;
9453 
9454 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9455 
9456 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9457 	ctf_calc_rwin(so, tp);
9458 	if ((thflags & TH_RST) ||
9459 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9460 		return (ctf_process_rst(m, th, so, tp));
9461 	/*
9462 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9463 	 * synchronized state.
9464 	 */
9465 	if (thflags & TH_SYN) {
9466 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9467 		return (ret_val);
9468 	}
9469 	/*
9470 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9471 	 * it's less than ts_recent, drop it.
9472 	 */
9473 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9474 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9475 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9476 			return (ret_val);
9477 	}
9478 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9479 		return (ret_val);
9480 	}
9481 	/*
9482 	 * If new data are received on a connection after the user processes
9483 	 * are gone, then RST the other end.
9484 	 * We call a new function now so we might continue and setup
9485 	 * to reset at all data being ack'd.
9486 	 */
9487 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9488 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9489 		return (1);
9490 	/*
9491 	 * If last ACK falls within this segment's sequence numbers, record
9492 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9493 	 * from the latest proposal of the tcplw@cray.com list (Braden
9494 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9495 	 * with our earlier PAWS tests, so this check should be solely
9496 	 * predicated on the sequence space of this segment. 3) That we
9497 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9498 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9499 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9500 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9501 	 * p.869. In such cases, we can still calculate the RTT correctly
9502 	 * when RCV.NXT == Last.ACK.Sent.
9503 	 */
9504 	if ((to->to_flags & TOF_TS) != 0 &&
9505 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9506 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9507 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9508 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9509 		tp->ts_recent = to->to_tsval;
9510 	}
9511 	/*
9512 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9513 	 * is on (half-synchronized state), then queue data for later
9514 	 * processing; else drop segment and return.
9515 	 */
9516 	if ((thflags & TH_ACK) == 0) {
9517 		if (tp->t_flags & TF_NEEDSYN) {
9518 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9519 			    tiwin, thflags, nxt_pkt));
9520 		} else if (tp->t_flags & TF_ACKNOW) {
9521 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9522 			bbr->r_wanted_output = 1;
9523 			return (ret_val);
9524 		} else {
9525 			ctf_do_drop(m, NULL);
9526 			return (0);
9527 		}
9528 	}
9529 	/*
9530 	 * Ack processing.
9531 	 */
9532 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9533 		return (ret_val);
9534 	}
9535 	if (ourfinisacked) {
9536 		/*
9537 		 * If we can't receive any more data, then closing user can
9538 		 * proceed. Starting the timer is contrary to the
9539 		 * specification, but if we don't get a FIN we'll hang
9540 		 * forever.
9541 		 *
9542 		 * XXXjl: we should release the tp also, and use a
9543 		 * compressed state.
9544 		 */
9545 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9546 			soisdisconnected(so);
9547 			tcp_timer_activate(tp, TT_2MSL,
9548 			    (tcp_fast_finwait2_recycle ?
9549 			    tcp_finwait2_timeout :
9550 			    TP_MAXIDLE(tp)));
9551 		}
9552 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9553 	}
9554 	if (sbavail(&so->so_snd)) {
9555 		if (ctf_progress_timeout_check(tp, true)) {
9556 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9557 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9558 			return (1);
9559 		}
9560 	}
9561 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9562 	    tiwin, thflags, nxt_pkt));
9563 }
9564 
9565 /*
9566  * Return value of 1, the TCB is unlocked and most
9567  * likely gone, return value of 0, the TCB is still
9568  * locked.
9569  */
9570 static int
9571 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9572     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9573     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9574 {
9575 	int32_t ourfinisacked = 0;
9576 	int32_t ret_val;
9577 	struct tcp_bbr *bbr;
9578 
9579 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9580 
9581 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9582 	ctf_calc_rwin(so, tp);
9583 	if ((thflags & TH_RST) ||
9584 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9585 		return (ctf_process_rst(m, th, so, tp));
9586 	/*
9587 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9588 	 * synchronized state.
9589 	 */
9590 	if (thflags & TH_SYN) {
9591 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9592 		return (ret_val);
9593 	}
9594 	/*
9595 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9596 	 * it's less than ts_recent, drop it.
9597 	 */
9598 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9599 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9600 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9601 			return (ret_val);
9602 	}
9603 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9604 		return (ret_val);
9605 	}
9606 	/*
9607 	 * If last ACK falls within this segment's sequence numbers, record
9608 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9609 	 * from the latest proposal of the tcplw@cray.com list (Braden
9610 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9611 	 * with our earlier PAWS tests, so this check should be solely
9612 	 * predicated on the sequence space of this segment. 3) That we
9613 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9614 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9615 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9616 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9617 	 * p.869. In such cases, we can still calculate the RTT correctly
9618 	 * when RCV.NXT == Last.ACK.Sent.
9619 	 */
9620 	if ((to->to_flags & TOF_TS) != 0 &&
9621 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9622 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9623 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9624 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9625 		tp->ts_recent = to->to_tsval;
9626 	}
9627 	/*
9628 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9629 	 * is on (half-synchronized state), then queue data for later
9630 	 * processing; else drop segment and return.
9631 	 */
9632 	if ((thflags & TH_ACK) == 0) {
9633 		if (tp->t_flags & TF_NEEDSYN) {
9634 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9635 			    tiwin, thflags, nxt_pkt));
9636 		} else if (tp->t_flags & TF_ACKNOW) {
9637 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9638 			bbr->r_wanted_output = 1;
9639 			return (ret_val);
9640 		} else {
9641 			ctf_do_drop(m, NULL);
9642 			return (0);
9643 		}
9644 	}
9645 	/*
9646 	 * Ack processing.
9647 	 */
9648 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9649 		return (ret_val);
9650 	}
9651 	if (ourfinisacked) {
9652 		tcp_twstart(tp);
9653 		m_freem(m);
9654 		return (1);
9655 	}
9656 	if (sbavail(&so->so_snd)) {
9657 		if (ctf_progress_timeout_check(tp, true)) {
9658 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9659 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9660 			return (1);
9661 		}
9662 	}
9663 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9664 	    tiwin, thflags, nxt_pkt));
9665 }
9666 
9667 /*
9668  * Return value of 1, the TCB is unlocked and most
9669  * likely gone, return value of 0, the TCB is still
9670  * locked.
9671  */
9672 static int
9673 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9674     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9675     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9676 {
9677 	int32_t ourfinisacked = 0;
9678 	int32_t ret_val;
9679 	struct tcp_bbr *bbr;
9680 
9681 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9682 
9683 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9684 	ctf_calc_rwin(so, tp);
9685 	if ((thflags & TH_RST) ||
9686 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9687 		return (ctf_process_rst(m, th, so, tp));
9688 	/*
9689 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9690 	 * synchronized state.
9691 	 */
9692 	if (thflags & TH_SYN) {
9693 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9694 		return (ret_val);
9695 	}
9696 	/*
9697 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9698 	 * it's less than ts_recent, drop it.
9699 	 */
9700 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9701 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9702 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9703 			return (ret_val);
9704 	}
9705 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9706 		return (ret_val);
9707 	}
9708 	/*
9709 	 * If last ACK falls within this segment's sequence numbers, record
9710 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9711 	 * from the latest proposal of the tcplw@cray.com list (Braden
9712 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9713 	 * with our earlier PAWS tests, so this check should be solely
9714 	 * predicated on the sequence space of this segment. 3) That we
9715 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9716 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9717 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9718 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9719 	 * p.869. In such cases, we can still calculate the RTT correctly
9720 	 * when RCV.NXT == Last.ACK.Sent.
9721 	 */
9722 	if ((to->to_flags & TOF_TS) != 0 &&
9723 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9724 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9725 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9726 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9727 		tp->ts_recent = to->to_tsval;
9728 	}
9729 	/*
9730 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9731 	 * is on (half-synchronized state), then queue data for later
9732 	 * processing; else drop segment and return.
9733 	 */
9734 	if ((thflags & TH_ACK) == 0) {
9735 		if (tp->t_flags & TF_NEEDSYN) {
9736 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9737 			    tiwin, thflags, nxt_pkt));
9738 		} else if (tp->t_flags & TF_ACKNOW) {
9739 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9740 			bbr->r_wanted_output = 1;
9741 			return (ret_val);
9742 		} else {
9743 			ctf_do_drop(m, NULL);
9744 			return (0);
9745 		}
9746 	}
9747 	/*
9748 	 * case TCPS_LAST_ACK: Ack processing.
9749 	 */
9750 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9751 		return (ret_val);
9752 	}
9753 	if (ourfinisacked) {
9754 		tp = tcp_close(tp);
9755 		ctf_do_drop(m, tp);
9756 		return (1);
9757 	}
9758 	if (sbavail(&so->so_snd)) {
9759 		if (ctf_progress_timeout_check(tp, true)) {
9760 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9761 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9762 			return (1);
9763 		}
9764 	}
9765 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9766 	    tiwin, thflags, nxt_pkt));
9767 }
9768 
9769 /*
9770  * Return value of 1, the TCB is unlocked and most
9771  * likely gone, return value of 0, the TCB is still
9772  * locked.
9773  */
9774 static int
9775 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9776     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9777     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9778 {
9779 	int32_t ourfinisacked = 0;
9780 	int32_t ret_val;
9781 	struct tcp_bbr *bbr;
9782 
9783 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9784 
9785 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9786 	ctf_calc_rwin(so, tp);
9787 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9788 	if ((thflags & TH_RST) ||
9789 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9790 		return (ctf_process_rst(m, th, so, tp));
9791 
9792 	/*
9793 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9794 	 * synchronized state.
9795 	 */
9796 	if (thflags & TH_SYN) {
9797 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9798 		return (ret_val);
9799 	}
9800 	/*
9801 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9802 	 * it's less than ts_recent, drop it.
9803 	 */
9804 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9805 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9806 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9807 			return (ret_val);
9808 	}
9809 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9810 		return (ret_val);
9811 	}
9812 	/*
9813 	 * If new data are received on a connection after the user processes
9814 	 * are gone, then we may RST the other end depending on the outcome
9815 	 * of bbr_check_data_after_close.
9816 	 * We call a new function now so we might continue and setup
9817 	 * to reset at all data being ack'd.
9818 	 */
9819 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9820 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9821 		return (1);
9822 	/*
9823 	 * If last ACK falls within this segment's sequence numbers, record
9824 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9825 	 * from the latest proposal of the tcplw@cray.com list (Braden
9826 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9827 	 * with our earlier PAWS tests, so this check should be solely
9828 	 * predicated on the sequence space of this segment. 3) That we
9829 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9830 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9831 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9832 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9833 	 * p.869. In such cases, we can still calculate the RTT correctly
9834 	 * when RCV.NXT == Last.ACK.Sent.
9835 	 */
9836 	if ((to->to_flags & TOF_TS) != 0 &&
9837 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9838 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9839 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9840 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9841 		tp->ts_recent = to->to_tsval;
9842 	}
9843 	/*
9844 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9845 	 * is on (half-synchronized state), then queue data for later
9846 	 * processing; else drop segment and return.
9847 	 */
9848 	if ((thflags & TH_ACK) == 0) {
9849 		if (tp->t_flags & TF_NEEDSYN) {
9850 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9851 			    tiwin, thflags, nxt_pkt));
9852 		} else if (tp->t_flags & TF_ACKNOW) {
9853 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9854 			bbr->r_wanted_output = 1;
9855 			return (ret_val);
9856 		} else {
9857 			ctf_do_drop(m, NULL);
9858 			return (0);
9859 		}
9860 	}
9861 	/*
9862 	 * Ack processing.
9863 	 */
9864 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9865 		return (ret_val);
9866 	}
9867 	if (sbavail(&so->so_snd)) {
9868 		if (ctf_progress_timeout_check(tp, true)) {
9869 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9870 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9871 			return (1);
9872 		}
9873 	}
9874 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9875 	    tiwin, thflags, nxt_pkt));
9876 }
9877 
9878 static void
9879 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr)
9880 {
9881 	/*
9882 	 * Assure no timers are running.
9883 	 */
9884 	if (tcp_timer_active(tp, TT_PERSIST)) {
9885 		/* We enter in persists, set the flag appropriately */
9886 		bbr->rc_in_persist = 1;
9887 	}
9888 	if (tcp_in_hpts(bbr->rc_tp)) {
9889 		tcp_hpts_remove(bbr->rc_tp);
9890 	}
9891 }
9892 
9893 static void
9894 bbr_google_mode_on(struct tcp_bbr *bbr)
9895 {
9896 	bbr->rc_use_google = 1;
9897 	bbr->rc_no_pacing = 0;
9898 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9899 	bbr->r_use_policer = bbr_policer_detection_enabled;
9900 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9901 	bbr->bbr_use_rack_cheat = 0;
9902 	bbr->r_ctl.rc_incr_tmrs = 0;
9903 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9904 	bbr->r_ctl.rc_inc_ip_oh = 0;
9905 	bbr->r_ctl.rc_inc_enet_oh = 0;
9906 	reset_time(&bbr->r_ctl.rc_delrate,
9907 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9908 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9909 			 (11 * USECS_IN_SECOND));
9910 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9911 }
9912 
9913 static void
9914 bbr_google_mode_off(struct tcp_bbr *bbr)
9915 {
9916 	bbr->rc_use_google = 0;
9917 	bbr->r_ctl.bbr_google_discount = 0;
9918 	bbr->no_pacing_until = bbr_no_pacing_until;
9919 	bbr->r_use_policer = 0;
9920 	if (bbr->no_pacing_until)
9921 		bbr->rc_no_pacing = 1;
9922 	else
9923 		bbr->rc_no_pacing = 0;
9924 	if (bbr_use_rack_resend_cheat)
9925 		bbr->bbr_use_rack_cheat = 1;
9926 	else
9927 		bbr->bbr_use_rack_cheat = 0;
9928 	if (bbr_incr_timers)
9929 		bbr->r_ctl.rc_incr_tmrs = 1;
9930 	else
9931 		bbr->r_ctl.rc_incr_tmrs = 0;
9932 	if (bbr_include_tcp_oh)
9933 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9934 	else
9935 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9936 	if (bbr_include_ip_oh)
9937 		bbr->r_ctl.rc_inc_ip_oh = 1;
9938 	else
9939 		bbr->r_ctl.rc_inc_ip_oh = 0;
9940 	if (bbr_include_enet_oh)
9941 		bbr->r_ctl.rc_inc_enet_oh = 1;
9942 	else
9943 		bbr->r_ctl.rc_inc_enet_oh = 0;
9944 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9945 	reset_time(&bbr->r_ctl.rc_delrate,
9946 		   bbr_num_pktepo_for_del_limit);
9947 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9948 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9949 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9950 }
9951 /*
9952  * Return 0 on success, non-zero on failure
9953  * which indicates the error (usually no memory).
9954  */
9955 static int
9956 bbr_init(struct tcpcb *tp, void **ptr)
9957 {
9958 	struct inpcb *inp = tptoinpcb(tp);
9959 	struct tcp_bbr *bbr = NULL;
9960 	uint32_t cts;
9961 
9962 	tcp_hpts_init(tp);
9963 
9964 	*ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
9965 	if (*ptr == NULL) {
9966 		/*
9967 		 * We need to allocate memory but cant. The INP and INP_INFO
9968 		 * locks and they are recursive (happens during setup. So a
9969 		 * scheme to drop the locks fails :(
9970 		 *
9971 		 */
9972 		return (ENOMEM);
9973 	}
9974 	bbr = (struct tcp_bbr *)*ptr;
9975 	bbr->rtt_valid = 0;
9976 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
9977 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
9978 	/* Take off any undesired flags */
9979 	tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
9980 	tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
9981 	tp->t_flags2 &= ~TF2_MBUF_ACKCMP;
9982 	tp->t_flags2 &= ~TF2_MBUF_L_ACKS;
9983 
9984 	TAILQ_INIT(&bbr->r_ctl.rc_map);
9985 	TAILQ_INIT(&bbr->r_ctl.rc_free);
9986 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
9987 	bbr->rc_tp = tp;
9988 	bbr->rc_inp = inp;
9989 	cts = tcp_get_usecs(&bbr->rc_tv);
9990 	tp->t_acktime = 0;
9991 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
9992 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
9993 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
9994 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
9995 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
9996 	bbr->r_ctl.rc_min_to = bbr_min_to;
9997 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
9998 	bbr->r_ctl.bbr_lost_at_state = 0;
9999 	bbr->r_ctl.rc_lost_at_startup = 0;
10000 	bbr->rc_all_timers_stopped = 0;
10001 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10002 	bbr->r_ctl.rc_pkt_epoch_del = 0;
10003 	bbr->r_ctl.rc_pkt_epoch = 0;
10004 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10005 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10006 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10007 	bbr->r_ctl.rc_went_idle_time = cts;
10008 	bbr->rc_pacer_started = cts;
10009 	bbr->r_ctl.rc_pkt_epoch_time = cts;
10010 	bbr->r_ctl.rc_rcvtime = cts;
10011 	bbr->r_ctl.rc_bbr_state_time = cts;
10012 	bbr->r_ctl.rc_del_time = cts;
10013 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10014 	bbr->r_ctl.last_in_probertt = cts;
10015 	bbr->skip_gain = 0;
10016 	bbr->gain_is_limited = 0;
10017 	bbr->no_pacing_until = bbr_no_pacing_until;
10018 	if (bbr->no_pacing_until)
10019 		bbr->rc_no_pacing = 1;
10020 	if (bbr_use_google_algo) {
10021 		bbr->rc_no_pacing = 0;
10022 		bbr->rc_use_google = 1;
10023 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10024 		bbr->r_use_policer = bbr_policer_detection_enabled;
10025 	} else {
10026 		bbr->rc_use_google = 0;
10027 		bbr->r_ctl.bbr_google_discount = 0;
10028 		bbr->r_use_policer = 0;
10029 	}
10030 	if (bbr_ts_limiting)
10031 		bbr->rc_use_ts_limit = 1;
10032 	else
10033 		bbr->rc_use_ts_limit = 0;
10034 	if (bbr_ts_can_raise)
10035 		bbr->ts_can_raise = 1;
10036 	else
10037 		bbr->ts_can_raise = 0;
10038 	if (V_tcp_delack_enabled == 1)
10039 		tp->t_delayed_ack = 2;
10040 	else if (V_tcp_delack_enabled == 0)
10041 		tp->t_delayed_ack = 0;
10042 	else if (V_tcp_delack_enabled < 100)
10043 		tp->t_delayed_ack = V_tcp_delack_enabled;
10044 	else
10045 		tp->t_delayed_ack = 2;
10046 	if (bbr->rc_use_google == 0)
10047 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10048 	else
10049 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10050 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10051 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10052 	bbr->rc_init_win = bbr_def_init_win;
10053 	if (tp->t_flags & TF_REQ_TSTMP)
10054 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10055 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10056 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10057 	bbr->r_init_rtt = 1;
10058 
10059 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10060 	if (bbr_allow_hdwr_pacing)
10061 		bbr->bbr_hdw_pace_ena = 1;
10062 	else
10063 		bbr->bbr_hdw_pace_ena = 0;
10064 	if (bbr_sends_full_iwnd)
10065 		bbr->bbr_init_win_cheat = 1;
10066 	else
10067 		bbr->bbr_init_win_cheat = 0;
10068 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10069 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10070 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10071 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10072 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10073 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10074 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10075 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10076 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10077 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10078 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10079 	bbr->r_ctl.rc_rtt_shrinks = cts;
10080 	if (bbr->rc_use_google) {
10081 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10082 				  FILTER_TYPE_MAX,
10083 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10084 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10085 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10086 	} else {
10087 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10088 				  FILTER_TYPE_MAX,
10089 				  bbr_num_pktepo_for_del_limit);
10090 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10091 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10092 	}
10093 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10094 	if (bbr_uses_idle_restart)
10095 		bbr->rc_use_idle_restart = 1;
10096 	else
10097 		bbr->rc_use_idle_restart = 0;
10098 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10099 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10100 	if (bbr_resends_use_tso)
10101 		bbr->rc_resends_use_tso = 1;
10102 	if (tp->snd_una != tp->snd_max) {
10103 		/* Create a send map for the current outstanding data */
10104 		struct bbr_sendmap *rsm;
10105 
10106 		rsm = bbr_alloc(bbr);
10107 		if (rsm == NULL) {
10108 			uma_zfree(bbr_pcb_zone, *ptr);
10109 			*ptr = NULL;
10110 			return (ENOMEM);
10111 		}
10112 		rsm->r_rtt_not_allowed = 1;
10113 		rsm->r_tim_lastsent[0] = cts;
10114 		rsm->r_rtr_cnt = 1;
10115 		rsm->r_rtr_bytes = 0;
10116 		rsm->r_start = tp->snd_una;
10117 		rsm->r_end = tp->snd_max;
10118 		rsm->r_dupack = 0;
10119 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10120 		rsm->r_ts_valid = 0;
10121 		rsm->r_del_ack_ts = tp->ts_recent;
10122 		rsm->r_del_time = cts;
10123 		if (bbr->r_ctl.r_app_limited_until)
10124 			rsm->r_app_limited = 1;
10125 		else
10126 			rsm->r_app_limited = 0;
10127 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10128 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10129 		rsm->r_in_tmap = 1;
10130 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10131 			rsm->r_bbr_state = bbr_state_val(bbr);
10132 		else
10133 			rsm->r_bbr_state = 8;
10134 	}
10135 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10136 		bbr->bbr_use_rack_cheat = 1;
10137 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10138 		bbr->r_ctl.rc_incr_tmrs = 1;
10139 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10140 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10141 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10142 		bbr->r_ctl.rc_inc_ip_oh = 1;
10143 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10144 		bbr->r_ctl.rc_inc_enet_oh = 1;
10145 
10146 	bbr_log_type_statechange(bbr, cts, __LINE__);
10147 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10148 	    (tp->t_srtt)) {
10149 		uint32_t rtt;
10150 
10151 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10152 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10153 	}
10154 	/* announce the settings and state */
10155 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10156 	tcp_bbr_tso_size_check(bbr, cts);
10157 	/*
10158 	 * Now call the generic function to start a timer. This will place
10159 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10160 	 * flags.
10161 	 */
10162 	bbr_stop_all_timers(tp, bbr);
10163 	/*
10164 	 * Validate the timers are not in usec, if they are convert.
10165 	 * BBR should in theory move to USEC and get rid of a
10166 	 * lot of the TICKS_2 calls.. but for now we stay
10167 	 * with tick timers.
10168 	 */
10169 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
10170 	TCPT_RANGESET(tp->t_rxtcur,
10171 	    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
10172 	    tp->t_rttmin, TCPTV_REXMTMAX);
10173 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10174 	return (0);
10175 }
10176 
10177 /*
10178  * Return 0 if we can accept the connection. Return
10179  * non-zero if we can't handle the connection. A EAGAIN
10180  * means you need to wait until the connection is up.
10181  * a EADDRNOTAVAIL means we can never handle the connection
10182  * (no SACK).
10183  */
10184 static int
10185 bbr_handoff_ok(struct tcpcb *tp)
10186 {
10187 	if ((tp->t_state == TCPS_CLOSED) ||
10188 	    (tp->t_state == TCPS_LISTEN)) {
10189 		/* Sure no problem though it may not stick */
10190 		return (0);
10191 	}
10192 	if ((tp->t_state == TCPS_SYN_SENT) ||
10193 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10194 		/*
10195 		 * We really don't know you have to get to ESTAB or beyond
10196 		 * to tell.
10197 		 */
10198 		return (EAGAIN);
10199 	}
10200 	if (tp->t_flags & TF_SENTFIN)
10201 		return (EINVAL);
10202 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10203 		return (0);
10204 	}
10205 	/*
10206 	 * If we reach here we don't do SACK on this connection so we can
10207 	 * never do rack.
10208 	 */
10209 	return (EINVAL);
10210 }
10211 
10212 static void
10213 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10214 {
10215 	if (tp->t_fb_ptr) {
10216 		uint32_t calc;
10217 		struct tcp_bbr *bbr;
10218 		struct bbr_sendmap *rsm;
10219 
10220 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10221 		if (bbr->r_ctl.crte)
10222 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10223 		bbr_log_flowend(bbr);
10224 		bbr->rc_tp = NULL;
10225 		if (bbr->bbr_hdrw_pacing)
10226 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10227 		else
10228 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10229 		if (bbr->r_ctl.crte != NULL) {
10230 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10231 			bbr->r_ctl.crte = NULL;
10232 		}
10233 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10234 		while (rsm) {
10235 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10236 			uma_zfree(bbr_zone, rsm);
10237 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10238 		}
10239 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10240 		while (rsm) {
10241 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10242 			uma_zfree(bbr_zone, rsm);
10243 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10244 		}
10245 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10246 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10247 			BBR_STAT_INC(bbr_dynamic_rwnd);
10248 		else
10249 			BBR_STAT_INC(bbr_static_rwnd);
10250 		bbr->r_ctl.rc_free_cnt = 0;
10251 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10252 		tp->t_fb_ptr = NULL;
10253 	}
10254 	/* Make sure snd_nxt is correctly set */
10255 	tp->snd_nxt = tp->snd_max;
10256 }
10257 
10258 static void
10259 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10260 {
10261 	switch (tp->t_state) {
10262 	case TCPS_SYN_SENT:
10263 		bbr->r_state = TCPS_SYN_SENT;
10264 		bbr->r_substate = bbr_do_syn_sent;
10265 		break;
10266 	case TCPS_SYN_RECEIVED:
10267 		bbr->r_state = TCPS_SYN_RECEIVED;
10268 		bbr->r_substate = bbr_do_syn_recv;
10269 		break;
10270 	case TCPS_ESTABLISHED:
10271 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10272 		bbr->r_state = TCPS_ESTABLISHED;
10273 		bbr->r_substate = bbr_do_established;
10274 		break;
10275 	case TCPS_CLOSE_WAIT:
10276 		bbr->r_state = TCPS_CLOSE_WAIT;
10277 		bbr->r_substate = bbr_do_close_wait;
10278 		break;
10279 	case TCPS_FIN_WAIT_1:
10280 		bbr->r_state = TCPS_FIN_WAIT_1;
10281 		bbr->r_substate = bbr_do_fin_wait_1;
10282 		break;
10283 	case TCPS_CLOSING:
10284 		bbr->r_state = TCPS_CLOSING;
10285 		bbr->r_substate = bbr_do_closing;
10286 		break;
10287 	case TCPS_LAST_ACK:
10288 		bbr->r_state = TCPS_LAST_ACK;
10289 		bbr->r_substate = bbr_do_lastack;
10290 		break;
10291 	case TCPS_FIN_WAIT_2:
10292 		bbr->r_state = TCPS_FIN_WAIT_2;
10293 		bbr->r_substate = bbr_do_fin_wait_2;
10294 		break;
10295 	case TCPS_LISTEN:
10296 	case TCPS_CLOSED:
10297 	case TCPS_TIME_WAIT:
10298 	default:
10299 		break;
10300 	};
10301 }
10302 
10303 static void
10304 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10305 {
10306 	/*
10307 	 * Now what state are we going into now? Is there adjustments
10308 	 * needed?
10309 	 */
10310 	int32_t old_state;
10311 
10312 	old_state = bbr_state_val(bbr);
10313 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10314 		/* Save the lowest srtt we saw in our end of the sub-state */
10315 		bbr->rc_hit_state_1 = 0;
10316 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10317 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10318 	}
10319 	bbr->rc_bbr_substate++;
10320 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10321 		/* Cycle back to first state-> gain */
10322 		bbr->rc_bbr_substate = 0;
10323 	}
10324 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10325 		/*
10326 		 * We enter the gain(5/4) cycle (possibly less if
10327 		 * shallow buffer detection is enabled)
10328 		 */
10329 		if (bbr->skip_gain) {
10330 			/*
10331 			 * Hardware pacing has set our rate to
10332 			 * the max and limited our b/w just
10333 			 * do level i.e. no gain.
10334 			 */
10335 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10336 		} else if (bbr->gain_is_limited &&
10337 			   bbr->bbr_hdrw_pacing &&
10338 			   bbr->r_ctl.crte) {
10339 			/*
10340 			 * We can't gain above the hardware pacing
10341 			 * rate which is less than our rate + the gain
10342 			 * calculate the gain needed to reach the hardware
10343 			 * pacing rate..
10344 			 */
10345 			uint64_t bw, rate, gain_calc;
10346 
10347 			bw = bbr_get_bw(bbr);
10348 			rate = bbr->r_ctl.crte->rate;
10349 			if ((rate > bw) &&
10350 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10351 				gain_calc = (rate * BBR_UNIT) / bw;
10352 				if (gain_calc < BBR_UNIT)
10353 					gain_calc = BBR_UNIT;
10354 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10355 			} else {
10356 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10357 			}
10358 		} else
10359 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10360 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10361 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10362 		} else
10363 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10364 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10365 		bbr->rc_hit_state_1 = 1;
10366 		bbr->r_ctl.rc_exta_time_gd = 0;
10367 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10368 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10369 		if (bbr_state_drain_2_tar) {
10370 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10371 		} else
10372 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10373 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10374 	} else {
10375 		/* All other cycles hit here 2-7 */
10376 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10377 			if (bbr_sub_drain_slam_cwnd &&
10378 			    (bbr->rc_use_google == 0) &&
10379 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10380 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10381 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10382 			}
10383 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10384 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10385 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10386 			else
10387 				bbr->r_ctl.rc_exta_time_gd = 0;
10388 			if (bbr->r_ctl.rc_exta_time_gd) {
10389 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10390 				/* Now chop up the time for each state (div by 7) */
10391 				bbr->r_ctl.rc_level_state_extra /= 7;
10392 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10393 					/* Add a randomization */
10394 					bbr_randomize_extra_state_time(bbr);
10395 				}
10396 			}
10397 		}
10398 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10399 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10400 	}
10401 	if (bbr->rc_use_google) {
10402 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10403 	}
10404 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10405 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10406 	if (dolog)
10407 		bbr_log_type_statechange(bbr, cts, line);
10408 
10409 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10410 		uint32_t time_in;
10411 
10412 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10413 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10414 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10415 		} else {
10416 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10417 		}
10418 	}
10419 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10420 	bbr_set_state_target(bbr, __LINE__);
10421 	if (bbr_sub_drain_slam_cwnd &&
10422 	    (bbr->rc_use_google == 0) &&
10423 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10424 		/* Slam down the cwnd */
10425 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10426 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10427 		if (bbr_sub_drain_app_limit) {
10428 			/* Go app limited if we are on a long drain */
10429 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10430 							  ctf_flight_size(bbr->rc_tp,
10431 							      (bbr->r_ctl.rc_sacked +
10432 							       bbr->r_ctl.rc_lost_bytes)));
10433 		}
10434 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10435 	}
10436 	if (bbr->rc_lt_use_bw) {
10437 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10438 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10439 	}
10440 	/* Google changes TSO size every cycle */
10441 	if (bbr->rc_use_google)
10442 		tcp_bbr_tso_size_check(bbr, cts);
10443 	bbr->r_ctl.gain_epoch = cts;
10444 	bbr->r_ctl.rc_bbr_state_time = cts;
10445 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10446 }
10447 
10448 static void
10449 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10450 {
10451 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10452 	    (google_allow_early_out == 1) &&
10453 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10454 		/* We have reached out target flight size possibly early */
10455 		goto change_state;
10456 	}
10457 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10458 		return;
10459 	}
10460 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10461 		/*
10462 		 * Must be a rttProp movement forward before
10463 		 * we can change states.
10464 		 */
10465 		return;
10466 	}
10467 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10468 		/*
10469 		 * The needed time has passed but for
10470 		 * the gain cycle extra rules apply:
10471 		 * 1) If we have seen loss, we exit
10472 		 * 2) If we have not reached the target
10473 		 *    we stay in GAIN (gain-to-target).
10474 		 */
10475 		if (google_consider_lost && losses)
10476 			goto change_state;
10477 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10478 			return;
10479 		}
10480 	}
10481 change_state:
10482 	/* For gain we must reach our target, all others last 1 rttProp */
10483 	bbr_substate_change(bbr, cts, __LINE__, 1);
10484 }
10485 
10486 static void
10487 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10488 {
10489 	uint32_t flight, bbr_cur_cycle_time;
10490 
10491 	if (bbr->rc_use_google) {
10492 		bbr_set_probebw_google_gains(bbr, cts, losses);
10493 		return;
10494 	}
10495 	if (cts == 0) {
10496 		/*
10497 		 * Never alow cts to be 0 we
10498 		 * do this so we can judge if
10499 		 * we have set a timestamp.
10500 		 */
10501 		cts = 1;
10502 	}
10503 	if (bbr_state_is_pkt_epoch)
10504 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10505 	else
10506 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10507 
10508 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10509 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10510 			flight = ctf_flight_size(bbr->rc_tp,
10511 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10512 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10513 				/* Keep it slam down */
10514 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10515 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10516 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10517 				}
10518 				if (bbr_sub_drain_app_limit) {
10519 					/* Go app limited if we are on a long drain */
10520 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10521 				}
10522 			}
10523 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10524 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10525 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10526 				/*
10527 				 * Still here after the same time as
10528 				 * the gain. We need to drain harder
10529 				 * for the next srtt. Reduce by a set amount
10530 				 * the gain drop is capped at DRAIN states
10531 				 * value (88).
10532 				 */
10533 				bbr->r_ctl.flightsize_at_drain = flight;
10534 				if (bbr_drain_drop_mul &&
10535 				    bbr_drain_drop_div &&
10536 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10537 					/* Use your specific drop value (def 4/5 = 20%) */
10538 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10539 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10540 				} else {
10541 					/* You get drop of 20% */
10542 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10543 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10544 				}
10545 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10546 					/* Reduce our gain again to the bottom  */
10547 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10548 				}
10549 				bbr_log_exit_gain(bbr, cts, 4);
10550 				/*
10551 				 * Extend out so we wait another
10552 				 * epoch before dropping again.
10553 				 */
10554 				bbr->r_ctl.gain_epoch = cts;
10555 			}
10556 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10557 				if (bbr_sub_drain_slam_cwnd &&
10558 				    (bbr->rc_use_google == 0) &&
10559 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10560 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10561 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10562 				}
10563 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10564 				bbr_log_exit_gain(bbr, cts, 3);
10565 			}
10566 		} else {
10567 			/* Its a gain  */
10568 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10569 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10570 				goto change_state;
10571 			}
10572 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10573 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10574 			     bbr->rc_tp->snd_wnd)) {
10575 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10576 				bbr_log_exit_gain(bbr, cts, 2);
10577 			}
10578 		}
10579 		/**
10580 		 * We fall through and return always one of two things has
10581 		 * occurred.
10582 		 * 1) We are still not at target
10583 		 *    <or>
10584 		 * 2) We reached the target and set rc_bbr_state_atflight
10585 		 *    which means we no longer hit this block
10586 		 *    next time we are called.
10587 		 */
10588 		return;
10589 	}
10590 change_state:
10591 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10592 		return;
10593 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10594 		/* Less than a full time-period has passed */
10595 		return;
10596 	}
10597 	if (bbr->r_ctl.rc_level_state_extra &&
10598 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10599 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10600 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10601 		/* Less than a full time-period + extra has passed */
10602 		return;
10603 	}
10604 	if (bbr_gain_gets_extra_too &&
10605 	    bbr->r_ctl.rc_level_state_extra &&
10606 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10607 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10608 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10609 		/* Less than a full time-period + extra has passed */
10610 		return;
10611 	}
10612 	bbr_substate_change(bbr, cts, __LINE__, 1);
10613 }
10614 
10615 static uint32_t
10616 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10617 {
10618 	uint32_t mss, tar;
10619 
10620 	if (bbr->rc_use_google) {
10621 		/* Google just uses the cwnd target */
10622 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10623 	} else {
10624 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10625 			  bbr->r_ctl.rc_pace_max_segs);
10626 		/* Get the base cwnd with gain rounded to a mss */
10627 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10628 						      gain), mss);
10629 		/* Make sure it is within our min */
10630 		if (tar < get_min_cwnd(bbr))
10631 			return (get_min_cwnd(bbr));
10632 	}
10633 	return (tar);
10634 }
10635 
10636 static void
10637 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10638 {
10639 	uint32_t tar, meth;
10640 
10641 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10642 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10643 		/* Special case using old probe-rtt method */
10644 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10645 		meth = 1;
10646 	} else {
10647 		/* Non-probe-rtt case and reduced probe-rtt  */
10648 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10649 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10650 			/* For gain cycle we use the hptsi gain */
10651 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10652 			meth = 2;
10653 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10654 			/*
10655 			 * If configured, or for google all other states
10656 			 * get BBR_UNIT.
10657 			 */
10658 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10659 			meth = 3;
10660 		} else {
10661 			/*
10662 			 * Or we set a target based on the pacing gain
10663 			 * for non-google mode and default (non-configured).
10664 			 * Note we don't set a target goal below drain (192).
10665 			 */
10666 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10667 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10668 				meth = 4;
10669 			} else {
10670 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10671 				meth = 5;
10672 			}
10673 		}
10674 	}
10675 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10676 	bbr->r_ctl.rc_target_at_state = tar;
10677 }
10678 
10679 static void
10680 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10681 {
10682 	/* Change to probe_rtt */
10683 	uint32_t time_in;
10684 
10685 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10686 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10687 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10688 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10689 					  + bbr->r_ctl.rc_delivered);
10690 	/* Setup so we force feed the filter */
10691 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10692 		bbr->rc_prtt_set_ts = 1;
10693 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10694 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10695 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10696 	}
10697 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10698 	bbr->r_ctl.rc_rtt_shrinks = cts;
10699 	bbr->r_ctl.last_in_probertt = cts;
10700 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10701 	bbr->r_ctl.rc_bbr_state_time = cts;
10702 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10703 	/* We need to force the filter to update */
10704 
10705 	if ((bbr_sub_drain_slam_cwnd) &&
10706 	    bbr->rc_hit_state_1 &&
10707 	    (bbr->rc_use_google == 0) &&
10708 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10709 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10710 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10711 	} else
10712 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10713 	/* Update the lost */
10714 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10715 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10716 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10717 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10718 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10719 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10720 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10721 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10722 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10723 	} else {
10724 		/*
10725 		 * We bring it down slowly by using a hptsi gain that is
10726 		 * probably 75%. This will slowly float down our outstanding
10727 		 * without tampering with the cwnd.
10728 		 */
10729 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10730 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10731 		bbr_set_state_target(bbr, __LINE__);
10732 		if (bbr_prtt_slam_cwnd &&
10733 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10734 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10735 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10736 		}
10737 	}
10738 	if (ctf_flight_size(bbr->rc_tp,
10739 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10740 	    bbr->r_ctl.rc_target_at_state) {
10741 		/* We are at target */
10742 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10743 	} else {
10744 		/* We need to come down to reach target before our time begins */
10745 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10746 	}
10747 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10748 	BBR_STAT_INC(bbr_enter_probertt);
10749 	bbr_log_exit_gain(bbr, cts, 0);
10750 	bbr_log_type_statechange(bbr, cts, line);
10751 }
10752 
10753 static void
10754 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10755 {
10756 	/*
10757 	 * Sanity check on probe-rtt intervals.
10758 	 * In crazy situations where we are competing
10759 	 * against new-reno flows with huge buffers
10760 	 * our rtt-prop interval could come to dominate
10761 	 * things if we can't get through a full set
10762 	 * of cycles, we need to adjust it.
10763 	 */
10764 	if (bbr_can_adjust_probertt &&
10765 	    (bbr->rc_use_google == 0)) {
10766 		uint16_t val = 0;
10767 		uint32_t cur_rttp, fval, newval, baseval;
10768 
10769 		/* Are we to small and go into probe-rtt to often? */
10770 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10771 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10772 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10773 		if (bbr_is_ratio == 0) {
10774 			if (fval > bbr_rtt_probe_limit)
10775 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10776 			else
10777 				newval = cur_rttp;
10778 		} else {
10779 			int mul;
10780 
10781 			mul = fval / bbr_rtt_probe_limit;
10782 			newval = cur_rttp * mul;
10783 		}
10784 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10785 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10786 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10787 			val = 1;
10788 		} else {
10789 			/*
10790 			 * No adjustments were made
10791 			 * do we need to shrink it?
10792 			 */
10793 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10794 				if (cur_rttp <= bbr_rtt_probe_limit) {
10795 					/*
10796 					 * Things have calmed down lets
10797 					 * shrink all the way to default
10798 					 */
10799 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10800 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10801 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10802 					cur_rttp = bbr_rtt_probe_limit;
10803 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10804 					val = 2;
10805 				} else {
10806 					/*
10807 					 * Well does some adjustment make sense?
10808 					 */
10809 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10810 						/* We can reduce interval time some */
10811 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10812 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10813 						val = 3;
10814 					}
10815 				}
10816 			}
10817 		}
10818 		if (val)
10819 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10820 	}
10821 }
10822 
10823 static void
10824 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10825 {
10826 	/* Exit probe-rtt */
10827 
10828 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10829 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10830 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10831 	}
10832 	bbr_log_exit_gain(bbr, cts, 1);
10833 	bbr->rc_hit_state_1 = 0;
10834 	bbr->r_ctl.rc_rtt_shrinks = cts;
10835 	bbr->r_ctl.last_in_probertt = cts;
10836 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10837 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10838 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10839 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10840 					  bbr->r_ctl.rc_delivered);
10841 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10842 		uint32_t time_in;
10843 
10844 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10845 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10846 	}
10847 	if (bbr->rc_filled_pipe) {
10848 		/* Switch to probe_bw */
10849 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10850 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10851 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10852 		bbr_substate_change(bbr, cts, __LINE__, 0);
10853 		bbr_log_type_statechange(bbr, cts, __LINE__);
10854 	} else {
10855 		/* Back to startup */
10856 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10857 		bbr->r_ctl.rc_bbr_state_time = cts;
10858 		/*
10859 		 * We don't want to give a complete free 3
10860 		 * measurements until we exit, so we use
10861 		 * the number of pe's we were in probe-rtt
10862 		 * to add to the startup_epoch. That way
10863 		 * we will still retain the old state.
10864 		 */
10865 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10866 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10867 		/* Make sure to use the lower pg when shifting back in */
10868 		if (bbr->r_ctl.rc_lost &&
10869 		    bbr_use_lower_gain_in_startup &&
10870 		    (bbr->rc_use_google == 0))
10871 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10872 		else
10873 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10874 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10875 		/* Probably not needed but set it anyway */
10876 		bbr_set_state_target(bbr, __LINE__);
10877 		bbr_log_type_statechange(bbr, cts, __LINE__);
10878 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10879 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10880 	}
10881 	bbr_check_probe_rtt_limits(bbr, cts);
10882 }
10883 
10884 static int32_t inline
10885 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10886 {
10887 	if ((bbr->rc_past_init_win == 1) &&
10888 	    (bbr->rc_in_persist == 0) &&
10889 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10890 		return (1);
10891 	}
10892 	if (bbr_can_force_probertt &&
10893 	    (bbr->rc_in_persist == 0) &&
10894 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10895 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10896 		return (1);
10897 	}
10898 	return (0);
10899 }
10900 
10901 static int32_t
10902 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10903 {
10904 	uint64_t btlbw, gain;
10905 	if (pkt_epoch == 0) {
10906 		/*
10907 		 * Need to be on a pkt-epoch to continue.
10908 		 */
10909 		return (0);
10910 	}
10911 	btlbw = bbr_get_full_bw(bbr);
10912 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10913 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10914 	if (btlbw >= gain) {
10915 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10916 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10917 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10918 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10919 	}
10920 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10921 		return (1);
10922 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10923 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10924 	return(0);
10925 }
10926 
10927 static int32_t inline
10928 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10929 {
10930 	/* Have we gained 25% in the last 3 packet based epoch's? */
10931 	uint64_t btlbw, gain;
10932 	int do_exit;
10933 	int delta, rtt_gain;
10934 
10935 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10936 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10937 		/*
10938 		 * This qualifies as a RTT_PROBE session since we drop the
10939 		 * data outstanding to nothing and waited more than
10940 		 * bbr_rtt_probe_time.
10941 		 */
10942 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10943 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10944 	}
10945 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10946 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10947 		return (0);
10948 	}
10949 	if (bbr->rc_use_google)
10950 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10951 
10952 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10953 	    (bbr_use_lower_gain_in_startup)) {
10954 		/* Drop to a lower gain 1.5 x since we saw loss */
10955 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10956 	}
10957 	if (pkt_epoch == 0) {
10958 		/*
10959 		 * Need to be on a pkt-epoch to continue.
10960 		 */
10961 		return (0);
10962 	}
10963 	if (bbr_rtt_gain_thresh) {
10964 		/*
10965 		 * Do we allow a flow to stay
10966 		 * in startup with no loss and no
10967 		 * gain in rtt over a set threshold?
10968 		 */
10969 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
10970 		    bbr->r_ctl.startup_last_srtt &&
10971 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
10972 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
10973 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
10974 		} else
10975 			rtt_gain = 0;
10976 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
10977 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
10978 			/* First time or new lower value */
10979 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
10980 
10981 		if ((bbr->r_ctl.rc_lost == 0) &&
10982 		    (rtt_gain < bbr_rtt_gain_thresh)) {
10983 			/*
10984 			 * No loss, and we are under
10985 			 * our gain threhold for
10986 			 * increasing RTT.
10987 			 */
10988 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10989 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
10990 			bbr_log_startup_event(bbr, cts, rtt_gain,
10991 					      delta, bbr->r_ctl.startup_last_srtt, 10);
10992 			return (0);
10993 		}
10994 	}
10995 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
10996 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
10997 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
10998 		/*
10999 		 * We only assess if we have a new measurement when
11000 		 * we have no loss and are not in recovery.
11001 		 * Drag up by one our last_startup epoch so we will hold
11002 		 * the number of non-gain we have already accumulated.
11003 		 */
11004 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11005 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
11006 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11007 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11008 		return (0);
11009 	}
11010 	/* Case where we reduced the lost (bad retransmit) */
11011 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11012 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11013 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11014 	btlbw = bbr_get_full_bw(bbr);
11015 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11016 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11017 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11018 	else
11019 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11020 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11021 	do_exit = 0;
11022 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11023 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11024 	if (btlbw >= gain) {
11025 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11026 		/* Update the lost so we won't exit in next set of tests */
11027 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11028 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11029 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11030 	}
11031 	if ((bbr->rc_loss_exit &&
11032 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11033 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11034 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11035 		/*
11036 		 * If we had no gain,  we had loss and that loss was above
11037 		 * our threshould, the rwnd is not constrained, and we have
11038 		 * had at least 3 packet epochs exit. Note that this is
11039 		 * switched off by sysctl. Google does not do this by the
11040 		 * way.
11041 		 */
11042 		if ((ctf_flight_size(bbr->rc_tp,
11043 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11044 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11045 			do_exit = 1;
11046 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11047 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11048 		} else {
11049 			/* Just record an updated loss value */
11050 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11051 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11052 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11053 		}
11054 	} else
11055 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11056 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11057 	    do_exit) {
11058 		/* Return 1 to exit the startup state. */
11059 		return (1);
11060 	}
11061 	/* Stay in startup */
11062 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11063 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11064 	return (0);
11065 }
11066 
11067 static void
11068 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11069 {
11070 	/*
11071 	 * A tick occurred in the rtt epoch do we need to do anything?
11072 	 */
11073 #ifdef BBR_INVARIANTS
11074 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11075 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11076 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11077 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11078 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11079 		/* Debug code? */
11080 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11081 	}
11082 #endif
11083 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11084 		/* Do we exit the startup state? */
11085 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11086 			uint32_t time_in;
11087 
11088 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11089 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11090 			bbr->rc_filled_pipe = 1;
11091 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11092 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11093 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11094 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11095 			} else
11096 				time_in = 0;
11097 			if (bbr->rc_no_pacing)
11098 				bbr->rc_no_pacing = 0;
11099 			bbr->r_ctl.rc_bbr_state_time = cts;
11100 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11101 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11102 			bbr_set_state_target(bbr, __LINE__);
11103 			if ((bbr->rc_use_google == 0) &&
11104 			    bbr_slam_cwnd_in_main_drain) {
11105 				/* Here we don't have to worry about probe-rtt */
11106 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11107 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11108 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11109 			}
11110 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11111 			bbr_log_type_statechange(bbr, cts, __LINE__);
11112 			if (ctf_flight_size(bbr->rc_tp,
11113 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11114 			    bbr->r_ctl.rc_target_at_state) {
11115 				/*
11116 				 * Switch to probe_bw if we are already
11117 				 * there
11118 				 */
11119 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11120 				bbr_substate_change(bbr, cts, __LINE__, 0);
11121 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11122 				bbr_log_type_statechange(bbr, cts, __LINE__);
11123 			}
11124 		}
11125 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11126 		uint32_t inflight;
11127 		struct tcpcb *tp;
11128 
11129 		tp = bbr->rc_tp;
11130 		inflight = ctf_flight_size(tp,
11131 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11132 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11133 			/* We have reached a flight of the cwnd target */
11134 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11135 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11136 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11137 			bbr_set_state_target(bbr, __LINE__);
11138 			/*
11139 			 * Rig it so we don't do anything crazy and
11140 			 * start fresh with a new randomization.
11141 			 */
11142 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11143 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11144 			bbr_substate_change(bbr, cts, __LINE__, 1);
11145 		}
11146 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11147 		/* Has in-flight reached the bdp (or less)? */
11148 		uint32_t inflight;
11149 		struct tcpcb *tp;
11150 
11151 		tp = bbr->rc_tp;
11152 		inflight = ctf_flight_size(tp,
11153 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11154 		if ((bbr->rc_use_google == 0) &&
11155 		    bbr_slam_cwnd_in_main_drain &&
11156 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11157 			/*
11158 			 * Here we don't have to worry about probe-rtt
11159 			 * re-slam it, but keep it slammed down.
11160 			 */
11161 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11162 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11163 		}
11164 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11165 			/* We have drained */
11166 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11167 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11168 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11169 				uint32_t time_in;
11170 
11171 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11172 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11173 			}
11174 			if ((bbr->rc_use_google == 0) &&
11175 			    bbr_slam_cwnd_in_main_drain &&
11176 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11177 				/* Restore the cwnd */
11178 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11179 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11180 			}
11181 			/* Setup probe-rtt has being done now RRS-HERE */
11182 			bbr->r_ctl.rc_rtt_shrinks = cts;
11183 			bbr->r_ctl.last_in_probertt = cts;
11184 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11185 			/* Randomly pick a sub-state */
11186 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11187 			bbr_substate_change(bbr, cts, __LINE__, 0);
11188 			bbr_log_type_statechange(bbr, cts, __LINE__);
11189 		}
11190 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11191 		uint32_t flight;
11192 
11193 		flight = ctf_flight_size(bbr->rc_tp,
11194 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11195 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11196 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11197 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11198 			/*
11199 			 * We must keep cwnd at the desired MSS.
11200 			 */
11201 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11202 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11203 		} else if ((bbr_prtt_slam_cwnd) &&
11204 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11205 			/* Re-slam it */
11206 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11207 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11208 		}
11209 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11210 			/* Has outstanding reached our target? */
11211 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11212 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11213 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11214 				/* If time is exactly 0, be 1usec off */
11215 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11216 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11217 				if (bbr->rc_use_google == 0) {
11218 					/*
11219 					 * Restore any lowering that as occurred to
11220 					 * reach here
11221 					 */
11222 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11223 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11224 					else
11225 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11226 				}
11227 			}
11228 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11229 			    (bbr->rc_use_google == 0) &&
11230 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11231 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11232 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11233 				/*
11234 				 * We have doddled with our current hptsi
11235 				 * gain an srtt and have still not made it
11236 				 * to target, or we have increased our flight.
11237 				 * Lets reduce the gain by xx%
11238 				 * flooring the reduce at DRAIN (based on
11239 				 * mul/div)
11240 				 */
11241 				int red;
11242 
11243 				bbr->r_ctl.flightsize_at_drain = flight;
11244 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11245 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11246 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11247 					/* Reduce our gain again */
11248 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11249 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11250 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11251 					/* one more chance before we give up */
11252 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11253 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11254 				} else {
11255 					/* At the very bottom */
11256 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11257 				}
11258 			}
11259 		}
11260 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11261 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11262 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11263 			/* Time to exit probe RTT normally */
11264 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11265 		}
11266 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11267 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11268 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11269 			/*
11270 			 * This qualifies as a RTT_PROBE session since we
11271 			 * drop the data outstanding to nothing and waited
11272 			 * more than bbr_rtt_probe_time.
11273 			 */
11274 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11275 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11276 		}
11277 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11278 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11279 		} else {
11280 			bbr_set_probebw_gains(bbr, cts, losses);
11281 		}
11282 	}
11283 }
11284 
11285 static void
11286 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11287 {
11288 	int32_t epoch = 0;
11289 
11290 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11291 		bbr_set_epoch(bbr, cts, line);
11292 		/* At each epoch doe lt bw sampling */
11293 		epoch = 1;
11294 	}
11295 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11296 }
11297 
11298 static int
11299 bbr_do_segment_nounlock(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11300     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos, int32_t nxt_pkt,
11301     struct timeval *tv)
11302 {
11303 	struct inpcb *inp = tptoinpcb(tp);
11304 	struct socket *so = tptosocket(tp);
11305 	int32_t thflags, retval;
11306 	uint32_t cts, lcts;
11307 	uint32_t tiwin;
11308 	struct tcpopt to;
11309 	struct tcp_bbr *bbr;
11310 	struct bbr_sendmap *rsm;
11311 	struct timeval ltv;
11312 	int32_t did_out = 0;
11313 	uint16_t nsegs;
11314 	int32_t prev_state;
11315 	uint32_t lost;
11316 
11317 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11318 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11319 	/* add in our stats */
11320 	kern_prefetch(bbr, &prev_state);
11321 	prev_state = 0;
11322 	thflags = tcp_get_flags(th);
11323 	/*
11324 	 * If this is either a state-changing packet or current state isn't
11325 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11326 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11327 	 * caller may have unnecessarily acquired a write lock due to a
11328 	 * race.
11329 	 */
11330 	INP_WLOCK_ASSERT(tptoinpcb(tp));
11331 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11332 	    __func__));
11333 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11334 	    __func__));
11335 
11336 	tp->t_rcvtime = ticks;
11337 	/*
11338 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11339 	 * the scale is zero.
11340 	 */
11341 	tiwin = th->th_win << tp->snd_scale;
11342 #ifdef STATS
11343 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11344 #endif
11345 
11346 	if (m->m_flags & M_TSTMP) {
11347 		/* Prefer the hardware timestamp if present */
11348 		struct timespec ts;
11349 
11350 		mbuf_tstmp2timespec(m, &ts);
11351 		bbr->rc_tv.tv_sec = ts.tv_sec;
11352 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11353 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11354 	} else if (m->m_flags & M_TSTMP_LRO) {
11355 		/* Next the arrival timestamp */
11356 		struct timespec ts;
11357 
11358 		mbuf_tstmp2timespec(m, &ts);
11359 		bbr->rc_tv.tv_sec = ts.tv_sec;
11360 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11361 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11362 	} else {
11363 		/*
11364 		 * Ok just get the current time.
11365 		 */
11366 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11367 	}
11368 	/*
11369 	 * Parse options on any incoming segment.
11370 	 */
11371 	tcp_dooptions(&to, (u_char *)(th + 1),
11372 	    (th->th_off << 2) - sizeof(struct tcphdr),
11373 	    (thflags & TH_SYN) ? TO_SYN : 0);
11374 	if (tp->t_flags2 & TF2_PROC_SACK_PROHIBIT) {
11375 		/*
11376 		 * We don't look at sack's from the
11377 		 * peer because the MSS is too small which
11378 		 * can subject us to an attack.
11379 		 */
11380 		to.to_flags &= ~TOF_SACK;
11381 	}
11382 	/*
11383 	 * If timestamps were negotiated during SYN/ACK and a
11384 	 * segment without a timestamp is received, silently drop
11385 	 * the segment, unless it is a RST segment or missing timestamps are
11386 	 * tolerated.
11387 	 * See section 3.2 of RFC 7323.
11388 	 */
11389 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11390 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11391 		retval = 0;
11392 		m_freem(m);
11393 		goto done_with_input;
11394 	}
11395 	/*
11396 	 * If echoed timestamp is later than the current time, fall back to
11397 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11398 	 * were used when this connection was established.
11399 	 */
11400 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11401 		to.to_tsecr -= tp->ts_offset;
11402 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11403 			to.to_tsecr = 0;
11404 	}
11405 	/*
11406 	 * If its the first time in we need to take care of options and
11407 	 * verify we can do SACK for rack!
11408 	 */
11409 	if (bbr->r_state == 0) {
11410 		/*
11411 		 * Process options only when we get SYN/ACK back. The SYN
11412 		 * case for incoming connections is handled in tcp_syncache.
11413 		 * According to RFC1323 the window field in a SYN (i.e., a
11414 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11415 		 * this is traditional behavior, may need to be cleaned up.
11416 		 */
11417 		if (bbr->rc_inp == NULL) {
11418 			bbr->rc_inp = inp;
11419 		}
11420 		/*
11421 		 * We need to init rc_inp here since its not init'd when
11422 		 * bbr_init is called
11423 		 */
11424 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11425 			if ((to.to_flags & TOF_SCALE) &&
11426 			    (tp->t_flags & TF_REQ_SCALE)) {
11427 				tp->t_flags |= TF_RCVD_SCALE;
11428 				tp->snd_scale = to.to_wscale;
11429 			} else
11430 				tp->t_flags &= ~TF_REQ_SCALE;
11431 			/*
11432 			 * Initial send window.  It will be updated with the
11433 			 * next incoming segment to the scaled value.
11434 			 */
11435 			tp->snd_wnd = th->th_win;
11436 			if ((to.to_flags & TOF_TS) &&
11437 			    (tp->t_flags & TF_REQ_TSTMP)) {
11438 				tp->t_flags |= TF_RCVD_TSTMP;
11439 				tp->ts_recent = to.to_tsval;
11440 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11441 			} else
11442 			    tp->t_flags &= ~TF_REQ_TSTMP;
11443 			if (to.to_flags & TOF_MSS)
11444 				tcp_mss(tp, to.to_mss);
11445 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11446 			    (to.to_flags & TOF_SACKPERM) == 0)
11447 				tp->t_flags &= ~TF_SACK_PERMIT;
11448 			if (tp->t_flags & TF_FASTOPEN) {
11449 				if (to.to_flags & TOF_FASTOPEN) {
11450 					uint16_t mss;
11451 
11452 					if (to.to_flags & TOF_MSS)
11453 						mss = to.to_mss;
11454 					else
11455 						if ((inp->inp_vflag & INP_IPV6) != 0)
11456 							mss = TCP6_MSS;
11457 						else
11458 							mss = TCP_MSS;
11459 					tcp_fastopen_update_cache(tp, mss,
11460 					    to.to_tfo_len, to.to_tfo_cookie);
11461 				} else
11462 					tcp_fastopen_disable_path(tp);
11463 			}
11464 		}
11465 		/*
11466 		 * At this point we are at the initial call. Here we decide
11467 		 * if we are doing RACK or not. We do this by seeing if
11468 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11469 		 * we switch to the default code.
11470 		 */
11471 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11472 			/* Bail */
11473 			tcp_switch_back_to_default(tp);
11474 			(*tp->t_fb->tfb_tcp_do_segment)(tp, m, th, drop_hdrlen,
11475 			    tlen, iptos);
11476 			return (1);
11477 		}
11478 		/* Set the flag */
11479 		bbr->r_is_v6 = (inp->inp_vflag & INP_IPV6) != 0;
11480 		tcp_set_hpts(tp);
11481 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11482 	}
11483 	if (thflags & TH_ACK) {
11484 		/* Track ack types */
11485 		if (to.to_flags & TOF_SACK)
11486 			BBR_STAT_INC(bbr_acks_with_sacks);
11487 		else
11488 			BBR_STAT_INC(bbr_plain_acks);
11489 	}
11490 	/*
11491 	 * This is the one exception case where we set the rack state
11492 	 * always. All other times (timers etc) we must have a rack-state
11493 	 * set (so we assure we have done the checks above for SACK).
11494 	 */
11495 	if (thflags & TH_FIN)
11496 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11497 	if (bbr->r_state != tp->t_state)
11498 		bbr_set_state(tp, bbr, tiwin);
11499 
11500 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11501 		kern_prefetch(rsm, &prev_state);
11502 	prev_state = bbr->r_state;
11503 	bbr->rc_ack_was_delayed = 0;
11504 	lost = bbr->r_ctl.rc_lost;
11505 	bbr->rc_is_pkt_epoch_now = 0;
11506 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11507 		/* Get the real time into lcts and figure the real delay */
11508 		lcts = tcp_get_usecs(&ltv);
11509 		if (TSTMP_GT(lcts, cts)) {
11510 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11511 			bbr->rc_ack_was_delayed = 1;
11512 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11513 				     bbr->r_ctl.highest_hdwr_delay))
11514 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11515 		} else {
11516 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11517 			bbr->rc_ack_was_delayed = 0;
11518 		}
11519 	} else {
11520 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11521 		bbr->rc_ack_was_delayed = 0;
11522 	}
11523 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11524 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11525 		retval = 0;
11526 		m_freem(m);
11527 		goto done_with_input;
11528 	}
11529 	/*
11530 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11531 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11532 	 */
11533 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11534 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11535 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11536 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11537 		return (1);
11538 	}
11539 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11540 		bbr->r_ctl.rc_high_rwnd = tiwin;
11541 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11542 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11543 	bbr->rtt_valid = 0;
11544 	if (to.to_flags & TOF_TS) {
11545 		bbr->rc_ts_valid = 1;
11546 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11547 	} else {
11548 		bbr->rc_ts_valid = 0;
11549 		bbr->r_ctl.last_inbound_ts = 0;
11550 	}
11551 	retval = (*bbr->r_substate) (m, th, so,
11552 	    tp, &to, drop_hdrlen,
11553 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11554 	if (nxt_pkt == 0)
11555 		BBR_STAT_INC(bbr_rlock_left_ret0);
11556 	else
11557 		BBR_STAT_INC(bbr_rlock_left_ret1);
11558 	if (retval == 0) {
11559 		/*
11560 		 * If retval is 1 the tcb is unlocked and most likely the tp
11561 		 * is gone.
11562 		 */
11563 		INP_WLOCK_ASSERT(inp);
11564 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11565 		if (bbr->rc_is_pkt_epoch_now)
11566 			bbr_set_pktepoch(bbr, cts, __LINE__);
11567 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11568 		if (nxt_pkt == 0) {
11569 			if ((bbr->r_wanted_output != 0) ||
11570 			    (tp->t_flags & TF_ACKNOW)) {
11571 
11572 				bbr->rc_output_starts_timer = 0;
11573 				did_out = 1;
11574 				if (tcp_output(tp) < 0)
11575 					return (1);
11576 			} else
11577 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11578 		}
11579 		if ((nxt_pkt == 0) &&
11580 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11581 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11582 		     (tp->t_flags & TF_DELACK) ||
11583 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11584 		      (tp->t_state <= TCPS_CLOSING)))) {
11585 			/*
11586 			 * We could not send (probably in the hpts but
11587 			 * stopped the timer)?
11588 			 */
11589 			if ((tp->snd_max == tp->snd_una) &&
11590 			    ((tp->t_flags & TF_DELACK) == 0) &&
11591 			    (tcp_in_hpts(tp)) &&
11592 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11593 				/*
11594 				 * keep alive not needed if we are hptsi
11595 				 * output yet
11596 				 */
11597 				;
11598 			} else {
11599 				if (tcp_in_hpts(tp)) {
11600 					tcp_hpts_remove(tp);
11601 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11602 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11603 						uint32_t del;
11604 
11605 						del = lcts - bbr->rc_pacer_started;
11606 						if (bbr->r_ctl.rc_last_delay_val > del) {
11607 							BBR_STAT_INC(bbr_force_timer_start);
11608 							bbr->r_ctl.rc_last_delay_val -= del;
11609 							bbr->rc_pacer_started = lcts;
11610 						} else {
11611 							/* We are late */
11612 							bbr->r_ctl.rc_last_delay_val = 0;
11613 							BBR_STAT_INC(bbr_force_output);
11614 							if (tcp_output(tp) < 0)
11615 								return (1);
11616 						}
11617 					}
11618 				}
11619 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11620 				    0);
11621 			}
11622 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11623 			/* Do we have the correct timer running? */
11624 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11625 		}
11626 		/* Clear the flag, it may have been cleared by output but we may not have  */
11627 		if ((nxt_pkt == 0) && (tp->t_flags2 & TF2_HPTS_CALLS))
11628 			tp->t_flags2 &= ~TF2_HPTS_CALLS;
11629 		/* Do we have a new state */
11630 		if (bbr->r_state != tp->t_state)
11631 			bbr_set_state(tp, bbr, tiwin);
11632 done_with_input:
11633 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11634 		if (did_out)
11635 			bbr->r_wanted_output = 0;
11636 	}
11637 	return (retval);
11638 }
11639 
11640 static void
11641 bbr_do_segment(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11642     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11643 {
11644 	struct timeval tv;
11645 	int retval;
11646 
11647 	/* First lets see if we have old packets */
11648 	if (!STAILQ_EMPTY(&tp->t_inqueue)) {
11649 		if (ctf_do_queued_segments(tp, 1)) {
11650 			m_freem(m);
11651 			return;
11652 		}
11653 	}
11654 	if (m->m_flags & M_TSTMP_LRO) {
11655 		mbuf_tstmp2timeval(m, &tv);
11656 	} else {
11657 		/* Should not be should we kassert instead? */
11658 		tcp_get_usecs(&tv);
11659 	}
11660 	retval = bbr_do_segment_nounlock(tp, m, th, drop_hdrlen, tlen, iptos,
11661 	    0, &tv);
11662 	if (retval == 0) {
11663 		INP_WUNLOCK(tptoinpcb(tp));
11664 	}
11665 }
11666 
11667 /*
11668  * Return how much data can be sent without violating the
11669  * cwnd or rwnd.
11670  */
11671 
11672 static inline uint32_t
11673 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11674     uint32_t avail, int32_t sb_offset, uint32_t cts)
11675 {
11676 	uint32_t len;
11677 
11678 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11679 		/* We never want to go over our peers rcv-window */
11680 		len = 0;
11681 	} else {
11682 		uint32_t flight;
11683 
11684 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11685 		if (flight >= sendwin) {
11686 			/*
11687 			 * We have in flight what we are allowed by cwnd (if
11688 			 * it was rwnd blocking it would have hit above out
11689 			 * >= tp->snd_wnd).
11690 			 */
11691 			return (0);
11692 		}
11693 		len = sendwin - flight;
11694 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11695 			/* We would send too much (beyond the rwnd) */
11696 			len = tp->snd_wnd - ctf_outstanding(tp);
11697 		}
11698 		if ((len + sb_offset) > avail) {
11699 			/*
11700 			 * We don't have that much in the SB, how much is
11701 			 * there?
11702 			 */
11703 			len = avail - sb_offset;
11704 		}
11705 	}
11706 	return (len);
11707 }
11708 
11709 static inline void
11710 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11711 {
11712 	if (error) {
11713 		return;
11714 	}
11715 	if (rsm) {
11716 		if (rsm->r_flags & BBR_TLP) {
11717 			/*
11718 			 * TLP should not count in retran count, but in its
11719 			 * own bin
11720 			 */
11721 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11722 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11723 		} else {
11724 			/* Retransmit */
11725 			tp->t_sndrexmitpack++;
11726 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11727 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11728 #ifdef STATS
11729 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11730 			    len);
11731 #endif
11732 		}
11733 		/*
11734 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11735 		 * sub-state
11736 		 */
11737 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11738 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11739 			/* Non probe_bw log in 1, 2, or 4. */
11740 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11741 		} else {
11742 			/*
11743 			 * Log our probe state 3, and log also 5-13 to show
11744 			 * us the recovery sub-state for the send. This
11745 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11746 			 */
11747 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11748 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11749 		}
11750 		/* Place in both 16's the totals of retransmitted */
11751 		counter_u64_add(bbr_state_lost[16], len);
11752 		counter_u64_add(bbr_state_resend[16], len);
11753 		/* Place in 17's the total sent */
11754 		counter_u64_add(bbr_state_resend[17], len);
11755 		counter_u64_add(bbr_state_lost[17], len);
11756 
11757 	} else {
11758 		/* New sends */
11759 		KMOD_TCPSTAT_INC(tcps_sndpack);
11760 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11761 		/* Place in 17's the total sent */
11762 		counter_u64_add(bbr_state_resend[17], len);
11763 		counter_u64_add(bbr_state_lost[17], len);
11764 #ifdef STATS
11765 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11766 		    len);
11767 #endif
11768 	}
11769 }
11770 
11771 static void
11772 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11773 {
11774 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11775 		/*
11776 		 * Limit the cwnd to not be above N x the target plus whats
11777 		 * is outstanding. The target is based on the current b/w
11778 		 * estimate.
11779 		 */
11780 		uint32_t target;
11781 
11782 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11783 		target += ctf_outstanding(tp);
11784 		target *= bbr_target_cwnd_mult_limit;
11785 		if (tp->snd_cwnd > target)
11786 			tp->snd_cwnd = target;
11787 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11788 	}
11789 }
11790 
11791 static int
11792 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11793 {
11794 	/*
11795 	 * "adv" is the amount we could increase the window, taking into
11796 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11797 	 */
11798 	int32_t adv;
11799 	int32_t oldwin;
11800 
11801 	adv = recwin;
11802 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11803 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11804 		if (adv > oldwin)
11805 			adv -= oldwin;
11806 		else {
11807 			/* We can't increase the window */
11808 			adv = 0;
11809 		}
11810 	} else
11811 		oldwin = 0;
11812 
11813 	/*
11814 	 * If the new window size ends up being the same as or less
11815 	 * than the old size when it is scaled, then don't force
11816 	 * a window update.
11817 	 */
11818 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11819 		return (0);
11820 
11821 	if (adv >= (2 * maxseg) &&
11822 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11823 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11824 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11825 		return (1);
11826 	}
11827 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11828 		return (1);
11829 	return (0);
11830 }
11831 
11832 /*
11833  * Return 0 on success and a errno on failure to send.
11834  * Note that a 0 return may not mean we sent anything
11835  * if the TCB was on the hpts. A non-zero return
11836  * does indicate the error we got from ip[6]_output.
11837  */
11838 static int
11839 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11840 {
11841 	struct socket *so;
11842 	int32_t len;
11843 	uint32_t cts;
11844 	uint32_t recwin, sendwin;
11845 	int32_t sb_offset;
11846 	int32_t flags, abandon, error = 0;
11847 	struct tcp_log_buffer *lgb;
11848 	struct mbuf *m;
11849 	struct mbuf *mb;
11850 	uint32_t if_hw_tsomaxsegcount = 0;
11851 	uint32_t if_hw_tsomaxsegsize = 0;
11852 	uint32_t if_hw_tsomax = 0;
11853 	struct ip *ip = NULL;
11854 	struct tcp_bbr *bbr;
11855 	struct tcphdr *th;
11856 	struct udphdr *udp = NULL;
11857 	u_char opt[TCP_MAXOLEN];
11858 	unsigned ipoptlen, optlen, hdrlen;
11859 	unsigned ulen;
11860 	uint32_t bbr_seq;
11861 	uint32_t delay_calc=0;
11862 	uint8_t doing_tlp = 0;
11863 	uint8_t local_options;
11864 #ifdef BBR_INVARIANTS
11865 	uint8_t doing_retran_from = 0;
11866 	uint8_t picked_up_retran = 0;
11867 #endif
11868 	uint8_t wanted_cookie = 0;
11869 	uint8_t more_to_rxt=0;
11870 	int32_t prefetch_so_done = 0;
11871 	int32_t prefetch_rsm = 0;
11872 	uint32_t tot_len = 0;
11873 	uint32_t maxseg, pace_max_segs, p_maxseg;
11874 	int32_t csum_flags = 0;
11875  	int32_t hw_tls;
11876 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11877 	unsigned ipsec_optlen = 0;
11878 
11879 #endif
11880 	volatile int32_t sack_rxmit;
11881 	struct bbr_sendmap *rsm = NULL;
11882 	int32_t tso, mtu;
11883 	struct tcpopt to;
11884 	int32_t slot = 0;
11885 	struct inpcb *inp;
11886 	struct sockbuf *sb;
11887 	bool hpts_calling;
11888 #ifdef INET6
11889 	struct ip6_hdr *ip6 = NULL;
11890 	int32_t isipv6;
11891 #endif
11892 	uint8_t app_limited = BBR_JR_SENT_DATA;
11893 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11894 	/* We take a cache hit here */
11895 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11896 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11897 	inp = bbr->rc_inp;
11898 	hpts_calling = !!(tp->t_flags2 & TF2_HPTS_CALLS);
11899 	tp->t_flags2 &= ~TF2_HPTS_CALLS;
11900 	so = inp->inp_socket;
11901 	sb = &so->so_snd;
11902 	if (tp->t_nic_ktls_xmit)
11903  		hw_tls = 1;
11904  	else
11905  		hw_tls = 0;
11906 	kern_prefetch(sb, &maxseg);
11907 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11908 	if (bbr_minseg(bbr) < maxseg) {
11909 		tcp_bbr_tso_size_check(bbr, cts);
11910 	}
11911 	/* Remove any flags that indicate we are pacing on the inp  */
11912 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11913 	p_maxseg = min(maxseg, pace_max_segs);
11914 	INP_WLOCK_ASSERT(inp);
11915 #ifdef TCP_OFFLOAD
11916 	if (tp->t_flags & TF_TOE)
11917 		return (tcp_offload_output(tp));
11918 #endif
11919 
11920 #ifdef INET6
11921 	if (bbr->r_state) {
11922 		/* Use the cache line loaded if possible */
11923 		isipv6 = bbr->r_is_v6;
11924 	} else {
11925 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11926 	}
11927 #endif
11928 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11929 	    tcp_in_hpts(tp)) {
11930 		/*
11931 		 * We are on the hpts for some timer but not hptsi output.
11932 		 * Possibly remove from the hpts so we can send/recv etc.
11933 		 */
11934 		if ((tp->t_flags & TF_ACKNOW) == 0) {
11935 			/*
11936 			 * No immediate demand right now to send an ack, but
11937 			 * the user may have read, making room for new data
11938 			 * (a window update). If so we may want to cancel
11939 			 * whatever timer is running (KEEP/DEL-ACK?) and
11940 			 * continue to send out a window update. Or we may
11941 			 * have gotten more data into the socket buffer to
11942 			 * send.
11943 			 */
11944 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
11945 				      (long)TCP_MAXWIN << tp->rcv_scale);
11946 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
11947 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
11948 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
11949 			    (tp->snd_max - tp->snd_una))) {
11950 				/*
11951 				 * Nothing new to send and no window update
11952 				 * is needed to send. Lets just return and
11953 				 * let the timer-run off.
11954 				 */
11955 				return (0);
11956 			}
11957 		}
11958 		tcp_hpts_remove(tp);
11959 		bbr_timer_cancel(bbr, __LINE__, cts);
11960 	}
11961 	if (bbr->r_ctl.rc_last_delay_val) {
11962 		/* Calculate a rough delay for early escape to sending  */
11963 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11964 			delay_calc = cts - bbr->rc_pacer_started;
11965 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11966 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11967 		else
11968 			delay_calc = 0;
11969 	}
11970 	/* Mark that we have called bbr_output(). */
11971 	if ((bbr->r_timer_override) ||
11972 	    (tp->t_state < TCPS_ESTABLISHED)) {
11973 		/* Timeouts or early states are exempt */
11974 		if (tcp_in_hpts(tp))
11975 			tcp_hpts_remove(tp);
11976 	} else if (tcp_in_hpts(tp)) {
11977 		if ((bbr->r_ctl.rc_last_delay_val) &&
11978 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11979 		    delay_calc) {
11980 			/*
11981 			 * We were being paced for output and the delay has
11982 			 * already exceeded when we were supposed to be
11983 			 * called, lets go ahead and pull out of the hpts
11984 			 * and call output.
11985 			 */
11986 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
11987 			bbr->r_ctl.rc_last_delay_val = 0;
11988 			tcp_hpts_remove(tp);
11989 		} else if (tp->t_state == TCPS_CLOSED) {
11990 			bbr->r_ctl.rc_last_delay_val = 0;
11991 			tcp_hpts_remove(tp);
11992 		} else {
11993 			/*
11994 			 * On the hpts, you shall not pass! even if ACKNOW
11995 			 * is on, we will when the hpts fires, unless of
11996 			 * course we are overdue.
11997 			 */
11998 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
11999 			return (0);
12000 		}
12001 	}
12002 	bbr->rc_cwnd_limited = 0;
12003 	if (bbr->r_ctl.rc_last_delay_val) {
12004 		/* recalculate the real delay and deal with over/under  */
12005 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12006 			delay_calc = cts - bbr->rc_pacer_started;
12007 		else
12008 			delay_calc = 0;
12009 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12010 			/* Setup the delay which will be added in */
12011 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12012 		else {
12013 			/*
12014 			 * We are early setup to adjust
12015 			 * our slot time.
12016 			 */
12017 			uint64_t merged_val;
12018 
12019 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12020 			bbr->r_agg_early_set = 1;
12021 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
12022 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12023 					/* Nope our previous late cancels out the early */
12024 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12025 					bbr->r_agg_early_set = 0;
12026 					bbr->r_ctl.rc_agg_early = 0;
12027 				} else {
12028 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12029 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
12030 				}
12031 			}
12032 			merged_val = bbr->rc_pacer_started;
12033 			merged_val <<= 32;
12034 			merged_val |= bbr->r_ctl.rc_last_delay_val;
12035 			bbr_log_pacing_delay_calc(bbr, hpts_calling,
12036 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12037 						 bbr->r_agg_early_set, 3);
12038 			bbr->r_ctl.rc_last_delay_val = 0;
12039 			BBR_STAT_INC(bbr_early);
12040 			delay_calc = 0;
12041 		}
12042 	} else {
12043 		/* We were not delayed due to hptsi */
12044 		if (bbr->r_agg_early_set)
12045 			bbr->r_ctl.rc_agg_early = 0;
12046 		bbr->r_agg_early_set = 0;
12047 		delay_calc = 0;
12048 	}
12049 	if (delay_calc) {
12050 		/*
12051 		 * We had a hptsi delay which means we are falling behind on
12052 		 * sending at the expected rate. Calculate an extra amount
12053 		 * of data we can send, if any, to put us back on track.
12054 		 */
12055 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12056 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12057 		else
12058 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12059 	}
12060 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12061 	if ((tp->snd_una == tp->snd_max) &&
12062 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12063 	    (sbavail(sb))) {
12064 		/*
12065 		 * Ok we have been idle with nothing outstanding
12066 		 * we possibly need to start fresh with either a new
12067 		 * suite of states or a fast-ramp up.
12068 		 */
12069 		bbr_restart_after_idle(bbr,
12070 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12071 	}
12072 	/*
12073 	 * Now was there a hptsi delay where we are behind? We only count
12074 	 * being behind if: a) We are not in recovery. b) There was a delay.
12075 	 * <and> c) We had room to send something.
12076 	 *
12077 	 */
12078 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12079 		int retval;
12080 
12081 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12082 		if (retval != 0) {
12083 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12084 			/*
12085 			 * If timers want tcp_drop(), then pass error out,
12086 			 * otherwise suppress it.
12087 			 */
12088 			return (retval < 0 ? retval : 0);
12089 		}
12090 	}
12091 	bbr->rc_tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
12092 	if (hpts_calling &&
12093 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12094 		bbr->r_ctl.rc_last_delay_val = 0;
12095 	}
12096 	bbr->r_timer_override = 0;
12097 	bbr->r_wanted_output = 0;
12098 	/*
12099 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12100 	 * SYN|ACK and those sent by the retransmit timer.
12101 	 */
12102 	if ((tp->t_flags & TF_FASTOPEN) &&
12103 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12104 	     (tp->t_state == TCPS_SYN_SENT)) &&
12105 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12106 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12107 		len = 0;
12108 		goto just_return_nolock;
12109 	}
12110 	/*
12111 	 * Before sending anything check for a state update. For hpts
12112 	 * calling without input this is important. If its input calling
12113 	 * then this was already done.
12114 	 */
12115 	if (bbr->rc_use_google == 0)
12116 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12117 again:
12118 	/*
12119 	 * If we've recently taken a timeout, snd_max will be greater than
12120 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12121 	 * for historic reasons the persist timer still uses it. This means
12122 	 * we have to look at it. All retransmissions that are not persits
12123 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12124 	 * end of this routine we pull snd_nxt always up to snd_max.
12125 	 */
12126 	doing_tlp = 0;
12127 #ifdef BBR_INVARIANTS
12128 	doing_retran_from = picked_up_retran = 0;
12129 #endif
12130 	error = 0;
12131 	tso = 0;
12132 	slot = 0;
12133 	mtu = 0;
12134 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12135 	sb_offset = tp->snd_max - tp->snd_una;
12136 	flags = tcp_outflags[tp->t_state];
12137 	sack_rxmit = 0;
12138 	len = 0;
12139 	rsm = NULL;
12140 	if (flags & TH_RST) {
12141 		SOCK_SENDBUF_LOCK(so);
12142 		goto send;
12143 	}
12144 recheck_resend:
12145 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12146 		/* We need to always have one in reserve */
12147 		rsm = bbr_alloc(bbr);
12148 		if (rsm == NULL) {
12149 			error = ENOMEM;
12150 			/* Lie to get on the hpts */
12151 			tot_len = tp->t_maxseg;
12152 			if (hpts_calling)
12153 				/* Retry in a ms */
12154 				slot = 1001;
12155 			goto just_return_nolock;
12156 		}
12157 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12158 		bbr->r_ctl.rc_free_cnt++;
12159 		rsm = NULL;
12160 	}
12161 	/* What do we send, a resend? */
12162 	if (bbr->r_ctl.rc_resend == NULL) {
12163 		/* Check for rack timeout */
12164 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12165 		if (bbr->r_ctl.rc_resend) {
12166 #ifdef BBR_INVARIANTS
12167 			picked_up_retran = 1;
12168 #endif
12169 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12170 		}
12171 	}
12172 	if (bbr->r_ctl.rc_resend) {
12173 		rsm = bbr->r_ctl.rc_resend;
12174 #ifdef BBR_INVARIANTS
12175 		doing_retran_from = 1;
12176 #endif
12177 		/* Remove any TLP flags its a RACK or T-O */
12178 		rsm->r_flags &= ~BBR_TLP;
12179 		bbr->r_ctl.rc_resend = NULL;
12180 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12181 #ifdef BBR_INVARIANTS
12182 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12183 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12184 			goto recheck_resend;
12185 #else
12186 			/* TSNH */
12187 			rsm = NULL;
12188 			goto recheck_resend;
12189 #endif
12190 		}
12191 		if (rsm->r_flags & BBR_HAS_SYN) {
12192 			/* Only retransmit a SYN by itself */
12193 			len = 0;
12194 			if ((flags & TH_SYN) == 0) {
12195 				/* Huh something is wrong */
12196 				rsm->r_start++;
12197 				if (rsm->r_start == rsm->r_end) {
12198 					/* Clean it up, somehow we missed the ack? */
12199 					bbr_log_syn(tp, NULL);
12200 				} else {
12201 					/* TFO with data? */
12202 					rsm->r_flags &= ~BBR_HAS_SYN;
12203 					len = rsm->r_end - rsm->r_start;
12204 				}
12205 			} else {
12206 				/* Retransmitting SYN */
12207 				rsm = NULL;
12208 				SOCK_SENDBUF_LOCK(so);
12209 				goto send;
12210 			}
12211 		} else
12212 			len = rsm->r_end - rsm->r_start;
12213 		if ((bbr->rc_resends_use_tso == 0) &&
12214 		    (len > maxseg)) {
12215 			len = maxseg;
12216 			more_to_rxt = 1;
12217 		}
12218 		sb_offset = rsm->r_start - tp->snd_una;
12219 		if (len > 0) {
12220 			sack_rxmit = 1;
12221 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12222 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12223 			    min(len, maxseg));
12224 		} else {
12225 			/* I dont think this can happen */
12226 			rsm = NULL;
12227 			goto recheck_resend;
12228 		}
12229 		BBR_STAT_INC(bbr_resends_set);
12230 	} else if (bbr->r_ctl.rc_tlp_send) {
12231 		/*
12232 		 * Tail loss probe
12233 		 */
12234 		doing_tlp = 1;
12235 		rsm = bbr->r_ctl.rc_tlp_send;
12236 		bbr->r_ctl.rc_tlp_send = NULL;
12237 		sack_rxmit = 1;
12238 		len = rsm->r_end - rsm->r_start;
12239 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12240 			len = maxseg;
12241 
12242 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12243 #ifdef BBR_INVARIANTS
12244 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12245 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12246 #else
12247 			/* TSNH */
12248 			rsm = NULL;
12249 			goto recheck_resend;
12250 #endif
12251 		}
12252 		sb_offset = rsm->r_start - tp->snd_una;
12253 		BBR_STAT_INC(bbr_tlp_set);
12254 	}
12255 	/*
12256 	 * Enforce a connection sendmap count limit if set
12257 	 * as long as we are not retransmiting.
12258 	 */
12259 	if ((rsm == NULL) &&
12260 	    (V_tcp_map_entries_limit > 0) &&
12261 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12262 		BBR_STAT_INC(bbr_alloc_limited);
12263 		if (!bbr->alloc_limit_reported) {
12264 			bbr->alloc_limit_reported = 1;
12265 			BBR_STAT_INC(bbr_alloc_limited_conns);
12266 		}
12267 		goto just_return_nolock;
12268 	}
12269 #ifdef BBR_INVARIANTS
12270 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12271 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12272 		    tp, bbr, rsm, sb_offset, len);
12273 	}
12274 #endif
12275 	/*
12276 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12277 	 * state flags.
12278 	 */
12279 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12280 		flags |= TH_FIN;
12281 	if (tp->t_flags & TF_NEEDSYN)
12282 		flags |= TH_SYN;
12283 
12284 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12285 		/* we are retransmitting the fin */
12286 		len--;
12287 		if (len) {
12288 			/*
12289 			 * When retransmitting data do *not* include the
12290 			 * FIN. This could happen from a TLP probe if we
12291 			 * allowed data with a FIN.
12292 			 */
12293 			flags &= ~TH_FIN;
12294 		}
12295 	} else if (rsm) {
12296 		if (flags & TH_FIN)
12297 			flags &= ~TH_FIN;
12298 	}
12299 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12300 		void *end_rsm;
12301 
12302 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12303 		if (end_rsm)
12304 			kern_prefetch(end_rsm, &prefetch_rsm);
12305 		prefetch_rsm = 1;
12306 	}
12307 	SOCK_SENDBUF_LOCK(so);
12308 	/*
12309 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12310 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12311 	 * negative length.  This can also occur when TCP opens up its
12312 	 * congestion window while receiving additional duplicate acks after
12313 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12314 	 * the fast-retransmit.
12315 	 *
12316 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12317 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12318 	 * up 0.
12319 	 *
12320 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12321 	 * in which case len is already set.
12322 	 */
12323 	if (sack_rxmit == 0) {
12324 		uint32_t avail;
12325 
12326 		avail = sbavail(sb);
12327 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12328 			sb_offset = tp->snd_max - tp->snd_una;
12329 		else
12330 			sb_offset = 0;
12331 		if (bbr->rc_tlp_new_data) {
12332 			/* TLP is forcing out new data */
12333 			uint32_t tlplen;
12334 
12335 			doing_tlp = 1;
12336 			tlplen = maxseg;
12337 
12338 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12339 				tlplen = (uint32_t)(avail - sb_offset);
12340 			}
12341 			if (tlplen > tp->snd_wnd) {
12342 				len = tp->snd_wnd;
12343 			} else {
12344 				len = tlplen;
12345 			}
12346 			bbr->rc_tlp_new_data = 0;
12347 		} else {
12348 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12349 			if ((len < p_maxseg) &&
12350 			    (bbr->rc_in_persist == 0) &&
12351 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12352 			    ((avail - sb_offset) >= p_maxseg)) {
12353 				/*
12354 				 * We are not completing whats in the socket
12355 				 * buffer (i.e. there is at least a segment
12356 				 * waiting to send) and we have 2 or more
12357 				 * segments outstanding. There is no sense
12358 				 * of sending a little piece. Lets defer and
12359 				 * and wait until we can send a whole
12360 				 * segment.
12361 				 */
12362 				len = 0;
12363 			}
12364 			if (bbr->rc_in_persist) {
12365 				/*
12366 				 * We are in persists, figure out if
12367 				 * a retransmit is available (maybe the previous
12368 				 * persists we sent) or if we have to send new
12369 				 * data.
12370 				 */
12371 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12372 				if (rsm) {
12373 					len = rsm->r_end - rsm->r_start;
12374 					if (rsm->r_flags & BBR_HAS_FIN)
12375 						len--;
12376 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12377 						len = maxseg;
12378 					if (len > 1)
12379 						BBR_STAT_INC(bbr_persist_reneg);
12380 					/*
12381 					 * XXXrrs we could force the len to
12382 					 * 1 byte here to cause the chunk to
12383 					 * split apart.. but that would then
12384 					 * mean we always retransmit it as
12385 					 * one byte even after the window
12386 					 * opens.
12387 					 */
12388 					sack_rxmit = 1;
12389 					sb_offset = rsm->r_start - tp->snd_una;
12390 				} else {
12391 					/*
12392 					 * First time through in persists or peer
12393 					 * acked our one byte. Though we do have
12394 					 * to have something in the sb.
12395 					 */
12396 					len = 1;
12397 					sb_offset = 0;
12398 					if (avail == 0)
12399 					    len = 0;
12400 				}
12401 			}
12402 		}
12403 	}
12404 	if (prefetch_so_done == 0) {
12405 		kern_prefetch(so, &prefetch_so_done);
12406 		prefetch_so_done = 1;
12407 	}
12408 	/*
12409 	 * Lop off SYN bit if it has already been sent.  However, if this is
12410 	 * SYN-SENT state and if segment contains data and if we don't know
12411 	 * that foreign host supports TAO, suppress sending segment.
12412 	 */
12413 	if ((flags & TH_SYN) && (rsm == NULL) &&
12414 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12415 		if (tp->t_state != TCPS_SYN_RECEIVED)
12416 			flags &= ~TH_SYN;
12417 		/*
12418 		 * When sending additional segments following a TFO SYN|ACK,
12419 		 * do not include the SYN bit.
12420 		 */
12421 		if ((tp->t_flags & TF_FASTOPEN) &&
12422 		    (tp->t_state == TCPS_SYN_RECEIVED))
12423 			flags &= ~TH_SYN;
12424 		sb_offset--, len++;
12425 		if (sbavail(sb) == 0)
12426 			len = 0;
12427 	} else if ((flags & TH_SYN) && rsm) {
12428 		/*
12429 		 * Subtract one from the len for the SYN being
12430 		 * retransmitted.
12431 		 */
12432 		len--;
12433 	}
12434 	/*
12435 	 * Be careful not to send data and/or FIN on SYN segments. This
12436 	 * measure is needed to prevent interoperability problems with not
12437 	 * fully conformant TCP implementations.
12438 	 */
12439 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12440 		len = 0;
12441 		flags &= ~TH_FIN;
12442 	}
12443 	/*
12444 	 * On TFO sockets, ensure no data is sent in the following cases:
12445 	 *
12446 	 *  - When retransmitting SYN|ACK on a passively-created socket
12447 	 *  - When retransmitting SYN on an actively created socket
12448 	 *  - When sending a zero-length cookie (cookie request) on an
12449 	 *    actively created socket
12450 	 *  - When the socket is in the CLOSED state (RST is being sent)
12451 	 */
12452 	if ((tp->t_flags & TF_FASTOPEN) &&
12453 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12454 	     ((tp->t_state == TCPS_SYN_SENT) &&
12455 	      (tp->t_tfo_client_cookie_len == 0)) ||
12456 	     (flags & TH_RST))) {
12457 		len = 0;
12458 		sack_rxmit = 0;
12459 		rsm = NULL;
12460 	}
12461 	/* Without fast-open there should never be data sent on a SYN */
12462 	if ((flags & TH_SYN) && !(tp->t_flags & TF_FASTOPEN))
12463 		len = 0;
12464 	if (len <= 0) {
12465 		/*
12466 		 * If FIN has been sent but not acked, but we haven't been
12467 		 * called to retransmit, len will be < 0.  Otherwise, window
12468 		 * shrank after we sent into it.  If window shrank to 0,
12469 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12470 		 * window, and set the persist timer if it isn't already
12471 		 * going.  If the window didn't close completely, just wait
12472 		 * for an ACK.
12473 		 *
12474 		 * We also do a general check here to ensure that we will
12475 		 * set the persist timer when we have data to send, but a
12476 		 * 0-byte window. This makes sure the persist timer is set
12477 		 * even if the packet hits one of the "goto send" lines
12478 		 * below.
12479 		 */
12480 		len = 0;
12481 		if ((tp->snd_wnd == 0) &&
12482 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12483 		    (tp->snd_una == tp->snd_max) &&
12484 		    (sb_offset < (int)sbavail(sb))) {
12485 			/*
12486 			 * Not enough room in the rwnd to send
12487 			 * a paced segment out.
12488 			 */
12489 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12490 		}
12491 	} else if ((rsm == NULL) &&
12492 		   (doing_tlp == 0) &&
12493 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12494 		/*
12495 		 * We are not sending a full segment for
12496 		 * some reason. Should we not send anything (think
12497 		 * sws or persists)?
12498 		 */
12499 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12500 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12501 		    (len < (int)(sbavail(sb) - sb_offset))) {
12502 			/*
12503 			 * Here the rwnd is less than
12504 			 * the pacing size, this is not a retransmit,
12505 			 * we are established and
12506 			 * the send is not the last in the socket buffer
12507 			 * lets not send, and possibly enter persists.
12508 			 */
12509 			len = 0;
12510 			if (tp->snd_max == tp->snd_una)
12511 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12512 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12513 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12514 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12515 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12516 			   (len < bbr_minseg(bbr))) {
12517 			/*
12518 			 * Here we are not retransmitting, and
12519 			 * the cwnd is not so small that we could
12520 			 * not send at least a min size (rxt timer
12521 			 * not having gone off), We have 2 segments or
12522 			 * more already in flight, its not the tail end
12523 			 * of the socket buffer  and the cwnd is blocking
12524 			 * us from sending out minimum pacing segment size.
12525 			 * Lets not send anything.
12526 			 */
12527 			bbr->rc_cwnd_limited = 1;
12528 			len = 0;
12529 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12530 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12531 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12532 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12533 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12534 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12535 			/*
12536 			 * Here we have a send window but we have
12537 			 * filled it up and we can't send another pacing segment.
12538 			 * We also have in flight more than 2 segments
12539 			 * and we are not completing the sb i.e. we allow
12540 			 * the last bytes of the sb to go out even if
12541 			 * its not a full pacing segment.
12542 			 */
12543 			len = 0;
12544 		}
12545 	}
12546 	/* len will be >= 0 after this point. */
12547 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12548 	tcp_sndbuf_autoscale(tp, so, sendwin);
12549 	/*
12550 	 *
12551 	 */
12552 	if (bbr->rc_in_persist &&
12553 	    len &&
12554 	    (rsm == NULL) &&
12555 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12556 		/*
12557 		 * We are in persist, not doing a retransmit and don't have enough space
12558 		 * yet to send a full TSO. So is it at the end of the sb
12559 		 * if so we need to send else nuke to 0 and don't send.
12560 		 */
12561 		int sbleft;
12562 		if (sbavail(sb) > sb_offset)
12563 			sbleft = sbavail(sb) - sb_offset;
12564 		else
12565 			sbleft = 0;
12566 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12567 			/* not at end of sb lets not send */
12568 			len = 0;
12569 		}
12570 	}
12571 	/*
12572 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12573 	 * hardware).
12574 	 *
12575 	 * TSO may only be used if we are in a pure bulk sending state.  The
12576 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12577 	 * options prevent using TSO.  With TSO the TCP header is the same
12578 	 * (except for the sequence number) for all generated packets.  This
12579 	 * makes it impossible to transmit any options which vary per
12580 	 * generated segment or packet.
12581 	 *
12582 	 * IPv4 handling has a clear separation of ip options and ip header
12583 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12584 	 * does the right thing below to provide length of just ip options
12585 	 * and thus checking for ipoptlen is enough to decide if ip options
12586 	 * are present.
12587 	 */
12588 #ifdef INET6
12589 	if (isipv6)
12590 		ipoptlen = ip6_optlen(inp);
12591 	else
12592 #endif
12593 	if (inp->inp_options)
12594 		ipoptlen = inp->inp_options->m_len -
12595 		    offsetof(struct ipoption, ipopt_list);
12596 	else
12597 		ipoptlen = 0;
12598 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12599 	/*
12600 	 * Pre-calculate here as we save another lookup into the darknesses
12601 	 * of IPsec that way and can actually decide if TSO is ok.
12602 	 */
12603 #ifdef INET6
12604 	if (isipv6 && IPSEC_ENABLED(ipv6))
12605 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12606 #ifdef INET
12607 	else
12608 #endif
12609 #endif				/* INET6 */
12610 #ifdef INET
12611 	if (IPSEC_ENABLED(ipv4))
12612 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12613 #endif				/* INET */
12614 #endif				/* IPSEC */
12615 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12616 	ipoptlen += ipsec_optlen;
12617 #endif
12618 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12619 	    (len > maxseg) &&
12620 	    (tp->t_port == 0) &&
12621 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12622 	    ipoptlen == 0)
12623 		tso = 1;
12624 
12625 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12626 	    (long)TCP_MAXWIN << tp->rcv_scale);
12627 	/*
12628 	 * Sender silly window avoidance.   We transmit under the following
12629 	 * conditions when len is non-zero:
12630 	 *
12631 	 * - We have a full segment (or more with TSO) - This is the last
12632 	 * buffer in a write()/send() and we are either idle or running
12633 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12634 	 * then 1/2 the maximum send window's worth of data (receiver may be
12635 	 * limited the window size) - we need to retransmit
12636 	 */
12637 	if (rsm)
12638 		goto send;
12639 	if (len) {
12640 		if (sack_rxmit)
12641 			goto send;
12642 		if (len >= p_maxseg)
12643 			goto send;
12644 		/*
12645 		 * NOTE! on localhost connections an 'ack' from the remote
12646 		 * end may occur synchronously with the output and cause us
12647 		 * to flush a buffer queued with moretocome.  XXX
12648 		 *
12649 		 */
12650 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12651 		    ((tp->t_flags & TF_NODELAY) ||
12652 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12653 		    (tp->t_flags & TF_NOPUSH) == 0) {
12654 			goto send;
12655 		}
12656 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12657 			goto send;
12658 		}
12659 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12660 			goto send;
12661 		}
12662 	}
12663 	/*
12664 	 * Sending of standalone window updates.
12665 	 *
12666 	 * Window updates are important when we close our window due to a
12667 	 * full socket buffer and are opening it again after the application
12668 	 * reads data from it.  Once the window has opened again and the
12669 	 * remote end starts to send again the ACK clock takes over and
12670 	 * provides the most current window information.
12671 	 *
12672 	 * We must avoid the silly window syndrome whereas every read from
12673 	 * the receive buffer, no matter how small, causes a window update
12674 	 * to be sent.  We also should avoid sending a flurry of window
12675 	 * updates when the socket buffer had queued a lot of data and the
12676 	 * application is doing small reads.
12677 	 *
12678 	 * Prevent a flurry of pointless window updates by only sending an
12679 	 * update when we can increase the advertized window by more than
12680 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12681 	 * full or is very small be more aggressive and send an update
12682 	 * whenever we can increase by two mss sized segments. In all other
12683 	 * situations the ACK's to new incoming data will carry further
12684 	 * window increases.
12685 	 *
12686 	 * Don't send an independent window update if a delayed ACK is
12687 	 * pending (it will get piggy-backed on it) or the remote side
12688 	 * already has done a half-close and won't send more data.  Skip
12689 	 * this if the connection is in T/TCP half-open state.
12690 	 */
12691 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12692 	    !(tp->t_flags & TF_DELACK) &&
12693 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12694 		/* Check to see if we should do a window update */
12695 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12696 			goto send;
12697 	}
12698 	/*
12699 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12700 	 * is also a catch-all for the retransmit timer timeout case.
12701 	 */
12702 	if (tp->t_flags & TF_ACKNOW) {
12703 		goto send;
12704 	}
12705 	if (flags & TH_RST) {
12706 		/* Always send a RST if one is due */
12707 		goto send;
12708 	}
12709 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12710 		goto send;
12711 	}
12712 	/*
12713 	 * If our state indicates that FIN should be sent and we have not
12714 	 * yet done so, then we need to send.
12715 	 */
12716 	if (flags & TH_FIN &&
12717 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12718 		goto send;
12719 	}
12720 	/*
12721 	 * No reason to send a segment, just return.
12722 	 */
12723 just_return:
12724 	SOCK_SENDBUF_UNLOCK(so);
12725 just_return_nolock:
12726 	if (tot_len)
12727 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12728 	if (bbr->rc_no_pacing)
12729 		slot = 0;
12730 	if (tot_len == 0) {
12731 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12732 		    tp->snd_wnd) {
12733 			BBR_STAT_INC(bbr_rwnd_limited);
12734 			app_limited = BBR_JR_RWND_LIMITED;
12735 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12736 			if ((bbr->rc_in_persist == 0) &&
12737 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12738 			    (tp->snd_max == tp->snd_una) &&
12739 			    sbavail(&so->so_snd)) {
12740 				/* No send window.. we must enter persist */
12741 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12742 			}
12743 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12744 			BBR_STAT_INC(bbr_app_limited);
12745 			app_limited = BBR_JR_APP_LIMITED;
12746 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12747 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12748 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12749 			BBR_STAT_INC(bbr_cwnd_limited);
12750  			app_limited = BBR_JR_CWND_LIMITED;
12751 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12752 									bbr->r_ctl.rc_lost_bytes)));
12753 			bbr->rc_cwnd_limited = 1;
12754 		} else {
12755 			BBR_STAT_INC(bbr_app_limited);
12756 			app_limited = BBR_JR_APP_LIMITED;
12757 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12758 		}
12759 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12760 		bbr->r_agg_early_set = 0;
12761 		bbr->r_ctl.rc_agg_early = 0;
12762 		bbr->r_ctl.rc_last_delay_val = 0;
12763 	} else if (bbr->rc_use_google == 0)
12764 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12765 	/* Are we app limited? */
12766 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12767 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12768 		/**
12769 		 * We are application limited.
12770 		 */
12771 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12772 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12773 	}
12774 	if (tot_len == 0)
12775 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12776 	/* Dont update the time if we did not send */
12777 	bbr->r_ctl.rc_last_delay_val = 0;
12778 	bbr->rc_output_starts_timer = 1;
12779 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12780 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12781 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12782 		/* Make sure snd_nxt is drug up */
12783 		tp->snd_nxt = tp->snd_max;
12784 	}
12785 	return (error);
12786 
12787 send:
12788 	if (doing_tlp == 0) {
12789 		/*
12790 		 * Data not a TLP, and its not the rxt firing. If it is the
12791 		 * rxt firing, we want to leave the tlp_in_progress flag on
12792 		 * so we don't send another TLP. It has to be a rack timer
12793 		 * or normal send (response to acked data) to clear the tlp
12794 		 * in progress flag.
12795 		 */
12796 		bbr->rc_tlp_in_progress = 0;
12797 		bbr->rc_tlp_rtx_out = 0;
12798 	} else {
12799 		/*
12800 		 * Its a TLP.
12801 		 */
12802 		bbr->rc_tlp_in_progress = 1;
12803 	}
12804 	bbr_timer_cancel(bbr, __LINE__, cts);
12805 	if (rsm == NULL) {
12806 		if (sbused(sb) > 0) {
12807 			/*
12808 			 * This is sub-optimal. We only send a stand alone
12809 			 * FIN on its own segment.
12810 			 */
12811 			if (flags & TH_FIN) {
12812 				flags &= ~TH_FIN;
12813 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12814 					/* Lets not send this */
12815 					slot = 0;
12816 					goto just_return;
12817 				}
12818 			}
12819 		}
12820 	} else {
12821 		/*
12822 		 * We do *not* send a FIN on a retransmit if it has data.
12823 		 * The if clause here where len > 1 should never come true.
12824 		 */
12825 		if ((len > 0) &&
12826 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12827 		    (flags & TH_FIN))) {
12828 			flags &= ~TH_FIN;
12829 			len--;
12830 		}
12831 	}
12832 	SOCK_SENDBUF_LOCK_ASSERT(so);
12833 	if (len > 0) {
12834 		if ((tp->snd_una == tp->snd_max) &&
12835 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12836 			/*
12837 			 * This qualifies as a RTT_PROBE session since we
12838 			 * drop the data outstanding to nothing and waited
12839 			 * more than bbr_rtt_probe_time.
12840 			 */
12841 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12842 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12843 		}
12844 		if (len >= maxseg)
12845 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12846 		else
12847 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12848 	}
12849 	/*
12850 	 * Before ESTABLISHED, force sending of initial options unless TCP
12851 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12852 	 * plus TCP options always fit in a single mbuf, leaving room for a
12853 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12854 	 * + optlen <= MCLBYTES
12855 	 */
12856 	optlen = 0;
12857 #ifdef INET6
12858 	if (isipv6)
12859 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12860 	else
12861 #endif
12862 		hdrlen = sizeof(struct tcpiphdr);
12863 
12864 	/*
12865 	 * Compute options for segment. We only have to care about SYN and
12866 	 * established connection segments.  Options for SYN-ACK segments
12867 	 * are handled in TCP syncache.
12868 	 */
12869 	to.to_flags = 0;
12870 	local_options = 0;
12871 	if ((tp->t_flags & TF_NOOPT) == 0) {
12872 		/* Maximum segment size. */
12873 		if (flags & TH_SYN) {
12874 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12875 			if (tp->t_port)
12876 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12877 			to.to_flags |= TOF_MSS;
12878 			/*
12879 			 * On SYN or SYN|ACK transmits on TFO connections,
12880 			 * only include the TFO option if it is not a
12881 			 * retransmit, as the presence of the TFO option may
12882 			 * have caused the original SYN or SYN|ACK to have
12883 			 * been dropped by a middlebox.
12884 			 */
12885 			if ((tp->t_flags & TF_FASTOPEN) &&
12886 			    (tp->t_rxtshift == 0)) {
12887 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12888 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12889 					to.to_tfo_cookie =
12890 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12891 					to.to_flags |= TOF_FASTOPEN;
12892 					wanted_cookie = 1;
12893 				} else if (tp->t_state == TCPS_SYN_SENT) {
12894 					to.to_tfo_len =
12895 					    tp->t_tfo_client_cookie_len;
12896 					to.to_tfo_cookie =
12897 					    tp->t_tfo_cookie.client;
12898 					to.to_flags |= TOF_FASTOPEN;
12899 					wanted_cookie = 1;
12900 				}
12901 			}
12902 		}
12903 		/* Window scaling. */
12904 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12905 			to.to_wscale = tp->request_r_scale;
12906 			to.to_flags |= TOF_SCALE;
12907 		}
12908 		/* Timestamps. */
12909 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12910 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12911 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12912 			to.to_tsecr = tp->ts_recent;
12913 			to.to_flags |= TOF_TS;
12914 			local_options += TCPOLEN_TIMESTAMP + 2;
12915 		}
12916 		/* Set receive buffer autosizing timestamp. */
12917 		if (tp->rfbuf_ts == 0 &&
12918 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12919 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12920 		/* Selective ACK's. */
12921 		if (flags & TH_SYN)
12922 			to.to_flags |= TOF_SACKPERM;
12923 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12924 		    tp->rcv_numsacks > 0) {
12925 			to.to_flags |= TOF_SACK;
12926 			to.to_nsacks = tp->rcv_numsacks;
12927 			to.to_sacks = (u_char *)tp->sackblks;
12928 		}
12929 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
12930 		/* TCP-MD5 (RFC2385). */
12931 		if (tp->t_flags & TF_SIGNATURE)
12932 			to.to_flags |= TOF_SIGNATURE;
12933 #endif				/* TCP_SIGNATURE */
12934 
12935 		/* Processing the options. */
12936 		hdrlen += (optlen = tcp_addoptions(&to, opt));
12937 		/*
12938 		 * If we wanted a TFO option to be added, but it was unable
12939 		 * to fit, ensure no data is sent.
12940 		 */
12941 		if ((tp->t_flags & TF_FASTOPEN) && wanted_cookie &&
12942 		    !(to.to_flags & TOF_FASTOPEN))
12943 			len = 0;
12944 	}
12945 	if (tp->t_port) {
12946 		if (V_tcp_udp_tunneling_port == 0) {
12947 			/* The port was removed?? */
12948 			SOCK_SENDBUF_UNLOCK(so);
12949 			return (EHOSTUNREACH);
12950 		}
12951 		hdrlen += sizeof(struct udphdr);
12952 	}
12953 #ifdef INET6
12954 	if (isipv6)
12955 		ipoptlen = ip6_optlen(inp);
12956 	else
12957 #endif
12958 	if (inp->inp_options)
12959 		ipoptlen = inp->inp_options->m_len -
12960 		    offsetof(struct ipoption, ipopt_list);
12961 	else
12962 		ipoptlen = 0;
12963 	ipoptlen = 0;
12964 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12965 	ipoptlen += ipsec_optlen;
12966 #endif
12967 	if (bbr->rc_last_options != local_options) {
12968 		/*
12969 		 * Cache the options length this generally does not change
12970 		 * on a connection. We use this to calculate TSO.
12971 		 */
12972 		bbr->rc_last_options = local_options;
12973 	}
12974 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
12975 	p_maxseg = min(maxseg, pace_max_segs);
12976 	/*
12977 	 * Adjust data length if insertion of options will bump the packet
12978 	 * length beyond the t_maxseg length. Clear the FIN bit because we
12979 	 * cut off the tail of the segment.
12980 	 */
12981 	if (len > maxseg) {
12982 		if (len != 0 && (flags & TH_FIN)) {
12983 			flags &= ~TH_FIN;
12984 		}
12985 		if (tso) {
12986 			uint32_t moff;
12987 			int32_t max_len;
12988 
12989 			/* extract TSO information */
12990 			if_hw_tsomax = tp->t_tsomax;
12991 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
12992 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
12993 			KASSERT(ipoptlen == 0,
12994 			    ("%s: TSO can't do IP options", __func__));
12995 
12996 			/*
12997 			 * Check if we should limit by maximum payload
12998 			 * length:
12999 			 */
13000 			if (if_hw_tsomax != 0) {
13001 				/* compute maximum TSO length */
13002 				max_len = (if_hw_tsomax - hdrlen -
13003 				    max_linkhdr);
13004 				if (max_len <= 0) {
13005 					len = 0;
13006 				} else if (len > max_len) {
13007 					len = max_len;
13008 				}
13009 			}
13010 			/*
13011 			 * Prevent the last segment from being fractional
13012 			 * unless the send sockbuf can be emptied:
13013 			 */
13014 			if ((sb_offset + len) < sbavail(sb)) {
13015 				moff = len % (uint32_t)maxseg;
13016 				if (moff != 0) {
13017 					len -= moff;
13018 				}
13019 			}
13020 			/*
13021 			 * In case there are too many small fragments don't
13022 			 * use TSO:
13023 			 */
13024 			if (len <= maxseg) {
13025 				len = maxseg;
13026 				tso = 0;
13027 			}
13028 		} else {
13029 			/* Not doing TSO */
13030 			if (optlen + ipoptlen >= tp->t_maxseg) {
13031 				/*
13032 				 * Since we don't have enough space to put
13033 				 * the IP header chain and the TCP header in
13034 				 * one packet as required by RFC 7112, don't
13035 				 * send it. Also ensure that at least one
13036 				 * byte of the payload can be put into the
13037 				 * TCP segment.
13038 				 */
13039 				SOCK_SENDBUF_UNLOCK(so);
13040 				error = EMSGSIZE;
13041 				sack_rxmit = 0;
13042 				goto out;
13043 			}
13044 			len = maxseg;
13045 		}
13046 	} else {
13047 		/* Not doing TSO */
13048 		if_hw_tsomaxsegcount = 0;
13049 		tso = 0;
13050 	}
13051 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13052 	    ("%s: len > IP_MAXPACKET", __func__));
13053 #ifdef DIAGNOSTIC
13054 #ifdef INET6
13055 	if (max_linkhdr + hdrlen > MCLBYTES)
13056 #else
13057 	if (max_linkhdr + hdrlen > MHLEN)
13058 #endif
13059 		panic("tcphdr too big");
13060 #endif
13061 	/*
13062 	 * This KASSERT is here to catch edge cases at a well defined place.
13063 	 * Before, those had triggered (random) panic conditions further
13064 	 * down.
13065 	 */
13066 #ifdef BBR_INVARIANTS
13067 	if (sack_rxmit) {
13068 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13069 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13070 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13071 		}
13072 	}
13073 #endif
13074 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13075 	if ((len == 0) &&
13076 	    (flags & TH_FIN) &&
13077 	    (sbused(sb))) {
13078 		/*
13079 		 * We have outstanding data, don't send a fin by itself!.
13080 		 */
13081 		slot = 0;
13082 		goto just_return;
13083 	}
13084 	/*
13085 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13086 	 * and initialize the header from the template for sends on this
13087 	 * connection.
13088 	 */
13089 	if (len) {
13090 		uint32_t moff;
13091 
13092 		/*
13093 		 * We place a limit on sending with hptsi.
13094 		 */
13095 		if ((rsm == NULL) && len > pace_max_segs)
13096 			len = pace_max_segs;
13097 		if (len <= maxseg)
13098 			tso = 0;
13099 #ifdef INET6
13100 		if (MHLEN < hdrlen + max_linkhdr)
13101 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13102 		else
13103 #endif
13104 			m = m_gethdr(M_NOWAIT, MT_DATA);
13105 
13106 		if (m == NULL) {
13107 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13108 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13109 			SOCK_SENDBUF_UNLOCK(so);
13110 			error = ENOBUFS;
13111 			sack_rxmit = 0;
13112 			goto out;
13113 		}
13114 		m->m_data += max_linkhdr;
13115 		m->m_len = hdrlen;
13116 		/*
13117 		 * Start the m_copy functions from the closest mbuf to the
13118 		 * sb_offset in the socket buffer chain.
13119 		 */
13120 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13121 #ifdef BBR_INVARIANTS
13122 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13123 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13124 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13125 				    doing_retran_from,
13126 				    picked_up_retran,
13127 				    doing_tlp);
13128 
13129 #endif
13130 			/*
13131 			 * In this messed up situation we have two choices,
13132 			 * a) pretend the send worked, and just start timers
13133 			 * and what not (not good since that may lead us
13134 			 * back here a lot). <or> b) Send the lowest segment
13135 			 * in the map. <or> c) Drop the connection. Lets do
13136 			 * <b> which if it continues to happen will lead to
13137 			 * <c> via timeouts.
13138 			 */
13139 			BBR_STAT_INC(bbr_offset_recovery);
13140 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13141 			sb_offset = 0;
13142 			if (rsm == NULL) {
13143 				sack_rxmit = 0;
13144 				len = sbavail(sb);
13145 			} else {
13146 				sack_rxmit = 1;
13147 				if (rsm->r_start != tp->snd_una) {
13148 					/*
13149 					 * Things are really messed up, <c>
13150 					 * is the only thing to do.
13151 					 */
13152 					BBR_STAT_INC(bbr_offset_drop);
13153 					SOCK_SENDBUF_UNLOCK(so);
13154 					(void)m_free(m);
13155 					return (-EFAULT); /* tcp_drop() */
13156 				}
13157 				len = rsm->r_end - rsm->r_start;
13158 			}
13159 			if (len > sbavail(sb))
13160 				len = sbavail(sb);
13161 			if (len > maxseg)
13162 				len = maxseg;
13163 		}
13164 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13165 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13166 			m_copydata(mb, moff, (int)len,
13167 			    mtod(m, caddr_t)+hdrlen);
13168 			if (rsm == NULL)
13169 				sbsndptr_adv(sb, mb, len);
13170 			m->m_len += len;
13171 		} else {
13172 			struct sockbuf *msb;
13173 
13174 			if (rsm)
13175 				msb = NULL;
13176 			else
13177 				msb = sb;
13178 #ifdef BBR_INVARIANTS
13179 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13180 				if (rsm) {
13181 					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 ",
13182 					    tp, bbr, len, moff,
13183 					    sbavail(sb), rsm,
13184 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13185 					    doing_retran_from,
13186 					    picked_up_retran,
13187 					    doing_tlp, sack_rxmit);
13188 				} else {
13189 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13190 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13191 				}
13192 			}
13193 #endif
13194 			m->m_next = tcp_m_copym(
13195 				mb, moff, &len,
13196 				if_hw_tsomaxsegcount,
13197 				if_hw_tsomaxsegsize, msb,
13198 				((rsm == NULL) ? hw_tls : 0)
13199 #ifdef NETFLIX_COPY_ARGS
13200 				, NULL, NULL
13201 #endif
13202 				);
13203 			if (len <= maxseg) {
13204 				/*
13205 				 * Must have ran out of mbufs for the copy
13206 				 * shorten it to no longer need tso. Lets
13207 				 * not put on sendalot since we are low on
13208 				 * mbufs.
13209 				 */
13210 				tso = 0;
13211 			}
13212 			if (m->m_next == NULL) {
13213 				SOCK_SENDBUF_UNLOCK(so);
13214 				(void)m_free(m);
13215 				error = ENOBUFS;
13216 				sack_rxmit = 0;
13217 				goto out;
13218 			}
13219 		}
13220 #ifdef BBR_INVARIANTS
13221 		if (tso && len < maxseg) {
13222 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13223 			    tp, len, maxseg);
13224 		}
13225 		if (tso && if_hw_tsomaxsegcount) {
13226 			int32_t seg_cnt = 0;
13227 			struct mbuf *foo;
13228 
13229 			foo = m;
13230 			while (foo) {
13231 				seg_cnt++;
13232 				foo = foo->m_next;
13233 			}
13234 			if (seg_cnt > if_hw_tsomaxsegcount) {
13235 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13236 			}
13237 		}
13238 #endif
13239 		/*
13240 		 * If we're sending everything we've got, set PUSH. (This
13241 		 * will keep happy those implementations which only give
13242 		 * data to the user when a buffer fills or a PUSH comes in.)
13243 		 */
13244 		if (sb_offset + len == sbused(sb) &&
13245 		    sbused(sb) &&
13246 		    !(flags & TH_SYN)) {
13247 			flags |= TH_PUSH;
13248 		}
13249 		SOCK_SENDBUF_UNLOCK(so);
13250 	} else {
13251 		SOCK_SENDBUF_UNLOCK(so);
13252 		if (tp->t_flags & TF_ACKNOW)
13253 			KMOD_TCPSTAT_INC(tcps_sndacks);
13254 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13255 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13256 		else
13257 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13258 
13259 		m = m_gethdr(M_NOWAIT, MT_DATA);
13260 		if (m == NULL) {
13261 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13262 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13263 			error = ENOBUFS;
13264 			/* Fudge the send time since we could not send */
13265 			sack_rxmit = 0;
13266 			goto out;
13267 		}
13268 #ifdef INET6
13269 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13270 		    MHLEN >= hdrlen) {
13271 			M_ALIGN(m, hdrlen);
13272 		} else
13273 #endif
13274 			m->m_data += max_linkhdr;
13275 		m->m_len = hdrlen;
13276 	}
13277 	SOCK_SENDBUF_UNLOCK_ASSERT(so);
13278 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13279 #ifdef MAC
13280 	mac_inpcb_create_mbuf(inp, m);
13281 #endif
13282 #ifdef INET6
13283 	if (isipv6) {
13284 		ip6 = mtod(m, struct ip6_hdr *);
13285 		if (tp->t_port) {
13286 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13287 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13288 			udp->uh_dport = tp->t_port;
13289 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13290 			udp->uh_ulen = htons(ulen);
13291 			th = (struct tcphdr *)(udp + 1);
13292 		} else {
13293 			th = (struct tcphdr *)(ip6 + 1);
13294 		}
13295 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13296 	} else
13297 #endif				/* INET6 */
13298 	{
13299 		ip = mtod(m, struct ip *);
13300 		if (tp->t_port) {
13301 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13302 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13303 			udp->uh_dport = tp->t_port;
13304 			ulen = hdrlen + len - sizeof(struct ip);
13305 			udp->uh_ulen = htons(ulen);
13306 			th = (struct tcphdr *)(udp + 1);
13307 		} else {
13308 			th = (struct tcphdr *)(ip + 1);
13309 		}
13310 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13311 	}
13312 	/*
13313 	 * If we are doing retransmissions, then snd_nxt will not reflect
13314 	 * the first unsent octet.  For ACK only packets, we do not want the
13315 	 * sequence number of the retransmitted packet, we want the sequence
13316 	 * number of the next unsent octet.  So, if there is no data (and no
13317 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13318 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13319 	 * one byte beyond the right edge of the window, so use snd_nxt in
13320 	 * that case, since we know we aren't doing a retransmission.
13321 	 * (retransmit and persist are mutually exclusive...)
13322 	 */
13323 	if (sack_rxmit == 0) {
13324 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13325 			/* New data (including new persists) */
13326 			th->th_seq = htonl(tp->snd_max);
13327 			bbr_seq = tp->snd_max;
13328 		} else if (flags & TH_SYN) {
13329 			/* Syn's always send from iss */
13330 			th->th_seq = htonl(tp->iss);
13331 			bbr_seq = tp->iss;
13332 		} else if (flags & TH_FIN) {
13333 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13334 				/*
13335 				 * If we sent the fin already its 1 minus
13336 				 * snd_max
13337 				 */
13338 				th->th_seq = (htonl(tp->snd_max - 1));
13339 				bbr_seq = (tp->snd_max - 1);
13340 			} else {
13341 				/* First time FIN use snd_max */
13342 				th->th_seq = htonl(tp->snd_max);
13343 				bbr_seq = tp->snd_max;
13344 			}
13345 		} else {
13346 			/*
13347 			 * len == 0 and not persist we use snd_max, sending
13348 			 * an ack unless we have sent the fin then its 1
13349 			 * minus.
13350 			 */
13351 			/*
13352 			 * XXXRRS Question if we are in persists and we have
13353 			 * nothing outstanding to send and we have not sent
13354 			 * a FIN, we will send an ACK. In such a case it
13355 			 * might be better to send (tp->snd_una - 1) which
13356 			 * would force the peer to ack.
13357 			 */
13358 			if (tp->t_flags & TF_SENTFIN) {
13359 				th->th_seq = htonl(tp->snd_max - 1);
13360 				bbr_seq = (tp->snd_max - 1);
13361 			} else {
13362 				th->th_seq = htonl(tp->snd_max);
13363 				bbr_seq = tp->snd_max;
13364 			}
13365 		}
13366 	} else {
13367 		/* All retransmits use the rsm to guide the send */
13368 		th->th_seq = htonl(rsm->r_start);
13369 		bbr_seq = rsm->r_start;
13370 	}
13371 	th->th_ack = htonl(tp->rcv_nxt);
13372 	if (optlen) {
13373 		bcopy(opt, th + 1, optlen);
13374 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13375 	}
13376 	tcp_set_flags(th, flags);
13377 	/*
13378 	 * Calculate receive window.  Don't shrink window, but avoid silly
13379 	 * window syndrome.
13380 	 */
13381 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13382 				  recwin < maxseg)))
13383 		recwin = 0;
13384 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13385 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13386 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13387 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13388 		recwin = TCP_MAXWIN << tp->rcv_scale;
13389 
13390 	/*
13391 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13392 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13393 	 * handled in syncache.
13394 	 */
13395 	if (flags & TH_SYN)
13396 		th->th_win = htons((u_short)
13397 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13398 	else {
13399 		/* Avoid shrinking window with window scaling. */
13400 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13401 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13402 	}
13403 	/*
13404 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13405 	 * window.  This may cause the remote transmitter to stall.  This
13406 	 * flag tells soreceive() to disable delayed acknowledgements when
13407 	 * draining the buffer.  This can occur if the receiver is
13408 	 * attempting to read more data than can be buffered prior to
13409 	 * transmitting on the connection.
13410 	 */
13411 	if (th->th_win == 0) {
13412 		tp->t_sndzerowin++;
13413 		tp->t_flags |= TF_RXWIN0SENT;
13414 	} else
13415 		tp->t_flags &= ~TF_RXWIN0SENT;
13416 	/*
13417 	 * We don't support urgent data, but drag along
13418 	 * the pointer in case of a stack switch.
13419 	 */
13420 	tp->snd_up = tp->snd_una;
13421 	/*
13422 	 * Put TCP length in extended header, and then checksum extended
13423 	 * header and data.
13424 	 */
13425 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13426 
13427 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13428 	if (to.to_flags & TOF_SIGNATURE) {
13429 		/*
13430 		 * Calculate MD5 signature and put it into the place
13431 		 * determined before. NOTE: since TCP options buffer doesn't
13432 		 * point into mbuf's data, calculate offset and use it.
13433 		 */
13434 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13435 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13436 			/*
13437 			 * Do not send segment if the calculation of MD5
13438 			 * digest has failed.
13439 			 */
13440 			goto out;
13441 		}
13442 	}
13443 #endif
13444 
13445 #ifdef INET6
13446 	if (isipv6) {
13447 		/*
13448 		 * ip6_plen is not need to be filled now, and will be filled
13449 		 * in ip6_output.
13450 		 */
13451 		if (tp->t_port) {
13452 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13453 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13454 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13455 			th->th_sum = htons(0);
13456 			UDPSTAT_INC(udps_opackets);
13457 		} else {
13458 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13459 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13460 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13461 			    optlen + len, IPPROTO_TCP, 0);
13462 		}
13463 	}
13464 #endif
13465 #if defined(INET6) && defined(INET)
13466 	else
13467 #endif
13468 #ifdef INET
13469 	{
13470 		if (tp->t_port) {
13471 			m->m_pkthdr.csum_flags = CSUM_UDP;
13472 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13473 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13474 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13475 			th->th_sum = htons(0);
13476 			UDPSTAT_INC(udps_opackets);
13477 		} else {
13478 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13479 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13480 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13481 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13482 			    IPPROTO_TCP + len + optlen));
13483 		}
13484 		/* IP version must be set here for ipv4/ipv6 checking later */
13485 		KASSERT(ip->ip_v == IPVERSION,
13486 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13487 	}
13488 #endif
13489 
13490 	/*
13491 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13492 	 * header checksum is always provided. XXX: Fixme: This is currently
13493 	 * not the case for IPv6.
13494 	 */
13495 	if (tso) {
13496 		KASSERT(len > maxseg,
13497 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13498 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13499 		csum_flags |= CSUM_TSO;
13500 		m->m_pkthdr.tso_segsz = maxseg;
13501 	}
13502 	KASSERT(len + hdrlen == m_length(m, NULL),
13503 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13504 	    __func__, len, hdrlen, m_length(m, NULL)));
13505 
13506 #ifdef TCP_HHOOK
13507 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13508 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13509 #endif
13510 
13511 	/* Log to the black box */
13512 	if (tcp_bblogging_on(tp)) {
13513 		union tcp_log_stackspecific log;
13514 
13515 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13516 		/* Record info on type of transmission */
13517 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13518 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13519 		log.u_bbr.flex3 = maxseg;
13520 		log.u_bbr.flex4 = delay_calc;
13521 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13522 		log.u_bbr.flex5 <<= 1;
13523 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13524 		log.u_bbr.flex5 <<= 29;
13525 		log.u_bbr.flex5 |= tp->t_maxseg;
13526 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13527 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13528 		/* lets poke in the low and the high here for debugging */
13529 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13530 		if (rsm || sack_rxmit) {
13531 			if (doing_tlp)
13532 				log.u_bbr.flex8 = 2;
13533 			else
13534 				log.u_bbr.flex8 = 1;
13535 		} else {
13536 			log.u_bbr.flex8 = 0;
13537 		}
13538 		lgb = tcp_log_event(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13539 		    len, &log, false, NULL, NULL, 0, tv);
13540 	} else {
13541 		lgb = NULL;
13542 	}
13543 	/*
13544 	 * Fill in IP length and desired time to live and send to IP level.
13545 	 * There should be a better way to handle ttl and tos; we could keep
13546 	 * them in the template, but need a way to checksum without them.
13547 	 */
13548 	/*
13549 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13550 	 * because in6_cksum() need it.
13551 	 */
13552 #ifdef INET6
13553 	if (isipv6) {
13554 		/*
13555 		 * we separately set hoplimit for every segment, since the
13556 		 * user might want to change the value via setsockopt. Also,
13557 		 * desired default hop limit might be changed via Neighbor
13558 		 * Discovery.
13559 		 */
13560 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13561 
13562 		/*
13563 		 * Set the packet size here for the benefit of DTrace
13564 		 * probes. ip6_output() will set it properly; it's supposed
13565 		 * to include the option header lengths as well.
13566 		 */
13567 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13568 
13569 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13570 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13571 		else
13572 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13573 
13574 		if (tp->t_state == TCPS_SYN_SENT)
13575 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13576 
13577 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13578 		/* TODO: IPv6 IP6TOS_ECT bit on */
13579 		error = ip6_output(m, inp->in6p_outputopts,
13580 		    &inp->inp_route6,
13581 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13582 		    NULL, NULL, inp);
13583 
13584 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13585 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13586 	}
13587 #endif				/* INET6 */
13588 #if defined(INET) && defined(INET6)
13589 	else
13590 #endif
13591 #ifdef INET
13592 	{
13593 		ip->ip_len = htons(m->m_pkthdr.len);
13594 #ifdef INET6
13595 		if (isipv6)
13596 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13597 #endif				/* INET6 */
13598 		/*
13599 		 * If we do path MTU discovery, then we set DF on every
13600 		 * packet. This might not be the best thing to do according
13601 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13602 		 * the problem so it affects only the first tcp connection
13603 		 * with a host.
13604 		 *
13605 		 * NB: Don't set DF on small MTU/MSS to have a safe
13606 		 * fallback.
13607 		 */
13608 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13609 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13610 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13611 				ip->ip_off |= htons(IP_DF);
13612 			}
13613 		} else {
13614 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13615 		}
13616 
13617 		if (tp->t_state == TCPS_SYN_SENT)
13618 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13619 
13620 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13621 
13622 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13623 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13624 		    inp);
13625 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13626 			mtu = inp->inp_route.ro_nh->nh_mtu;
13627 	}
13628 #endif				/* INET */
13629 	if (lgb) {
13630 		lgb->tlb_errno = error;
13631 		lgb = NULL;
13632 	}
13633 
13634 out:
13635 	/*
13636 	 * In transmit state, time the transmission and arrange for the
13637 	 * retransmit.  In persist state, just set snd_max.
13638 	 */
13639 	if (error == 0) {
13640 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13641 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13642 		    (tp->t_flags & TF_SACK_PERMIT) &&
13643 		    tp->rcv_numsacks > 0)
13644 			tcp_clean_dsack_blocks(tp);
13645 		/* We sent an ack clear the bbr_segs_rcvd count */
13646 		bbr->output_error_seen = 0;
13647 		bbr->oerror_cnt = 0;
13648 		bbr->bbr_segs_rcvd = 0;
13649 		if (len == 0)
13650 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13651 		/* Do accounting for new sends */
13652 		if ((len > 0) && (rsm == NULL)) {
13653 			int idx;
13654 			if (tp->snd_una == tp->snd_max) {
13655 				/*
13656 				 * Special case to match google, when
13657 				 * nothing is in flight the delivered
13658 				 * time does get updated to the current
13659 				 * time (see tcp_rate_bsd.c).
13660 				 */
13661 				bbr->r_ctl.rc_del_time = cts;
13662 			}
13663 			if (len >= maxseg) {
13664 				idx = (len / maxseg) + 3;
13665 				if (idx >= TCP_MSS_ACCT_ATIMER)
13666 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13667 				else
13668 					counter_u64_add(bbr_out_size[idx], 1);
13669 			} else {
13670 				/* smaller than a MSS */
13671 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13672 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13673 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13674 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13675 			}
13676 		}
13677 	}
13678 	abandon = 0;
13679 	/*
13680 	 * We must do the send accounting before we log the output,
13681 	 * otherwise the state of the rsm could change and we account to the
13682 	 * wrong bucket.
13683 	 */
13684 	if (len > 0) {
13685 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13686 		if (error == 0) {
13687 			if (tp->snd_una == tp->snd_max)
13688 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13689 		}
13690 	}
13691 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13692 	    cts, mb, &abandon, rsm, 0, sb);
13693 	if (abandon) {
13694 		/*
13695 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13696 		 * sent we should hit this condition.
13697 		 */
13698 		return (0);
13699 	}
13700 	if (bbr->rc_in_persist == 0) {
13701 		/*
13702 		 * Advance snd_nxt over sequence space of this segment.
13703 		 */
13704 		if (error)
13705 			/* We don't log or do anything with errors */
13706 			goto skip_upd;
13707 
13708 		if (tp->snd_una == tp->snd_max &&
13709 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13710 			/*
13711 			 * Update the time we just added data since none was
13712 			 * outstanding.
13713 			 */
13714 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13715 			bbr->rc_tp->t_acktime  = ticks;
13716 		}
13717 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13718 			if (flags & TH_SYN) {
13719 				/*
13720 				 * Smack the snd_max to iss + 1
13721 				 * if its a FO we will add len below.
13722 				 */
13723 				tp->snd_max = tp->iss + 1;
13724 			}
13725 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13726 				tp->snd_max++;
13727 				tp->t_flags |= TF_SENTFIN;
13728 			}
13729 		}
13730 		if (sack_rxmit == 0)
13731 			tp->snd_max += len;
13732 skip_upd:
13733 		if ((error == 0) && len)
13734 			tot_len += len;
13735 	} else {
13736 		/* Persists case */
13737 		int32_t xlen = len;
13738 
13739 		if (error)
13740 			goto nomore;
13741 
13742 		if (flags & TH_SYN)
13743 			++xlen;
13744 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13745 			++xlen;
13746 			tp->t_flags |= TF_SENTFIN;
13747 		}
13748 		if (xlen && (tp->snd_una == tp->snd_max)) {
13749 			/*
13750 			 * Update the time we just added data since none was
13751 			 * outstanding.
13752 			 */
13753 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13754 			bbr->rc_tp->t_acktime = ticks;
13755 		}
13756 		if (sack_rxmit == 0)
13757 			tp->snd_max += xlen;
13758 		tot_len += (len + optlen + ipoptlen);
13759 	}
13760 nomore:
13761 	if (error) {
13762 		/*
13763 		 * Failures do not advance the seq counter above. For the
13764 		 * case of ENOBUFS we will fall out and become ack-clocked.
13765 		 * capping the cwnd at the current flight.
13766 		 * Everything else will just have to retransmit with the timer
13767 		 * (no pacer).
13768 		 */
13769 		SOCK_SENDBUF_UNLOCK_ASSERT(so);
13770 		BBR_STAT_INC(bbr_saw_oerr);
13771 		/* Clear all delay/early tracks */
13772 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13773 		bbr->r_ctl.rc_agg_early = 0;
13774 		bbr->r_agg_early_set = 0;
13775 		bbr->output_error_seen = 1;
13776 		if (bbr->oerror_cnt < 0xf)
13777 			bbr->oerror_cnt++;
13778 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13779 			/* drop the session */
13780 			return (-ENETDOWN);
13781 		}
13782 		switch (error) {
13783 		case ENOBUFS:
13784 			/*
13785 			 * Make this guy have to get ack's to send
13786 			 * more but lets make sure we don't
13787 			 * slam him below a T-O (1MSS).
13788 			 */
13789 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13790 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13791 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13792 				if (tp->snd_cwnd < maxseg)
13793 					tp->snd_cwnd = maxseg;
13794 			}
13795 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13796 			BBR_STAT_INC(bbr_saw_enobuf);
13797 			if (bbr->bbr_hdrw_pacing)
13798 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13799 			else
13800 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13801 			/*
13802 			 * Here even in the enobuf's case we want to do our
13803 			 * state update. The reason being we may have been
13804 			 * called by the input function. If so we have had
13805 			 * things change.
13806 			 */
13807 			error = 0;
13808 			goto enobufs;
13809 		case EMSGSIZE:
13810 			/*
13811 			 * For some reason the interface we used initially
13812 			 * to send segments changed to another or lowered
13813 			 * its MTU. If TSO was active we either got an
13814 			 * interface without TSO capabilits or TSO was
13815 			 * turned off. If we obtained mtu from ip_output()
13816 			 * then update it and try again.
13817 			 */
13818 			/* Turn on tracing (or try to) */
13819 			{
13820 				int old_maxseg;
13821 
13822 				old_maxseg = tp->t_maxseg;
13823 				BBR_STAT_INC(bbr_saw_emsgsiz);
13824 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13825 				if (mtu != 0)
13826 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13827 				if (old_maxseg <= tp->t_maxseg) {
13828 					/* Huh it did not shrink? */
13829 					tp->t_maxseg = old_maxseg - 40;
13830 					if (tp->t_maxseg < V_tcp_mssdflt) {
13831 						/*
13832 						 * The MSS is so small we should not
13833 						 * process incoming SACK's since we are
13834 						 * subject to attack in such a case.
13835 						 */
13836 						tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
13837 					} else {
13838 						tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
13839 					}
13840 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13841 				}
13842 				/*
13843 				 * Nuke all other things that can interfere
13844 				 * with slot
13845 				 */
13846 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13847 					slot = bbr_get_pacing_delay(bbr,
13848 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13849 					    (tot_len + len), cts, 0);
13850 					if (slot < bbr_error_base_paceout)
13851 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13852 				} else
13853 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13854 				bbr->rc_output_starts_timer = 1;
13855 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13856 				    tot_len);
13857 				return (error);
13858 			}
13859 		case EPERM:
13860 		case EACCES:
13861 			tp->t_softerror = error;
13862 			/* FALLTHROUGH */
13863 		case EHOSTDOWN:
13864 		case EHOSTUNREACH:
13865 		case ENETDOWN:
13866 		case ENETUNREACH:
13867 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13868 				tp->t_softerror = error;
13869 				error = 0;
13870 			}
13871 			/* FALLTHROUGH */
13872 		default:
13873 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13874 			bbr->rc_output_starts_timer = 1;
13875 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13876 			return (error);
13877 		}
13878 #ifdef STATS
13879 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13880 		    len &&
13881 		    (rsm == NULL) &&
13882 	    (bbr->rc_in_persist == 0)) {
13883 		tp->gput_seq = bbr_seq;
13884 		tp->gput_ack = bbr_seq +
13885 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13886 		tp->gput_ts = cts;
13887 		tp->t_flags |= TF_GPUTINPROG;
13888 #endif
13889 	}
13890 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13891 	if ((bbr->bbr_hdw_pace_ena) &&
13892 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13893 	    (bbr->rc_past_init_win) &&
13894 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13895 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13896 	    (inp->inp_route.ro_nh &&
13897 	     inp->inp_route.ro_nh->nh_ifp)) {
13898 		/*
13899 		 * We are past the initial window and
13900 		 * have at least one measurement so we
13901 		 * could use hardware pacing if its available.
13902 		 * We have an interface and we have not attempted
13903 		 * to setup hardware pacing, lets try to now.
13904 		 */
13905 		uint64_t rate_wanted;
13906 		int err = 0;
13907 
13908 		rate_wanted = bbr_get_hardware_rate(bbr);
13909 		bbr->bbr_attempt_hdwr_pace = 1;
13910 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13911 						      inp->inp_route.ro_nh->nh_ifp,
13912 						      rate_wanted,
13913 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
13914 						      &err, NULL);
13915 		if (bbr->r_ctl.crte) {
13916 			bbr_type_log_hdwr_pacing(bbr,
13917 						 bbr->r_ctl.crte->ptbl->rs_ifp,
13918 						 rate_wanted,
13919 						 bbr->r_ctl.crte->rate,
13920 						 __LINE__, cts, err);
13921 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
13922 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
13923 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
13924 			bbr->bbr_hdrw_pacing = 1;
13925 			/* Now what is our gain status? */
13926 			if (bbr->r_ctl.crte->rate < rate_wanted) {
13927 				/* We have a problem */
13928 				bbr_setup_less_of_rate(bbr, cts,
13929 						       bbr->r_ctl.crte->rate, rate_wanted);
13930 			} else {
13931 				/* We are good */
13932 				bbr->gain_is_limited = 0;
13933 				bbr->skip_gain = 0;
13934 			}
13935 			tcp_bbr_tso_size_check(bbr, cts);
13936 		} else {
13937 			bbr_type_log_hdwr_pacing(bbr,
13938 						 inp->inp_route.ro_nh->nh_ifp,
13939 						 rate_wanted,
13940 						 0,
13941 						 __LINE__, cts, err);
13942 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
13943 		}
13944 	}
13945 	if (bbr->bbr_hdrw_pacing) {
13946 		/*
13947 		 * Worry about cases where the route
13948 		 * changes or something happened that we
13949 		 * lost our hardware pacing possibly during
13950 		 * the last ip_output call.
13951 		 */
13952 		if (inp->inp_snd_tag == NULL) {
13953 			/* A change during ip output disabled hw pacing? */
13954 			bbr->bbr_hdrw_pacing = 0;
13955 		} else if ((inp->inp_route.ro_nh == NULL) ||
13956 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
13957 			/*
13958 			 * We had an interface or route change,
13959 			 * detach from the current hdwr pacing
13960 			 * and setup to re-attempt next go
13961 			 * round.
13962 			 */
13963 			bbr->bbr_hdrw_pacing = 0;
13964 			bbr->bbr_attempt_hdwr_pace = 0;
13965 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
13966 			tcp_bbr_tso_size_check(bbr, cts);
13967 		}
13968 	}
13969 	/*
13970 	 * Data sent (as far as we can tell). If this advertises a larger
13971 	 * window than any other segment, then remember the size of the
13972 	 * advertised window. Any pending ACK has now been sent.
13973 	 */
13974 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
13975 		tp->rcv_adv = tp->rcv_nxt + recwin;
13976 
13977 	tp->last_ack_sent = tp->rcv_nxt;
13978 	if ((error == 0) &&
13979 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
13980 	    (doing_tlp == 0) &&
13981 	    (tso == 0) &&
13982 	    (len > 0) &&
13983 	    ((flags & TH_RST) == 0) &&
13984 	    ((flags & TH_SYN) == 0) &&
13985 	    (IN_RECOVERY(tp->t_flags) == 0) &&
13986 	    (bbr->rc_in_persist == 0) &&
13987 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
13988 		/*
13989 		 * For non-tso we need to goto again until we have sent out
13990 		 * enough data to match what we are hptsi out every hptsi
13991 		 * interval.
13992 		 */
13993 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13994 			/* Make sure snd_nxt is drug up */
13995 			tp->snd_nxt = tp->snd_max;
13996 		}
13997 		if (rsm != NULL) {
13998 			rsm = NULL;
13999 			goto skip_again;
14000 		}
14001 		rsm = NULL;
14002 		sack_rxmit = 0;
14003 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14004 		goto again;
14005 	}
14006 skip_again:
14007 	if ((error == 0) && (flags & TH_FIN))
14008 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
14009 	if ((error == 0) && (flags & TH_RST))
14010 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
14011 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14012 		/*
14013 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
14014 		 * what we have sent so far
14015 		 */
14016 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14017 		if (bbr->rc_no_pacing)
14018 			slot = 0;
14019 	}
14020 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14021 enobufs:
14022 	if (bbr->rc_use_google == 0)
14023 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14024 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14025 							bbr->r_ctl.rc_lost_bytes)));
14026 	bbr->rc_output_starts_timer = 1;
14027 	if (bbr->bbr_use_rack_cheat &&
14028 	    (more_to_rxt ||
14029 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14030 		/* Rack cheats and shotguns out all rxt's 1ms apart */
14031 		if (slot > 1000)
14032 			slot = 1000;
14033 	}
14034 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14035 		/*
14036 		 * We don't change the tso size until some number of sends
14037 		 * to give the hardware commands time to get down
14038 		 * to the interface.
14039 		 */
14040 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14041 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14042 			bbr->hw_pacing_set = 1;
14043 			tcp_bbr_tso_size_check(bbr, cts);
14044 		}
14045 	}
14046 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14047 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14048 		/* Make sure snd_nxt is drug up */
14049 		tp->snd_nxt = tp->snd_max;
14050 	}
14051 	return (error);
14052 
14053 }
14054 
14055 /*
14056  * See bbr_output_wtime() for return values.
14057  */
14058 static int
14059 bbr_output(struct tcpcb *tp)
14060 {
14061 	int32_t ret;
14062 	struct timeval tv;
14063 
14064 	NET_EPOCH_ASSERT();
14065 
14066 	INP_WLOCK_ASSERT(tptoinpcb(tp));
14067 	(void)tcp_get_usecs(&tv);
14068 	ret = bbr_output_wtime(tp, &tv);
14069 	return (ret);
14070 }
14071 
14072 static void
14073 bbr_mtu_chg(struct tcpcb *tp)
14074 {
14075 	struct tcp_bbr *bbr;
14076 	struct bbr_sendmap *rsm, *frsm = NULL;
14077 	uint32_t maxseg;
14078 
14079 	/*
14080 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14081 	 * over the current size as SACK_PASS so a retransmit will occur.
14082 	 */
14083 
14084 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14085 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14086 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14087 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14088 		/* Don't mess with ones acked (by sack?) */
14089 		if (rsm->r_flags & BBR_ACKED)
14090 			continue;
14091 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14092 			/*
14093 			 * We mark sack-passed on all the previous large
14094 			 * sends we did. This will force them to retransmit.
14095 			 */
14096 			rsm->r_flags |= BBR_SACK_PASSED;
14097 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14098 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14099 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14100 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14101 				rsm->r_flags |= BBR_MARKED_LOST;
14102 			}
14103 			if (frsm == NULL)
14104 				frsm = rsm;
14105 		}
14106 	}
14107 	if (frsm) {
14108 		bbr->r_ctl.rc_resend = frsm;
14109 	}
14110 }
14111 
14112 static int
14113 bbr_pru_options(struct tcpcb *tp, int flags)
14114 {
14115 	if (flags & PRUS_OOB)
14116 		return (EOPNOTSUPP);
14117 	return (0);
14118 }
14119 
14120 static void
14121 bbr_switch_failed(struct tcpcb *tp)
14122 {
14123 	/*
14124 	 * If a switch fails we only need to
14125 	 * make sure mbuf_queuing is still in place.
14126 	 * We also need to make sure we are still in
14127 	 * ticks granularity (though we should probably
14128 	 * change bbr to go to USECs).
14129 	 *
14130 	 * For timers we need to see if we are still in the
14131 	 * pacer (if our flags are up) if so we are good, if
14132 	 * not we need to get back into the pacer.
14133 	 */
14134 	struct timeval tv;
14135 	uint32_t cts;
14136 	uint32_t toval;
14137 	struct tcp_bbr *bbr;
14138 	struct hpts_diag diag;
14139 
14140 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
14141 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
14142 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
14143 	if (tp->t_in_hpts > IHPTS_NONE) {
14144 		return;
14145 	}
14146 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14147 	cts = tcp_get_usecs(&tv);
14148 	if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
14149 		if (TSTMP_GT(bbr->rc_pacer_started, cts)) {
14150 			toval = bbr->rc_pacer_started - cts;
14151 		} else {
14152 			/* one slot please */
14153 			toval = HPTS_TICKS_PER_SLOT;
14154 		}
14155 	} else if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
14156 		if (TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
14157 			toval = bbr->r_ctl.rc_timer_exp - cts;
14158 		} else {
14159 			/* one slot please */
14160 			toval = HPTS_TICKS_PER_SLOT;
14161 		}
14162 	} else
14163 		toval = HPTS_TICKS_PER_SLOT;
14164 	(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(toval),
14165 				   __LINE__, &diag);
14166 	bbr_log_hpts_diag(bbr, cts, &diag);
14167 }
14168 
14169 struct tcp_function_block __tcp_bbr = {
14170 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14171 	.tfb_tcp_output = bbr_output,
14172 	.tfb_do_queued_segments = ctf_do_queued_segments,
14173 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14174 	.tfb_tcp_do_segment = bbr_do_segment,
14175 	.tfb_tcp_ctloutput = bbr_ctloutput,
14176 	.tfb_tcp_fb_init = bbr_init,
14177 	.tfb_tcp_fb_fini = bbr_fini,
14178 	.tfb_tcp_timer_stop_all = bbr_stopall,
14179 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14180 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14181 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14182 	.tfb_pru_options = bbr_pru_options,
14183 	.tfb_switch_failed = bbr_switch_failed,
14184 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP | TCP_FUNC_DEFAULT_OK,
14185 };
14186 
14187 /*
14188  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14189  * socket option arguments.  When it re-acquires the lock after the copy, it
14190  * has to revalidate that the connection is still valid for the socket
14191  * option.
14192  */
14193 static int
14194 bbr_set_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14195 {
14196 	struct epoch_tracker et;
14197 	struct inpcb *inp = tptoinpcb(tp);
14198 	struct tcp_bbr *bbr;
14199 	int32_t error = 0, optval;
14200 
14201 	switch (sopt->sopt_level) {
14202 	case IPPROTO_IPV6:
14203 	case IPPROTO_IP:
14204 		return (tcp_default_ctloutput(tp, sopt));
14205 	}
14206 
14207 	switch (sopt->sopt_name) {
14208 	case TCP_RACK_PACE_MAX_SEG:
14209 	case TCP_RACK_MIN_TO:
14210 	case TCP_RACK_REORD_THRESH:
14211 	case TCP_RACK_REORD_FADE:
14212 	case TCP_RACK_TLP_THRESH:
14213 	case TCP_RACK_PKT_DELAY:
14214 	case TCP_BBR_ALGORITHM:
14215 	case TCP_BBR_TSLIMITS:
14216 	case TCP_BBR_IWINTSO:
14217 	case TCP_BBR_STARTUP_PG:
14218 	case TCP_BBR_DRAIN_PG:
14219 	case TCP_BBR_PROBE_RTT_INT:
14220 	case TCP_BBR_PROBE_RTT_GAIN:
14221 	case TCP_BBR_PROBE_RTT_LEN:
14222 	case TCP_BBR_STARTUP_LOSS_EXIT:
14223 	case TCP_BBR_USEDEL_RATE:
14224 	case TCP_BBR_MIN_RTO:
14225 	case TCP_BBR_MAX_RTO:
14226 	case TCP_BBR_PACE_PER_SEC:
14227 	case TCP_DELACK:
14228 	case TCP_BBR_PACE_DEL_TAR:
14229 	case TCP_BBR_SEND_IWND_IN_TSO:
14230 	case TCP_BBR_EXTRA_STATE:
14231 	case TCP_BBR_UTTER_MAX_TSO:
14232 	case TCP_BBR_MIN_TOPACEOUT:
14233 	case TCP_BBR_FLOOR_MIN_TSO:
14234 	case TCP_BBR_TSTMP_RAISES:
14235 	case TCP_BBR_POLICER_DETECT:
14236 	case TCP_BBR_USE_RACK_CHEAT:
14237 	case TCP_DATA_AFTER_CLOSE:
14238 	case TCP_BBR_HDWR_PACE:
14239 	case TCP_BBR_PACE_SEG_MAX:
14240 	case TCP_BBR_PACE_SEG_MIN:
14241 	case TCP_BBR_PACE_CROSS:
14242 	case TCP_BBR_PACE_OH:
14243 	case TCP_BBR_TMR_PACE_OH:
14244 	case TCP_BBR_RACK_RTT_USE:
14245 	case TCP_BBR_RETRAN_WTSO:
14246 		break;
14247 	default:
14248 		return (tcp_default_ctloutput(tp, sopt));
14249 		break;
14250 	}
14251 	INP_WUNLOCK(inp);
14252 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14253 	if (error)
14254 		return (error);
14255 	INP_WLOCK(inp);
14256 	if (inp->inp_flags & INP_DROPPED) {
14257 		INP_WUNLOCK(inp);
14258 		return (ECONNRESET);
14259 	}
14260 	if (tp->t_fb != &__tcp_bbr) {
14261 		INP_WUNLOCK(inp);
14262 		return (ENOPROTOOPT);
14263 	}
14264 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14265 	switch (sopt->sopt_name) {
14266 	case TCP_BBR_PACE_PER_SEC:
14267 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14268 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14269 		break;
14270 	case TCP_BBR_PACE_DEL_TAR:
14271 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14272 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14273 		break;
14274 	case TCP_BBR_PACE_SEG_MAX:
14275 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14276 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14277 		break;
14278 	case TCP_BBR_PACE_SEG_MIN:
14279 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14280 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14281 		break;
14282 	case TCP_BBR_PACE_CROSS:
14283 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14284 		bbr->r_ctl.bbr_cross_over = optval;
14285 		break;
14286 	case TCP_BBR_ALGORITHM:
14287 		BBR_OPTS_INC(tcp_bbr_algorithm);
14288 		if (optval && (bbr->rc_use_google == 0)) {
14289 			/* Turn on the google mode */
14290 			bbr_google_mode_on(bbr);
14291 			if ((optval > 3) && (optval < 500)) {
14292 				/*
14293 				 * Must be at least greater than .3%
14294 				 * and must be less than 50.0%.
14295 				 */
14296 				bbr->r_ctl.bbr_google_discount = optval;
14297 			}
14298 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14299 			/* Turn off the google mode */
14300 			bbr_google_mode_off(bbr);
14301 		}
14302 		break;
14303 	case TCP_BBR_TSLIMITS:
14304 		BBR_OPTS_INC(tcp_bbr_tslimits);
14305 		if (optval == 1)
14306 			bbr->rc_use_ts_limit = 1;
14307 		else if (optval == 0)
14308 			bbr->rc_use_ts_limit = 0;
14309 		else
14310 			error = EINVAL;
14311 		break;
14312 
14313 	case TCP_BBR_IWINTSO:
14314 		BBR_OPTS_INC(tcp_bbr_iwintso);
14315 		if ((optval >= 0) && (optval < 128)) {
14316 			uint32_t twin;
14317 
14318 			bbr->rc_init_win = optval;
14319 			twin = bbr_initial_cwnd(bbr, tp);
14320 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14321 				tp->snd_cwnd = twin;
14322 			else
14323 				error = EBUSY;
14324 		} else
14325 			error = EINVAL;
14326 		break;
14327 	case TCP_BBR_STARTUP_PG:
14328 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14329 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14330 			bbr->r_ctl.rc_startup_pg = optval;
14331 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14332 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14333 			}
14334 		} else
14335 			error = EINVAL;
14336 		break;
14337 	case TCP_BBR_DRAIN_PG:
14338 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14339 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14340 			bbr->r_ctl.rc_drain_pg = optval;
14341 		else
14342 			error = EINVAL;
14343 		break;
14344 	case TCP_BBR_PROBE_RTT_LEN:
14345 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14346 		if (optval <= 1)
14347 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14348 		else
14349 			error = EINVAL;
14350 		break;
14351 	case TCP_BBR_PROBE_RTT_GAIN:
14352 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14353 		if (optval <= BBR_UNIT)
14354 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14355 		else
14356 			error = EINVAL;
14357 		break;
14358 	case TCP_BBR_PROBE_RTT_INT:
14359 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14360 		if (optval > 1000)
14361 			bbr->r_ctl.rc_probertt_int = optval;
14362 		else
14363 			error = EINVAL;
14364 		break;
14365 	case TCP_BBR_MIN_TOPACEOUT:
14366 		BBR_OPTS_INC(tcp_bbr_topaceout);
14367 		if (optval == 0) {
14368 			bbr->no_pacing_until = 0;
14369 			bbr->rc_no_pacing = 0;
14370 		} else if (optval <= 0x00ff) {
14371 			bbr->no_pacing_until = optval;
14372 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14373 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14374 				/* Turn on no pacing */
14375 				bbr->rc_no_pacing = 1;
14376 			}
14377 		} else
14378 			error = EINVAL;
14379 		break;
14380 	case TCP_BBR_STARTUP_LOSS_EXIT:
14381 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14382 		bbr->rc_loss_exit = optval;
14383 		break;
14384 	case TCP_BBR_USEDEL_RATE:
14385 		error = EINVAL;
14386 		break;
14387 	case TCP_BBR_MIN_RTO:
14388 		BBR_OPTS_INC(tcp_bbr_min_rto);
14389 		bbr->r_ctl.rc_min_rto_ms = optval;
14390 		break;
14391 	case TCP_BBR_MAX_RTO:
14392 		BBR_OPTS_INC(tcp_bbr_max_rto);
14393 		bbr->rc_max_rto_sec = optval;
14394 		break;
14395 	case TCP_RACK_MIN_TO:
14396 		/* Minimum time between rack t-o's in ms */
14397 		BBR_OPTS_INC(tcp_rack_min_to);
14398 		bbr->r_ctl.rc_min_to = optval;
14399 		break;
14400 	case TCP_RACK_REORD_THRESH:
14401 		/* RACK reorder threshold (shift amount) */
14402 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14403 		if ((optval > 0) && (optval < 31))
14404 			bbr->r_ctl.rc_reorder_shift = optval;
14405 		else
14406 			error = EINVAL;
14407 		break;
14408 	case TCP_RACK_REORD_FADE:
14409 		/* Does reordering fade after ms time */
14410 		BBR_OPTS_INC(tcp_rack_reord_fade);
14411 		bbr->r_ctl.rc_reorder_fade = optval;
14412 		break;
14413 	case TCP_RACK_TLP_THRESH:
14414 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14415 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14416 		if (optval)
14417 			bbr->rc_tlp_threshold = optval;
14418 		else
14419 			error = EINVAL;
14420 		break;
14421 	case TCP_BBR_USE_RACK_CHEAT:
14422 		BBR_OPTS_INC(tcp_use_rackcheat);
14423 		if (bbr->rc_use_google) {
14424 			error = EINVAL;
14425 			break;
14426 		}
14427 		BBR_OPTS_INC(tcp_rack_cheat);
14428 		if (optval)
14429 			bbr->bbr_use_rack_cheat = 1;
14430 		else
14431 			bbr->bbr_use_rack_cheat = 0;
14432 		break;
14433 	case TCP_BBR_FLOOR_MIN_TSO:
14434 		BBR_OPTS_INC(tcp_utter_max_tso);
14435 		if ((optval >= 0) && (optval < 40))
14436 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14437 		else
14438 			error = EINVAL;
14439 		break;
14440 	case TCP_BBR_UTTER_MAX_TSO:
14441 		BBR_OPTS_INC(tcp_utter_max_tso);
14442 		if ((optval >= 0) && (optval < 0xffff))
14443 			bbr->r_ctl.bbr_utter_max = optval;
14444 		else
14445 			error = EINVAL;
14446 		break;
14447 
14448 	case TCP_BBR_EXTRA_STATE:
14449 		BBR_OPTS_INC(tcp_extra_state);
14450 		if (optval)
14451 			bbr->rc_use_idle_restart = 1;
14452 		else
14453 			bbr->rc_use_idle_restart = 0;
14454 		break;
14455 	case TCP_BBR_SEND_IWND_IN_TSO:
14456 		BBR_OPTS_INC(tcp_iwnd_tso);
14457 		if (optval) {
14458 			bbr->bbr_init_win_cheat = 1;
14459 			if (bbr->rc_past_init_win == 0) {
14460 				uint32_t cts;
14461 				cts = tcp_get_usecs(&bbr->rc_tv);
14462 				tcp_bbr_tso_size_check(bbr, cts);
14463 			}
14464 		} else
14465 			bbr->bbr_init_win_cheat = 0;
14466 		break;
14467 	case TCP_BBR_HDWR_PACE:
14468 		BBR_OPTS_INC(tcp_hdwr_pacing);
14469 		if (optval){
14470 			bbr->bbr_hdw_pace_ena = 1;
14471 			bbr->bbr_attempt_hdwr_pace = 0;
14472 		} else {
14473 			bbr->bbr_hdw_pace_ena = 0;
14474 #ifdef RATELIMIT
14475 			if (bbr->r_ctl.crte != NULL) {
14476 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14477 				bbr->r_ctl.crte = NULL;
14478 			}
14479 #endif
14480 		}
14481 		break;
14482 
14483 	case TCP_DELACK:
14484 		BBR_OPTS_INC(tcp_delack);
14485 		if (optval < 100) {
14486 			if (optval == 0) /* off */
14487 				tp->t_delayed_ack = 0;
14488 			else if (optval == 1) /* on which is 2 */
14489 				tp->t_delayed_ack = 2;
14490 			else /* higher than 2 and less than 100 */
14491 				tp->t_delayed_ack = optval;
14492 			if (tp->t_flags & TF_DELACK) {
14493 				tp->t_flags &= ~TF_DELACK;
14494 				tp->t_flags |= TF_ACKNOW;
14495 				NET_EPOCH_ENTER(et);
14496 				bbr_output(tp);
14497 				NET_EPOCH_EXIT(et);
14498 			}
14499 		} else
14500 			error = EINVAL;
14501 		break;
14502 	case TCP_RACK_PKT_DELAY:
14503 		/* RACK added ms i.e. rack-rtt + reord + N */
14504 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14505 		bbr->r_ctl.rc_pkt_delay = optval;
14506 		break;
14507 
14508 	case TCP_BBR_RETRAN_WTSO:
14509 		BBR_OPTS_INC(tcp_retran_wtso);
14510 		if (optval)
14511 			bbr->rc_resends_use_tso = 1;
14512 		else
14513 			bbr->rc_resends_use_tso = 0;
14514 		break;
14515 	case TCP_DATA_AFTER_CLOSE:
14516 		BBR_OPTS_INC(tcp_data_ac);
14517 		if (optval)
14518 			bbr->rc_allow_data_af_clo = 1;
14519 		else
14520 			bbr->rc_allow_data_af_clo = 0;
14521 		break;
14522 	case TCP_BBR_POLICER_DETECT:
14523 		BBR_OPTS_INC(tcp_policer_det);
14524 		if (bbr->rc_use_google == 0)
14525 			error = EINVAL;
14526 		else if (optval)
14527 			bbr->r_use_policer = 1;
14528 		else
14529 			bbr->r_use_policer = 0;
14530 		break;
14531 
14532 	case TCP_BBR_TSTMP_RAISES:
14533 		BBR_OPTS_INC(tcp_ts_raises);
14534 		if (optval)
14535 			bbr->ts_can_raise = 1;
14536 		else
14537 			bbr->ts_can_raise = 0;
14538 		break;
14539 	case TCP_BBR_TMR_PACE_OH:
14540 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14541 		if (bbr->rc_use_google) {
14542 			error = EINVAL;
14543 		} else {
14544 			if (optval)
14545 				bbr->r_ctl.rc_incr_tmrs = 1;
14546 			else
14547 				bbr->r_ctl.rc_incr_tmrs = 0;
14548 		}
14549 		break;
14550 	case TCP_BBR_PACE_OH:
14551 		BBR_OPTS_INC(tcp_pacing_oh);
14552 		if (bbr->rc_use_google) {
14553 			error = EINVAL;
14554 		} else {
14555 			if (optval > (BBR_INCL_TCP_OH|
14556 				      BBR_INCL_IP_OH|
14557 				      BBR_INCL_ENET_OH)) {
14558 				error = EINVAL;
14559 				break;
14560 			}
14561 			if (optval & BBR_INCL_TCP_OH)
14562 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14563 			else
14564 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14565 			if (optval & BBR_INCL_IP_OH)
14566 				bbr->r_ctl.rc_inc_ip_oh = 1;
14567 			else
14568 				bbr->r_ctl.rc_inc_ip_oh = 0;
14569 			if (optval & BBR_INCL_ENET_OH)
14570 				bbr->r_ctl.rc_inc_enet_oh = 1;
14571 			else
14572 				bbr->r_ctl.rc_inc_enet_oh = 0;
14573 		}
14574 		break;
14575 	default:
14576 		return (tcp_default_ctloutput(tp, sopt));
14577 		break;
14578 	}
14579 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14580 	INP_WUNLOCK(inp);
14581 	return (error);
14582 }
14583 
14584 /*
14585  * return 0 on success, error-num on failure
14586  */
14587 static int
14588 bbr_get_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14589 {
14590 	struct inpcb *inp = tptoinpcb(tp);
14591 	struct tcp_bbr *bbr;
14592 	int32_t error, optval;
14593 
14594 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14595 	if (bbr == NULL) {
14596 		INP_WUNLOCK(inp);
14597 		return (EINVAL);
14598 	}
14599 	/*
14600 	 * Because all our options are either boolean or an int, we can just
14601 	 * pull everything into optval and then unlock and copy. If we ever
14602 	 * add a option that is not a int, then this will have quite an
14603 	 * impact to this routine.
14604 	 */
14605 	switch (sopt->sopt_name) {
14606 	case TCP_BBR_PACE_PER_SEC:
14607 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14608 		break;
14609 	case TCP_BBR_PACE_DEL_TAR:
14610 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14611 		break;
14612 	case TCP_BBR_PACE_SEG_MAX:
14613 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14614 		break;
14615 	case TCP_BBR_MIN_TOPACEOUT:
14616 		optval = bbr->no_pacing_until;
14617 		break;
14618 	case TCP_BBR_PACE_SEG_MIN:
14619 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14620 		break;
14621 	case TCP_BBR_PACE_CROSS:
14622 		optval = bbr->r_ctl.bbr_cross_over;
14623 		break;
14624 	case TCP_BBR_ALGORITHM:
14625 		optval = bbr->rc_use_google;
14626 		break;
14627 	case TCP_BBR_TSLIMITS:
14628 		optval = bbr->rc_use_ts_limit;
14629 		break;
14630 	case TCP_BBR_IWINTSO:
14631 		optval = bbr->rc_init_win;
14632 		break;
14633 	case TCP_BBR_STARTUP_PG:
14634 		optval = bbr->r_ctl.rc_startup_pg;
14635 		break;
14636 	case TCP_BBR_DRAIN_PG:
14637 		optval = bbr->r_ctl.rc_drain_pg;
14638 		break;
14639 	case TCP_BBR_PROBE_RTT_INT:
14640 		optval = bbr->r_ctl.rc_probertt_int;
14641 		break;
14642 	case TCP_BBR_PROBE_RTT_LEN:
14643 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14644 		break;
14645 	case TCP_BBR_PROBE_RTT_GAIN:
14646 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14647 		break;
14648 	case TCP_BBR_STARTUP_LOSS_EXIT:
14649 		optval = bbr->rc_loss_exit;
14650 		break;
14651 	case TCP_BBR_USEDEL_RATE:
14652 		error = EINVAL;
14653 		break;
14654 	case TCP_BBR_MIN_RTO:
14655 		optval = bbr->r_ctl.rc_min_rto_ms;
14656 		break;
14657 	case TCP_BBR_MAX_RTO:
14658 		optval = bbr->rc_max_rto_sec;
14659 		break;
14660 	case TCP_RACK_PACE_MAX_SEG:
14661 		/* Max segments in a pace */
14662 		optval = bbr->r_ctl.rc_pace_max_segs;
14663 		break;
14664 	case TCP_RACK_MIN_TO:
14665 		/* Minimum time between rack t-o's in ms */
14666 		optval = bbr->r_ctl.rc_min_to;
14667 		break;
14668 	case TCP_RACK_REORD_THRESH:
14669 		/* RACK reorder threshold (shift amount) */
14670 		optval = bbr->r_ctl.rc_reorder_shift;
14671 		break;
14672 	case TCP_RACK_REORD_FADE:
14673 		/* Does reordering fade after ms time */
14674 		optval = bbr->r_ctl.rc_reorder_fade;
14675 		break;
14676 	case TCP_BBR_USE_RACK_CHEAT:
14677 		/* Do we use the rack cheat for rxt */
14678 		optval = bbr->bbr_use_rack_cheat;
14679 		break;
14680 	case TCP_BBR_FLOOR_MIN_TSO:
14681 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14682 		break;
14683 	case TCP_BBR_UTTER_MAX_TSO:
14684 		optval = bbr->r_ctl.bbr_utter_max;
14685 		break;
14686 	case TCP_BBR_SEND_IWND_IN_TSO:
14687 		/* Do we send TSO size segments initially */
14688 		optval = bbr->bbr_init_win_cheat;
14689 		break;
14690 	case TCP_BBR_EXTRA_STATE:
14691 		optval = bbr->rc_use_idle_restart;
14692 		break;
14693 	case TCP_RACK_TLP_THRESH:
14694 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14695 		optval = bbr->rc_tlp_threshold;
14696 		break;
14697 	case TCP_RACK_PKT_DELAY:
14698 		/* RACK added ms i.e. rack-rtt + reord + N */
14699 		optval = bbr->r_ctl.rc_pkt_delay;
14700 		break;
14701 	case TCP_BBR_RETRAN_WTSO:
14702 		optval = bbr->rc_resends_use_tso;
14703 		break;
14704 	case TCP_DATA_AFTER_CLOSE:
14705 		optval = bbr->rc_allow_data_af_clo;
14706 		break;
14707 	case TCP_DELACK:
14708 		optval = tp->t_delayed_ack;
14709 		break;
14710 	case TCP_BBR_HDWR_PACE:
14711 		optval = bbr->bbr_hdw_pace_ena;
14712 		break;
14713 	case TCP_BBR_POLICER_DETECT:
14714 		optval = bbr->r_use_policer;
14715 		break;
14716 	case TCP_BBR_TSTMP_RAISES:
14717 		optval = bbr->ts_can_raise;
14718 		break;
14719 	case TCP_BBR_TMR_PACE_OH:
14720 		optval = bbr->r_ctl.rc_incr_tmrs;
14721 		break;
14722 	case TCP_BBR_PACE_OH:
14723 		optval = 0;
14724 		if (bbr->r_ctl.rc_inc_tcp_oh)
14725 			optval |= BBR_INCL_TCP_OH;
14726 		if (bbr->r_ctl.rc_inc_ip_oh)
14727 			optval |= BBR_INCL_IP_OH;
14728 		if (bbr->r_ctl.rc_inc_enet_oh)
14729 			optval |= BBR_INCL_ENET_OH;
14730 		break;
14731 	default:
14732 		return (tcp_default_ctloutput(tp, sopt));
14733 		break;
14734 	}
14735 	INP_WUNLOCK(inp);
14736 	error = sooptcopyout(sopt, &optval, sizeof optval);
14737 	return (error);
14738 }
14739 
14740 /*
14741  * return 0 on success, error-num on failure
14742  */
14743 static int
14744 bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt)
14745 {
14746 	if (sopt->sopt_dir == SOPT_SET) {
14747 		return (bbr_set_sockopt(tp, sopt));
14748 	} else if (sopt->sopt_dir == SOPT_GET) {
14749 		return (bbr_get_sockopt(tp, sopt));
14750 	} else {
14751 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14752 	}
14753 }
14754 
14755 static const char *bbr_stack_names[] = {
14756 	__XSTRING(STACKNAME),
14757 #ifdef STACKALIAS
14758 	__XSTRING(STACKALIAS),
14759 #endif
14760 };
14761 
14762 static bool bbr_mod_inited = false;
14763 
14764 static int
14765 tcp_addbbr(module_t mod, int32_t type, void *data)
14766 {
14767 	int32_t err = 0;
14768 	int num_stacks;
14769 
14770 	switch (type) {
14771 	case MOD_LOAD:
14772 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14773 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14774 		    sizeof(struct bbr_sendmap),
14775 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14776 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14777 		    sizeof(struct tcp_bbr),
14778 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14779 		sysctl_ctx_init(&bbr_sysctl_ctx);
14780 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14781 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14782 		    OID_AUTO,
14783 #ifdef STACKALIAS
14784 		    __XSTRING(STACKALIAS),
14785 #else
14786 		    __XSTRING(STACKNAME),
14787 #endif
14788 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14789 		    "");
14790 		if (bbr_sysctl_root == NULL) {
14791 			printf("Failed to add sysctl node\n");
14792 			err = EFAULT;
14793 			goto free_uma;
14794 		}
14795 		bbr_init_sysctls();
14796 		num_stacks = nitems(bbr_stack_names);
14797 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14798 		    bbr_stack_names, &num_stacks);
14799 		if (err) {
14800 			printf("Failed to register %s stack name for "
14801 			    "%s module\n", bbr_stack_names[num_stacks],
14802 			    __XSTRING(MODNAME));
14803 			sysctl_ctx_free(&bbr_sysctl_ctx);
14804 	free_uma:
14805 			uma_zdestroy(bbr_zone);
14806 			uma_zdestroy(bbr_pcb_zone);
14807 			bbr_counter_destroy();
14808 			printf("Failed to register " __XSTRING(MODNAME)
14809 			    " module err:%d\n", err);
14810 			return (err);
14811 		}
14812 		tcp_lro_reg_mbufq();
14813 		bbr_mod_inited = true;
14814 		printf(__XSTRING(MODNAME) " is now available\n");
14815 		break;
14816 	case MOD_QUIESCE:
14817 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14818 		break;
14819 	case MOD_UNLOAD:
14820 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14821 		if (err == EBUSY)
14822 			break;
14823 		if (bbr_mod_inited) {
14824 			uma_zdestroy(bbr_zone);
14825 			uma_zdestroy(bbr_pcb_zone);
14826 			sysctl_ctx_free(&bbr_sysctl_ctx);
14827 			bbr_counter_destroy();
14828 			printf(__XSTRING(MODNAME)
14829 			    " is now no longer available\n");
14830 			bbr_mod_inited = false;
14831 		}
14832 		tcp_lro_dereg_mbufq();
14833 		err = 0;
14834 		break;
14835 	default:
14836 		return (EOPNOTSUPP);
14837 	}
14838 	return (err);
14839 }
14840 
14841 static moduledata_t tcp_bbr = {
14842 	.name = __XSTRING(MODNAME),
14843 	    .evhand = tcp_addbbr,
14844 	    .priv = 0
14845 };
14846 
14847 MODULE_VERSION(MODNAME, 1);
14848 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14849 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14850