xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision 9768746b)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_ratelimit.h"
40 #include <sys/param.h>
41 #include <sys/arb.h>
42 #include <sys/module.h>
43 #include <sys/kernel.h>
44 #include <sys/libkern.h>
45 #ifdef TCP_HHOOK
46 #include <sys/hhook.h>
47 #endif
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/proc.h>
51 #include <sys/socket.h>
52 #include <sys/socketvar.h>
53 #include <sys/sysctl.h>
54 #include <sys/systm.h>
55 #ifdef STATS
56 #include <sys/qmath.h>
57 #include <sys/tree.h>
58 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
59 #endif
60 #include <sys/refcount.h>
61 #include <sys/queue.h>
62 #include <sys/eventhandler.h>
63 #include <sys/smp.h>
64 #include <sys/kthread.h>
65 #include <sys/lock.h>
66 #include <sys/mutex.h>
67 #include <sys/tim_filter.h>
68 #include <sys/time.h>
69 #include <sys/protosw.h>
70 #include <vm/uma.h>
71 #include <sys/kern_prefetch.h>
72 
73 #include <net/route.h>
74 #include <net/route/nhop.h>
75 #include <net/vnet.h>
76 
77 #define TCPSTATES		/* for logging */
78 
79 #include <netinet/in.h>
80 #include <netinet/in_kdtrace.h>
81 #include <netinet/in_pcb.h>
82 #include <netinet/ip.h>
83 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
84 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
85 #include <netinet/ip_var.h>
86 #include <netinet/ip6.h>
87 #include <netinet6/in6_pcb.h>
88 #include <netinet6/ip6_var.h>
89 #define	TCPOUTFLAGS
90 #include <netinet/tcp.h>
91 #include <netinet/tcp_fsm.h>
92 #include <netinet/tcp_seq.h>
93 #include <netinet/tcp_timer.h>
94 #include <netinet/tcp_var.h>
95 #include <netinet/tcpip.h>
96 #include <netinet/tcp_hpts.h>
97 #include <netinet/cc/cc.h>
98 #include <netinet/tcp_log_buf.h>
99 #include <netinet/tcp_ratelimit.h>
100 #include <netinet/tcp_lro.h>
101 #ifdef TCP_OFFLOAD
102 #include <netinet/tcp_offload.h>
103 #endif
104 #ifdef INET6
105 #include <netinet6/tcp6_var.h>
106 #endif
107 #include <netinet/tcp_fastopen.h>
108 
109 #include <netipsec/ipsec_support.h>
110 #include <net/if.h>
111 #include <net/if_var.h>
112 #include <net/ethernet.h>
113 
114 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
115 #include <netipsec/ipsec.h>
116 #include <netipsec/ipsec6.h>
117 #endif				/* IPSEC */
118 
119 #include <netinet/udp.h>
120 #include <netinet/udp_var.h>
121 #include <machine/in_cksum.h>
122 
123 #ifdef MAC
124 #include <security/mac/mac_framework.h>
125 #endif
126 
127 #include "sack_filter.h"
128 #include "tcp_bbr.h"
129 #include "rack_bbr_common.h"
130 uma_zone_t bbr_zone;
131 uma_zone_t bbr_pcb_zone;
132 
133 struct sysctl_ctx_list bbr_sysctl_ctx;
134 struct sysctl_oid *bbr_sysctl_root;
135 
136 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
137 	(tv) = (value); \
138 	if ((u_long)(tv) < (u_long)(tvmin)) \
139 		(tv) = (tvmin); \
140 	if ((u_long)(tv) > (u_long)(tvmax)) \
141 		(tv) = (tvmax); \
142 } while(0)
143 
144 /*#define BBR_INVARIANT 1*/
145 
146 /*
147  * initial window
148  */
149 static uint32_t bbr_def_init_win = 10;
150 static int32_t bbr_persist_min = 250000;	/* 250ms */
151 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
152 static int32_t bbr_cwnd_may_shrink = 0;
153 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
154 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
155 static int32_t bbr_hardware_pacing_limit = 8000;
156 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
157 static int32_t bbr_no_retran = 0;
158 
159 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
160 static int32_t bbr_max_net_error_cnt = 10;
161 /* Should the following be dynamic too -- loss wise */
162 static int32_t bbr_rtt_gain_thresh = 0;
163 /* Measurement controls */
164 static int32_t bbr_use_google_algo = 1;
165 static int32_t bbr_ts_limiting = 1;
166 static int32_t bbr_ts_can_raise = 0;
167 static int32_t bbr_do_red = 600;
168 static int32_t bbr_red_scale = 20000;
169 static int32_t bbr_red_mul = 1;
170 static int32_t bbr_red_div = 2;
171 static int32_t bbr_red_growth_restrict = 1;
172 static int32_t  bbr_target_is_bbunit = 0;
173 static int32_t bbr_drop_limit = 0;
174 /*
175  * How much gain do we need to see to
176  * stay in startup?
177  */
178 static int32_t bbr_marks_rxt_sack_passed = 0;
179 static int32_t bbr_start_exit = 25;
180 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
181 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
182 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
183 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
184 					 * if we go back ever to where the pacer
185 					 * has priority over timers.
186 					 */
187 static int32_t bbr_policer_call_from_rack_to = 0;
188 static int32_t bbr_policer_detection_enabled = 1;
189 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
190 						 * measurements before we are
191 						 * "good" note that 2 == 1.
192 						 * This is because we use a >
193 						 * comparison. This means if
194 						 * min_measure was 0, it takes
195 						 * num-measures > min(0) and
196 						 * you get 1 measurement and
197 						 * you are good. Set to 1, you
198 						 * have to have two
199 						 * measurements (this is done
200 						 * to prevent it from being ok
201 						 * to have no measurements). */
202 static int32_t bbr_no_pacing_until = 4;
203 
204 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
205 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
206 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
207 
208 static int32_t bbr_target_cwnd_mult_limit = 8;
209 /*
210  * bbr_cwnd_min_val is the number of
211  * segments we hold to in the RTT probe
212  * state typically 4.
213  */
214 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
215 
216 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
217 
218 static int32_t bbr_gain_to_target = 1;
219 static int32_t bbr_gain_gets_extra_too = 1;
220 /*
221  * bbr_high_gain is the 2/ln(2) value we need
222  * to double the sending rate in startup. This
223  * is used for both cwnd and hptsi gain's.
224  */
225 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
226 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
227 static int32_t bbr_use_lower_gain_in_startup = 1;
228 
229 /* thresholds for reduction on drain in sub-states/drain */
230 static int32_t bbr_drain_rtt = BBR_SRTT;
231 static int32_t bbr_drain_floor = 88;
232 static int32_t google_allow_early_out = 1;
233 static int32_t google_consider_lost = 1;
234 static int32_t bbr_drain_drop_mul = 4;
235 static int32_t bbr_drain_drop_div = 5;
236 static int32_t bbr_rand_ot = 50;
237 static int32_t bbr_can_force_probertt = 0;
238 static int32_t bbr_can_adjust_probertt = 1;
239 static int32_t bbr_probertt_sets_rtt = 0;
240 static int32_t bbr_can_use_ts_for_rtt = 1;
241 static int32_t bbr_is_ratio = 0;
242 static int32_t bbr_sub_drain_app_limit = 1;
243 static int32_t bbr_prtt_slam_cwnd = 1;
244 static int32_t bbr_sub_drain_slam_cwnd = 1;
245 static int32_t bbr_slam_cwnd_in_main_drain = 1;
246 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
247 					 * hold */
248 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
249 /*
250  * bbr_drain_gain is the reverse of the high_gain
251  * designed to drain back out the standing queue
252  * that is formed in startup by causing a larger
253  * hptsi gain and thus drainging the packets
254  * in flight.
255  */
256 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
257 static int32_t bbr_rttprobe_gain = 192;
258 
259 /*
260  * The cwnd_gain is the default cwnd gain applied when
261  * calculating a target cwnd. Note that the cwnd is
262  * a secondary factor in the way BBR works (see the
263  * paper and think about it, it will take some time).
264  * Basically the hptsi_gain spreads the packets out
265  * so you never get more than BDP to the peer even
266  * if the cwnd is high. In our implemenation that
267  * means in non-recovery/retransmission scenarios
268  * cwnd will never be reached by the flight-size.
269  */
270 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
271 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
272 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
273 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
274 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
275 static int32_t bbr_ignore_data_after_close = 1;
276 static int16_t bbr_hptsi_gain[] = {
277 	(BBR_UNIT *5 / 4),
278 	(BBR_UNIT * 3 / 4),
279 	BBR_UNIT,
280 	BBR_UNIT,
281 	BBR_UNIT,
282 	BBR_UNIT,
283 	BBR_UNIT,
284 	BBR_UNIT
285 };
286 int32_t bbr_use_rack_resend_cheat = 1;
287 int32_t bbr_sends_full_iwnd = 1;
288 
289 #define BBR_HPTSI_GAIN_MAX 8
290 /*
291  * The BBR module incorporates a number of
292  * TCP ideas that have been put out into the IETF
293  * over the last few years:
294  * - Yuchung Cheng's RACK TCP (for which its named) that
295  *    will stop us using the number of dup acks and instead
296  *    use time as the gage of when we retransmit.
297  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
298  *    of Dukkipati et.al.
299  * - Van Jacobson's et.al BBR.
300  *
301  * RACK depends on SACK, so if an endpoint arrives that
302  * cannot do SACK the state machine below will shuttle the
303  * connection back to using the "default" TCP stack that is
304  * in FreeBSD.
305  *
306  * To implement BBR and RACK the original TCP stack was first decomposed
307  * into a functional state machine with individual states
308  * for each of the possible TCP connection states. The do_segment
309  * functions role in life is to mandate the connection supports SACK
310  * initially and then assure that the RACK state matches the conenction
311  * state before calling the states do_segment function. Data processing
312  * of inbound segments also now happens in the hpts_do_segment in general
313  * with only one exception. This is so we can keep the connection on
314  * a single CPU.
315  *
316  * Each state is simplified due to the fact that the original do_segment
317  * has been decomposed and we *know* what state we are in (no
318  * switches on the state) and all tests for SACK are gone. This
319  * greatly simplifies what each state does.
320  *
321  * TCP output is also over-written with a new version since it
322  * must maintain the new rack scoreboard and has had hptsi
323  * integrated as a requirment. Still todo is to eliminate the
324  * use of the callout_() system and use the hpts for all
325  * timers as well.
326  */
327 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
328 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
329 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
330 						 * free list */
331 static int32_t bbr_tlp_thresh = 1;
332 static int32_t bbr_reorder_thresh = 2;
333 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
334 						 * 60,000,000 - 60 seconds */
335 static int32_t bbr_pkt_delay = 1000;
336 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
337 static int32_t bbr_incr_timers = 1;
338 
339 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
340 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
341 static int32_t bbr_exit_startup_at_loss = 1;
342 
343 /*
344  * bbr_lt_bw_ratio is 1/8th
345  * bbr_lt_bw_diff is  < 4 Kbit/sec
346  */
347 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
348 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
349 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
350 						 * the lt_bw for */
351 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
352 						 * lt_bw */
353 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
354 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
355 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
356 
357 static int32_t bbr_verbose_logging = 0;
358 /*
359  * Currently regular tcp has a rto_min of 30ms
360  * the backoff goes 12 times so that ends up
361  * being a total of 122.850 seconds before a
362  * connection is killed.
363  */
364 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
365 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
366 
367 /****************************************************/
368 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
369 /****************************************************/
370 /* What amount is our formula using to get TSO size */
371 static int32_t bbr_hptsi_per_second = 1000;
372 
373 /*
374  * For hptsi under bbr_cross_over connections what is delay
375  * target 7ms (in usec) combined with a seg_max of 2
376  * gets us close to identical google behavior in
377  * TSO size selection (possibly more 1MSS sends).
378  */
379 static int32_t bbr_hptsi_segments_delay_tar = 7000;
380 
381 /* Does pacing delay include overhead's in its time calculations? */
382 static int32_t bbr_include_enet_oh = 0;
383 static int32_t bbr_include_ip_oh = 1;
384 static int32_t bbr_include_tcp_oh = 1;
385 static int32_t bbr_google_discount = 10;
386 
387 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
388 static int32_t bbr_state_is_pkt_epoch = 0;
389 static int32_t bbr_state_drain_2_tar = 1;
390 /* What is the max the 0 - bbr_cross_over MBPS TSO target
391  * can reach using our delay target. Note that this
392  * value becomes the floor for the cross over
393  * algorithm.
394  */
395 static int32_t bbr_hptsi_segments_max = 2;
396 static int32_t bbr_hptsi_segments_floor = 1;
397 static int32_t bbr_hptsi_utter_max = 0;
398 
399 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
400 static int32_t bbr_hptsi_bytes_min = 1460;
401 static int32_t bbr_all_get_min = 0;
402 
403 /* Cross over point from algo-a to algo-b */
404 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
405 
406 /* Do we deal with our restart state? */
407 static int32_t bbr_uses_idle_restart = 0;
408 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
409 
410 /* Do we allow hardware pacing? */
411 static int32_t bbr_allow_hdwr_pacing = 0;
412 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
413 static int32_t bbr_hdwr_pace_floor = 1;
414 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
415 
416 /****************************************************/
417 static int32_t bbr_resends_use_tso = 0;
418 static int32_t bbr_tlp_max_resend = 2;
419 static int32_t bbr_sack_block_limit = 128;
420 
421 #define  BBR_MAX_STAT 19
422 counter_u64_t bbr_state_time[BBR_MAX_STAT];
423 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
424 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
425 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
426 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
427 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
428 counter_u64_t bbr_flows_whdwr_pacing;
429 counter_u64_t bbr_flows_nohdwr_pacing;
430 
431 counter_u64_t bbr_nohdwr_pacing_enobuf;
432 counter_u64_t bbr_hdwr_pacing_enobuf;
433 
434 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
435 
436 /*
437  * Static defintions we need for forward declarations.
438  */
439 static uint32_t
440 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
441 		      uint32_t useconds_time, uint64_t bw);
442 static uint32_t
443 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
444 static void
445 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
446 static void
447 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
448 static void
449 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
450 		    int dolog);
451 static uint32_t
452 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
453 static void
454 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
455 		 int32_t pkt_epoch, uint32_t losses);
456 static uint32_t
457 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts,
458 		     struct bbr_sendmap *rsm);
459 static uint32_t
460 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
461 static uint32_t
462 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
463 		    struct bbr_sendmap *rsm, uint32_t srtt, uint32_t cts);
464 static void
465 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
466 		 int32_t line);
467 static void
468 bbr_set_state_target(struct tcp_bbr *bbr, int line);
469 static void
470 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
471 static void
472 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick,
473 		       int event, int line);
474 static void
475 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
476 static void
477 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
478 static void
479 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
480 		    uint32_t rtt, uint32_t line, uint8_t is_start,
481 		    uint16_t set);
482 static struct bbr_sendmap *
483 bbr_find_lowest_rsm(struct tcp_bbr *bbr);
484 static __inline uint32_t
485 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
486 static void
487 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot,
488 		 uint8_t which);
489 static void
490 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts,
491 		  uint32_t time_since_sent, uint32_t srtt,
492 		  uint32_t thresh, uint32_t to);
493 static void
494 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
495 static void
496 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
497 		    uint32_t del_by, uint32_t cts, uint32_t sloton,
498 		    uint32_t prev_delay);
499 static void
500 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
501 		  int32_t line);
502 static void
503 bbr_stop_all_timers(struct tcpcb *tp);
504 static void
505 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
506 static void
507 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
508 static void
509 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
510 static void
511 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
512 			  uint32_t cts, uint32_t usecs, uint64_t bw,
513 			  uint32_t override, int mod);
514 static int
515 bbr_ctloutput(struct inpcb *inp, struct sockopt *sopt);
516 
517 static inline uint8_t
518 bbr_state_val(struct tcp_bbr *bbr)
519 {
520 	return(bbr->rc_bbr_substate);
521 }
522 
523 static inline uint32_t
524 get_min_cwnd(struct tcp_bbr *bbr)
525 {
526 	int mss;
527 
528 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
529 		  bbr->r_ctl.rc_pace_max_segs);
530 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
531 		return (bbr_cwnd_min_val_hs * mss);
532 	else
533 		return (bbr_cwnd_min_val * mss);
534 }
535 
536 static uint32_t
537 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
538 {
539 	uint64_t srtt, var;
540 	uint64_t ret_val;
541 
542 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
543 	if (tp->t_srtt == 0) {
544 		srtt = (uint64_t)BBR_INITIAL_RTO;
545 		var = 0;
546 	} else {
547 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
548 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
549 	}
550 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
551 	    bbr_persist_min, bbr_persist_max);
552 	return ((uint32_t)ret_val);
553 }
554 
555 static uint32_t
556 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
557 {
558 	/*
559 	 * Start the FR timer, we do this based on getting the first one in
560 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
561 	 * events we need to stop the running timer (if its running) before
562 	 * starting the new one.
563 	 */
564 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
565 	int32_t idx;
566 	int32_t is_tlp_timer = 0;
567 	struct bbr_sendmap *rsm;
568 
569 	if (bbr->rc_all_timers_stopped) {
570 		/* All timers have been stopped none are to run */
571 		return (0);
572 	}
573 	if (bbr->rc_in_persist) {
574 		/* We can't start any timer in persists */
575 		return (bbr_get_persists_timer_val(tp, bbr));
576 	}
577 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
578 	if ((rsm == NULL) ||
579 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
580 	    (tp->t_state < TCPS_ESTABLISHED)) {
581 		/* Nothing on the send map */
582 activate_rxt:
583 		if (SEQ_LT(tp->snd_una, tp->snd_max) ||
584 		    sbavail(&tptosocket(tp)->so_snd)) {
585 			uint64_t tov;
586 
587 			time_since_sent = 0;
588 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
589 			if (rsm) {
590 				idx = rsm->r_rtr_cnt - 1;
591 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
592 					tstmp_touse = rsm->r_tim_lastsent[idx];
593 				else
594 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
595 				if (TSTMP_GT(tstmp_touse, cts))
596 				    time_since_sent = cts - tstmp_touse;
597 			}
598 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
599 			if (tp->t_srtt == 0)
600 				tov = BBR_INITIAL_RTO;
601 			else
602 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
603 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
604 			if (tp->t_rxtshift)
605 				tov *= tcp_backoff[tp->t_rxtshift];
606 			if (tov > time_since_sent)
607 				tov -= time_since_sent;
608 			else
609 				tov = bbr->r_ctl.rc_min_to;
610 			TCPT_RANGESET_NOSLOP(to, tov,
611 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
612 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
613 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
614 			return (to);
615 		}
616 		return (0);
617 	}
618 	if (rsm->r_flags & BBR_ACKED) {
619 		rsm = bbr_find_lowest_rsm(bbr);
620 		if (rsm == NULL) {
621 			/* No lowest? */
622 			goto activate_rxt;
623 		}
624 	}
625 	/* Convert from ms to usecs */
626 	if (rsm->r_flags & BBR_SACK_PASSED) {
627 		if ((tp->t_flags & TF_SENTFIN) &&
628 		    ((tp->snd_max - tp->snd_una) == 1) &&
629 		    (rsm->r_flags & BBR_HAS_FIN)) {
630 			/*
631 			 * We don't start a bbr rack timer if all we have is
632 			 * a FIN outstanding.
633 			 */
634 			goto activate_rxt;
635 		}
636 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
637 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
638 		idx = rsm->r_rtr_cnt - 1;
639 		exp = rsm->r_tim_lastsent[idx] + thresh;
640 		if (SEQ_GEQ(exp, cts)) {
641 			to = exp - cts;
642 			if (to < bbr->r_ctl.rc_min_to) {
643 				to = bbr->r_ctl.rc_min_to;
644 			}
645 		} else {
646 			to = bbr->r_ctl.rc_min_to;
647 		}
648 	} else {
649 		/* Ok we need to do a TLP not RACK */
650 		if (bbr->rc_tlp_in_progress != 0) {
651 			/*
652 			 * The previous send was a TLP.
653 			 */
654 			goto activate_rxt;
655 		}
656 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
657 		if (rsm == NULL) {
658 			/* We found no rsm to TLP with. */
659 			goto activate_rxt;
660 		}
661 		if (rsm->r_flags & BBR_HAS_FIN) {
662 			/* If its a FIN we don't do TLP */
663 			rsm = NULL;
664 			goto activate_rxt;
665 		}
666 		time_since_sent = 0;
667 		idx = rsm->r_rtr_cnt - 1;
668 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
669 			tstmp_touse = rsm->r_tim_lastsent[idx];
670 		else
671 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
672 		if (TSTMP_GT(tstmp_touse, cts))
673 		    time_since_sent = cts - tstmp_touse;
674 		is_tlp_timer = 1;
675 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
676 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
677 		if (thresh > time_since_sent)
678 			to = thresh - time_since_sent;
679 		else
680 			to = bbr->r_ctl.rc_min_to;
681 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
682 			/*
683 			 * If the TLP time works out to larger than the max
684 			 * RTO lets not do TLP.. just RTO.
685 			 */
686 			goto activate_rxt;
687 		}
688 		if ((bbr->rc_tlp_rtx_out == 1) &&
689 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
690 			/*
691 			 * Second retransmit of the same TLP
692 			 * lets not.
693 			 */
694 			bbr->rc_tlp_rtx_out = 0;
695 			goto activate_rxt;
696 		}
697 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
698 			/*
699 			 * The tail is no longer the last one I did a probe
700 			 * on
701 			 */
702 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
703 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
704 		}
705 	}
706 	if (is_tlp_timer == 0) {
707 		BBR_STAT_INC(bbr_to_arm_rack);
708 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
709 	} else {
710 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
711 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
712 			/*
713 			 * We have exceeded how many times we can retran the
714 			 * current TLP timer, switch to the RTO timer.
715 			 */
716 			goto activate_rxt;
717 		} else {
718 			BBR_STAT_INC(bbr_to_arm_tlp);
719 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
720 		}
721 	}
722 	return (to);
723 }
724 
725 static inline int32_t
726 bbr_minseg(struct tcp_bbr *bbr)
727 {
728 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
729 }
730 
731 static void
732 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
733 {
734 	struct inpcb *inp = tptoinpcb(tp);
735 	struct hpts_diag diag;
736 	uint32_t delayed_ack = 0;
737 	uint32_t left = 0;
738 	uint32_t hpts_timeout;
739 	uint8_t stopped;
740 	int32_t delay_calc = 0;
741 	uint32_t prev_delay = 0;
742 
743 	if (tcp_in_hpts(inp)) {
744 		/* A previous call is already set up */
745 		return;
746 	}
747 	if ((tp->t_state == TCPS_CLOSED) ||
748 	    (tp->t_state == TCPS_LISTEN)) {
749 		return;
750 	}
751 	stopped = bbr->rc_tmr_stopped;
752 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
753 		left = bbr->r_ctl.rc_timer_exp - cts;
754 	}
755 	bbr->r_ctl.rc_hpts_flags = 0;
756 	bbr->r_ctl.rc_timer_exp = 0;
757 	prev_delay = bbr->r_ctl.rc_last_delay_val;
758 	if (bbr->r_ctl.rc_last_delay_val &&
759 	    (slot == 0)) {
760 		/*
761 		 * If a previous pacer delay was in place we
762 		 * are not coming from the output side (where
763 		 * we calculate a delay, more likely a timer).
764 		 */
765 		slot = bbr->r_ctl.rc_last_delay_val;
766 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
767 			/* Compensate for time passed  */
768 			delay_calc = cts - bbr->rc_pacer_started;
769 			if (delay_calc <= slot)
770 				slot -= delay_calc;
771 		}
772 	}
773 	/* Do we have early to make up for by pushing out the pacing time? */
774 	if (bbr->r_agg_early_set) {
775 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
776 		slot += bbr->r_ctl.rc_agg_early;
777 		bbr->r_ctl.rc_agg_early = 0;
778 		bbr->r_agg_early_set = 0;
779 	}
780 	/* Are we running a total debt that needs to be compensated for? */
781 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
782 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
783 			/* We nuke the delay */
784 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
785 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
786 		} else {
787 			/* We nuke some of the delay, put in a minimal 100usecs  */
788 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
789 			bbr->r_ctl.rc_last_delay_val = slot = 100;
790 		}
791 	}
792 	bbr->r_ctl.rc_last_delay_val = slot;
793 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
794 	if (tp->t_flags & TF_DELACK) {
795 		if (bbr->rc_in_persist == 0) {
796 			delayed_ack = bbr_delack_time;
797 		} else {
798 			/*
799 			 * We are in persists and have
800 			 * gotten a new data element.
801 			 */
802 			if (hpts_timeout > bbr_delack_time) {
803 				/*
804 				 * Lets make the persists timer (which acks)
805 				 * be the smaller of hpts_timeout and bbr_delack_time.
806 				 */
807 				hpts_timeout = bbr_delack_time;
808 			}
809 		}
810 	}
811 	if (delayed_ack &&
812 	    ((hpts_timeout == 0) ||
813 	     (delayed_ack < hpts_timeout))) {
814 		/* We need a Delayed ack timer */
815 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
816 		hpts_timeout = delayed_ack;
817 	}
818 	if (slot) {
819 		/* Mark that we have a pacing timer up */
820 		BBR_STAT_INC(bbr_paced_segments);
821 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
822 	}
823 	/*
824 	 * If no timers are going to run and we will fall off thfe hptsi
825 	 * wheel, we resort to a keep-alive timer if its configured.
826 	 */
827 	if ((hpts_timeout == 0) &&
828 	    (slot == 0)) {
829 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
830 		    (tp->t_state <= TCPS_CLOSING)) {
831 			/*
832 			 * Ok we have no timer (persists, rack, tlp, rxt  or
833 			 * del-ack), we don't have segments being paced. So
834 			 * all that is left is the keepalive timer.
835 			 */
836 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
837 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
838 			} else {
839 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
840 			}
841 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
842 		}
843 	}
844 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
845 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
846 		/*
847 		 * RACK, TLP, persists and RXT timers all are restartable
848 		 * based on actions input .. i.e we received a packet (ack
849 		 * or sack) and that changes things (rw, or snd_una etc).
850 		 * Thus we can restart them with a new value. For
851 		 * keep-alive, delayed_ack we keep track of what was left
852 		 * and restart the timer with a smaller value.
853 		 */
854 		if (left < hpts_timeout)
855 			hpts_timeout = left;
856 	}
857 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
858 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
859 		/*
860 		 * If configured to do so, and the timer is either
861 		 * the TLP or RXT timer, we need to increase the timeout
862 		 * by the pacing time. Consider the bottleneck at my
863 		 * machine as an example, we are sending something
864 		 * to start a TLP on. The last packet won't be emitted
865 		 * fully until the pacing time (the bottleneck will hold
866 		 * the data in place). Once the packet is emitted that
867 		 * is when we want to start waiting for the TLP. This
868 		 * is most evident with hardware pacing (where the nic
869 		 * is holding the packet(s) before emitting). But it
870 		 * can also show up in the network so we do it for all
871 		 * cases. Technically we would take off one packet from
872 		 * this extra delay but this is easier and being more
873 		 * conservative is probably better.
874 		 */
875 		hpts_timeout += slot;
876 	}
877 	if (hpts_timeout) {
878 		/*
879 		 * Hack alert for now we can't time-out over 2147 seconds (a
880 		 * bit more than 35min)
881 		 */
882 		if (hpts_timeout > 0x7ffffffe)
883 			hpts_timeout = 0x7ffffffe;
884 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
885 	} else
886 		bbr->r_ctl.rc_timer_exp = 0;
887 	if ((slot) &&
888 	    (bbr->rc_use_google ||
889 	     bbr->output_error_seen ||
890 	     (slot <= hpts_timeout))  ) {
891 		/*
892 		 * Tell LRO that it can queue packets while
893 		 * we pace.
894 		 */
895 		bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
896 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
897 		    (bbr->rc_cwnd_limited == 0)) {
898 			/*
899 			 * If we are not cwnd limited and we
900 			 * are running a rack timer we put on
901 			 * the do not disturbe even for sack.
902 			 */
903 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
904 		} else
905 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
906 		bbr->rc_pacer_started = cts;
907 
908 		(void)tcp_hpts_insert_diag(inp, HPTS_USEC_TO_SLOTS(slot),
909 					   __LINE__, &diag);
910 		bbr->rc_timer_first = 0;
911 		bbr->bbr_timer_src = frm;
912 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
913 		bbr_log_hpts_diag(bbr, cts, &diag);
914 	} else if (hpts_timeout) {
915 		(void)tcp_hpts_insert_diag(inp, HPTS_USEC_TO_SLOTS(hpts_timeout),
916 					   __LINE__, &diag);
917 		/*
918 		 * We add the flag here as well if the slot is set,
919 		 * since hpts will call in to clear the queue first before
920 		 * calling the output routine (which does our timers).
921 		 * We don't want to set the flag if its just a timer
922 		 * else the arrival of data might (that causes us
923 		 * to send more) might get delayed. Imagine being
924 		 * on a keep-alive timer and a request comes in for
925 		 * more data.
926 		 */
927 		if (slot)
928 			bbr->rc_pacer_started = cts;
929 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
930 		    (bbr->rc_cwnd_limited == 0)) {
931 			/*
932 			 * For a rack timer, don't wake us even
933 			 * if a sack arrives as long as we are
934 			 * not cwnd limited.
935 			 */
936 			bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
937 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
938 		} else {
939 			/* All other timers wake us up */
940 			bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
941 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
942 		}
943 		bbr->bbr_timer_src = frm;
944 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
945 		bbr_log_hpts_diag(bbr, cts, &diag);
946 		bbr->rc_timer_first = 1;
947 	}
948 	bbr->rc_tmr_stopped = 0;
949 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
950 }
951 
952 static void
953 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
954 {
955 	/*
956 	 * We received an ack, and then did not call send or were bounced
957 	 * out due to the hpts was running. Now a timer is up as well, is it
958 	 * the right timer?
959 	 */
960 	struct inpcb *inp;
961 	struct bbr_sendmap *rsm;
962 	uint32_t hpts_timeout;
963 	int tmr_up;
964 
965 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
966 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
967 		return;
968 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
969 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
970 	    (tmr_up == PACE_TMR_RXT)) {
971 		/* Should be an RXT */
972 		return;
973 	}
974 	inp = bbr->rc_inp;
975 	if (rsm == NULL) {
976 		/* Nothing outstanding? */
977 		if (tp->t_flags & TF_DELACK) {
978 			if (tmr_up == PACE_TMR_DELACK)
979 				/*
980 				 * We are supposed to have delayed ack up
981 				 * and we do
982 				 */
983 				return;
984 		} else if (sbavail(&inp->inp_socket->so_snd) &&
985 		    (tmr_up == PACE_TMR_RXT)) {
986 			/*
987 			 * if we hit enobufs then we would expect the
988 			 * possibility of nothing outstanding and the RXT up
989 			 * (and the hptsi timer).
990 			 */
991 			return;
992 		} else if (((V_tcp_always_keepalive ||
993 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
994 			    (tp->t_state <= TCPS_CLOSING)) &&
995 			    (tmr_up == PACE_TMR_KEEP) &&
996 		    (tp->snd_max == tp->snd_una)) {
997 			/* We should have keep alive up and we do */
998 			return;
999 		}
1000 	}
1001 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1002 		if ((tp->t_flags & TF_SENTFIN) &&
1003 		    ((tp->snd_max - tp->snd_una) == 1) &&
1004 		    (rsm->r_flags & BBR_HAS_FIN)) {
1005 			/* needs to be a RXT */
1006 			if (tmr_up == PACE_TMR_RXT)
1007 				return;
1008 			else
1009 				goto wrong_timer;
1010 		} else if (tmr_up == PACE_TMR_RACK)
1011 			return;
1012 		else
1013 			goto wrong_timer;
1014 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1015 		/* Rack timer has priority if we have data out */
1016 		return;
1017 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1018 		    ((tmr_up == PACE_TMR_TLP) ||
1019 	    (tmr_up == PACE_TMR_RXT))) {
1020 		/*
1021 		 * Either a TLP or RXT is fine if no sack-passed is in place
1022 		 * and data is outstanding.
1023 		 */
1024 		return;
1025 	} else if (tmr_up == PACE_TMR_DELACK) {
1026 		/*
1027 		 * If the delayed ack was going to go off before the
1028 		 * rtx/tlp/rack timer were going to expire, then that would
1029 		 * be the timer in control. Note we don't check the time
1030 		 * here trusting the code is correct.
1031 		 */
1032 		return;
1033 	}
1034 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1035 	    ((tmr_up == PACE_TMR_RXT) ||
1036 	     (tmr_up == PACE_TMR_TLP) ||
1037 	     (tmr_up == PACE_TMR_RACK))) {
1038 		/*
1039 		 * We have outstanding data and
1040 		 * we *do* have a RACK, TLP or RXT
1041 		 * timer running. We won't restart
1042 		 * anything here since thats probably ok we
1043 		 * will get called with some timer here shortly.
1044 		 */
1045 		return;
1046 	}
1047 	/*
1048 	 * Ok the timer originally started is not what we want now. We will
1049 	 * force the hpts to be stopped if any, and restart with the slot
1050 	 * set to what was in the saved slot.
1051 	 */
1052 wrong_timer:
1053 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1054 		if (tcp_in_hpts(inp))
1055 			tcp_hpts_remove(inp);
1056 		bbr_timer_cancel(bbr, __LINE__, cts);
1057 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1058 		    0);
1059 	} else {
1060 		/*
1061 		 * Output is hptsi so we just need to switch the type of
1062 		 * timer. We don't bother with keep-alive, since when we
1063 		 * jump through the output, it will start the keep-alive if
1064 		 * nothing is sent.
1065 		 *
1066 		 * We only need a delayed-ack added and or the hpts_timeout.
1067 		 */
1068 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1069 		if (tp->t_flags & TF_DELACK) {
1070 			if (hpts_timeout == 0) {
1071 				hpts_timeout = bbr_delack_time;
1072 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1073 			}
1074 			else if (hpts_timeout > bbr_delack_time) {
1075 				hpts_timeout = bbr_delack_time;
1076 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1077 			}
1078 		}
1079 		if (hpts_timeout) {
1080 			if (hpts_timeout > 0x7ffffffe)
1081 				hpts_timeout = 0x7ffffffe;
1082 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1083 		}
1084 	}
1085 }
1086 
1087 int32_t bbr_clear_lost = 0;
1088 
1089 /*
1090  * Considers the two time values now (cts) and earlier.
1091  * If cts is smaller than earlier, we could have
1092  * had a sequence wrap (our counter wraps every
1093  * 70 min or so) or it could be just clock skew
1094  * getting us two different time values. Clock skew
1095  * will show up within 10ms or so. So in such
1096  * a case (where cts is behind earlier time by
1097  * less than 10ms) we return 0. Otherwise we
1098  * return the true difference between them.
1099  */
1100 static inline uint32_t
1101 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1102 	/*
1103 	 * Given two timestamps, the current time stamp cts, and some other
1104 	 * time-stamp taken in theory earlier return the difference. The
1105 	 * trick is here sometimes locking will get the other timestamp
1106 	 * after the cts. If this occurs we need to return 0.
1107 	 */
1108 	if (TSTMP_GEQ(cts, earlier_time))
1109 		return (cts - earlier_time);
1110 	/*
1111 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1112 	 * If its more than 10ms difference then we had a time wrap. Else
1113 	 * its just the normal locking foo. I wonder if we should not go to
1114 	 * 64bit TS and get rid of this issue.
1115 	 */
1116 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1117 		return (0);
1118 	/*
1119 	 * Ok the time must have wrapped. So we need to answer a large
1120 	 * amount of time, which the normal subtraction should do.
1121 	 */
1122 	return (cts - earlier_time);
1123 }
1124 
1125 static int
1126 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1127 {
1128 	uint32_t stat;
1129 	int32_t error;
1130 
1131 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1132 	if (error || req->newptr == NULL)
1133 		return error;
1134 
1135 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1136 	if (error)
1137 		return (error);
1138 	if (stat == 1) {
1139 #ifdef BBR_INVARIANTS
1140 		printf("Clearing BBR lost counters\n");
1141 #endif
1142 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1143 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1144 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1145 	} else if (stat == 2) {
1146 #ifdef BBR_INVARIANTS
1147 		printf("Clearing BBR option counters\n");
1148 #endif
1149 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1150 	} else if (stat == 3) {
1151 #ifdef BBR_INVARIANTS
1152 		printf("Clearing BBR stats counters\n");
1153 #endif
1154 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1155 	} else if (stat == 4) {
1156 #ifdef BBR_INVARIANTS
1157 		printf("Clearing BBR out-size counters\n");
1158 #endif
1159 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1160 	}
1161 	bbr_clear_lost = 0;
1162 	return (0);
1163 }
1164 
1165 static void
1166 bbr_init_sysctls(void)
1167 {
1168 	struct sysctl_oid *bbr_probertt;
1169 	struct sysctl_oid *bbr_hptsi;
1170 	struct sysctl_oid *bbr_measure;
1171 	struct sysctl_oid *bbr_cwnd;
1172 	struct sysctl_oid *bbr_timeout;
1173 	struct sysctl_oid *bbr_states;
1174 	struct sysctl_oid *bbr_startup;
1175 	struct sysctl_oid *bbr_policer;
1176 
1177 	/* Probe rtt controls */
1178 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1179 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1180 	    OID_AUTO,
1181 	    "probertt",
1182 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1183 	    "");
1184 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1185 	    SYSCTL_CHILDREN(bbr_probertt),
1186 	    OID_AUTO, "gain", CTLFLAG_RW,
1187 	    &bbr_rttprobe_gain, 192,
1188 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1189 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1190 	    SYSCTL_CHILDREN(bbr_probertt),
1191 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1192 	    &bbr_rtt_probe_cwndtarg, 4,
1193 	    "How many mss's are outstanding during probe-rtt");
1194 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1195 	    SYSCTL_CHILDREN(bbr_probertt),
1196 	    OID_AUTO, "int", CTLFLAG_RW,
1197 	    &bbr_rtt_probe_limit, 4000000,
1198 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1199 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1200 	    SYSCTL_CHILDREN(bbr_probertt),
1201 	    OID_AUTO, "mintime", CTLFLAG_RW,
1202 	    &bbr_rtt_probe_time, 200000,
1203 	    "How many microseconds in probe-rtt");
1204 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1205 	    SYSCTL_CHILDREN(bbr_probertt),
1206 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1207 	    &bbr_filter_len_sec, 6,
1208 	    "How long in seconds does the rttProp filter run?");
1209 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1210 	    SYSCTL_CHILDREN(bbr_probertt),
1211 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1212 	    &bbr_drain_rtt, BBR_SRTT,
1213 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1214 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1215 	    SYSCTL_CHILDREN(bbr_probertt),
1216 	    OID_AUTO, "can_force", CTLFLAG_RW,
1217 	    &bbr_can_force_probertt, 0,
1218 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1219 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1220 	    SYSCTL_CHILDREN(bbr_probertt),
1221 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1222 	    &bbr_probertt_sets_rtt, 0,
1223 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1224 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1225 	    SYSCTL_CHILDREN(bbr_probertt),
1226 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1227 	    &bbr_can_adjust_probertt, 1,
1228 	    "Can we dynamically adjust the probe-rtt limits and times?");
1229 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1230 	    SYSCTL_CHILDREN(bbr_probertt),
1231 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1232 	    &bbr_is_ratio, 0,
1233 	    "is the limit to filter a ratio?");
1234 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1235 	    SYSCTL_CHILDREN(bbr_probertt),
1236 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1237 	    &bbr_prtt_slam_cwnd, 0,
1238 	    "Should we set/recover cwnd?");
1239 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1240 	    SYSCTL_CHILDREN(bbr_probertt),
1241 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1242 	    &bbr_can_use_ts_for_rtt, 1,
1243 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1244 
1245 	/* Pacing controls */
1246 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1247 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1248 	    OID_AUTO,
1249 	    "pacing",
1250 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1251 	    "");
1252 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1253 	    SYSCTL_CHILDREN(bbr_hptsi),
1254 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1255 	    &bbr_allow_hdwr_pacing, 1,
1256 	    "Do we allow hardware pacing?");
1257 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1258 	    SYSCTL_CHILDREN(bbr_hptsi),
1259 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1260 	    &bbr_hardware_pacing_limit, 4000,
1261 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1262 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1263 	    SYSCTL_CHILDREN(bbr_hptsi),
1264 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1265 	    &bbr_hdwr_pace_adjust, 2,
1266 	    "Multiplier to calculated tso size?");
1267 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1268 	    SYSCTL_CHILDREN(bbr_hptsi),
1269 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1270 	    &bbr_hdwr_pace_floor, 1,
1271 	    "Do we invoke the hardware pacing floor?");
1272 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1273 	    SYSCTL_CHILDREN(bbr_hptsi),
1274 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1275 	    &bbr_hdwr_pacing_delay_cnt, 10,
1276 	    "How many packets must be sent after hdwr pacing is enabled");
1277 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1278 	    SYSCTL_CHILDREN(bbr_hptsi),
1279 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1280 	    &bbr_cross_over, 3000000,
1281 	    "What is the point where we cross over to linux like TSO size set");
1282 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1283 	    SYSCTL_CHILDREN(bbr_hptsi),
1284 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1285 	    &bbr_hptsi_segments_delay_tar, 7000,
1286 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1287 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1288 	    SYSCTL_CHILDREN(bbr_hptsi),
1289 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1290 	    &bbr_include_enet_oh, 0,
1291 	    "Do we include the ethernet overhead in calculating pacing delay?");
1292 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1293 	    SYSCTL_CHILDREN(bbr_hptsi),
1294 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1295 	    &bbr_include_ip_oh, 1,
1296 	    "Do we include the IP overhead in calculating pacing delay?");
1297 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1298 	    SYSCTL_CHILDREN(bbr_hptsi),
1299 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1300 	    &bbr_include_tcp_oh, 0,
1301 	    "Do we include the TCP overhead in calculating pacing delay?");
1302 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1303 	    SYSCTL_CHILDREN(bbr_hptsi),
1304 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1305 	    &bbr_google_discount, 10,
1306 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1307 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1308 	    SYSCTL_CHILDREN(bbr_hptsi),
1309 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1310 	    &bbr_all_get_min, 0,
1311 	    "If you are less than a MSS do you just get the min?");
1312 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1313 	    SYSCTL_CHILDREN(bbr_hptsi),
1314 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1315 	    &bbr_hptsi_bytes_min, 1460,
1316 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1317 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1318 	    SYSCTL_CHILDREN(bbr_hptsi),
1319 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1320 	    &bbr_hptsi_segments_max, 6,
1321 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1322 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1323 	    SYSCTL_CHILDREN(bbr_hptsi),
1324 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1325 	    &bbr_hptsi_segments_floor, 1,
1326 	    "Minimum TSO size we will fall too in segments");
1327 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1328 	    SYSCTL_CHILDREN(bbr_hptsi),
1329 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1330 	    &bbr_hptsi_utter_max, 0,
1331 	    "The absolute maximum that any pacing (outside of hardware) can be");
1332 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1333 	    SYSCTL_CHILDREN(bbr_hptsi),
1334 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1335 	    &bbr_hptsi_per_second, 100,
1336 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1337 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1338 	    SYSCTL_CHILDREN(bbr_hptsi),
1339 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1340 	    &bbr_hptsi_max_mul, 1,
1341 	    "The multiplier for pace len max");
1342 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1343 	    SYSCTL_CHILDREN(bbr_hptsi),
1344 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1345 	    &bbr_hptsi_max_div, 2,
1346 	    "The divisor for pace len max");
1347 	/* Measurement controls */
1348 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1349 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1350 	    OID_AUTO,
1351 	    "measure",
1352 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1353 	    "Measurement controls");
1354 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1355 	    SYSCTL_CHILDREN(bbr_measure),
1356 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1357 	    &bbr_initial_bw_bps, 62500,
1358 	    "Minimum initial b/w in bytes per second");
1359 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1360 	    SYSCTL_CHILDREN(bbr_measure),
1361 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1362 	    &bbr_sack_not_required, 0,
1363 	    "Do we allow bbr to run on connections not supporting SACK?");
1364 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1365 	    SYSCTL_CHILDREN(bbr_measure),
1366 	    OID_AUTO, "use_google", CTLFLAG_RW,
1367 	    &bbr_use_google_algo, 0,
1368 	    "Use has close to google V1.0 has possible?");
1369 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1370 	    SYSCTL_CHILDREN(bbr_measure),
1371 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1372 	    &bbr_ts_limiting, 1,
1373 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1374 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1375 	    SYSCTL_CHILDREN(bbr_measure),
1376 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1377 	    &bbr_ts_can_raise, 0,
1378 	    "Can we raise the b/w via timestamp b/w calculation?");
1379 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1380 	    SYSCTL_CHILDREN(bbr_measure),
1381 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1382 	    &bbr_min_usec_delta, 20000,
1383 	    "How long in usec between ts of our sends in ts validation code?");
1384 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1385 	    SYSCTL_CHILDREN(bbr_measure),
1386 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1387 	    &bbr_min_peer_delta, 20,
1388 	    "What min numerical value should be between the peer deltas?");
1389 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1390 	    SYSCTL_CHILDREN(bbr_measure),
1391 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1392 	    &bbr_delta_percent, 150,
1393 	    "What percentage (150 = 15.0) do we allow variance for?");
1394 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1395 	    SYSCTL_CHILDREN(bbr_measure),
1396 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1397 	    &bbr_min_measurements_req, 1,
1398 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1399 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1400 	    SYSCTL_CHILDREN(bbr_measure),
1401 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1402 	    &bbr_no_pacing_until, 4,
1403 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1404 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1405 	    SYSCTL_CHILDREN(bbr_measure),
1406 	    OID_AUTO, "quanta", CTLFLAG_RW,
1407 	    &bbr_quanta, 2,
1408 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1409 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1410 	    SYSCTL_CHILDREN(bbr_measure),
1411 	    OID_AUTO, "noretran", CTLFLAG_RW,
1412 	    &bbr_no_retran, 0,
1413 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1414 	/* State controls */
1415 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1416 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1417 	    OID_AUTO,
1418 	    "states",
1419 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1420 	    "State controls");
1421 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1422 	    SYSCTL_CHILDREN(bbr_states),
1423 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1424 	    &bbr_uses_idle_restart, 0,
1425 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1426 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1427 	    SYSCTL_CHILDREN(bbr_states),
1428 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1429 	    &bbr_idle_restart_threshold, 100000,
1430 	    "How long must we be idle before we restart??");
1431 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1432 	    SYSCTL_CHILDREN(bbr_states),
1433 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1434 	    &bbr_state_is_pkt_epoch, 0,
1435 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1436 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1437 	    SYSCTL_CHILDREN(bbr_states),
1438 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1439 	    &bbr_rtt_gain_thresh, 0,
1440 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1441 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1442 	    SYSCTL_CHILDREN(bbr_states),
1443 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1444 	    &bbr_drain_floor, 88,
1445 	    "What is the lowest we can drain (pg) too?");
1446 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1447 	    SYSCTL_CHILDREN(bbr_states),
1448 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1449 	    &bbr_state_drain_2_tar, 1,
1450 	    "Do we drain to target in drain substate?");
1451 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1452 	    SYSCTL_CHILDREN(bbr_states),
1453 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1454 	    &bbr_gain_to_target, 1,
1455 	    "Does probe bw gain to target??");
1456 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1457 	    SYSCTL_CHILDREN(bbr_states),
1458 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1459 	    &bbr_gain_gets_extra_too, 1,
1460 	    "Does probe bw gain get the extra time too?");
1461 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1462 	    SYSCTL_CHILDREN(bbr_states),
1463 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1464 	    &bbr_drain_drop_div, 5,
1465 	    "Long drain drop divider?");
1466 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1467 	    SYSCTL_CHILDREN(bbr_states),
1468 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1469 	    &bbr_drain_drop_mul, 4,
1470 	    "Long drain drop multiplier?");
1471 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1472 	    SYSCTL_CHILDREN(bbr_states),
1473 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1474 	    &bbr_rand_ot, 50,
1475 	    "Random discount of the ot?");
1476 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1477 	    SYSCTL_CHILDREN(bbr_states),
1478 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1479 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1480 	    "How many packet-epochs does the b/w delivery rate last?");
1481 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1482 	    SYSCTL_CHILDREN(bbr_states),
1483 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1484 	    &bbr_sub_drain_app_limit, 0,
1485 	    "Does our sub-state drain invoke app limited if its long?");
1486 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1487 	    SYSCTL_CHILDREN(bbr_states),
1488 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1489 	    &bbr_sub_drain_slam_cwnd, 0,
1490 	    "Should we set/recover cwnd for sub-state drain?");
1491 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1492 	    SYSCTL_CHILDREN(bbr_states),
1493 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1494 	    &bbr_slam_cwnd_in_main_drain, 0,
1495 	    "Should we set/recover cwnd for main-state drain?");
1496 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1497 	    SYSCTL_CHILDREN(bbr_states),
1498 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1499 	    &google_allow_early_out, 1,
1500 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1501 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1502 	    SYSCTL_CHILDREN(bbr_states),
1503 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1504 	    &google_consider_lost, 1,
1505 	    "Should we have losses exit gain of probebw in google mode??");
1506 	/* Startup controls */
1507 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1508 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1509 	    OID_AUTO,
1510 	    "startup",
1511 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1512 	    "Startup controls");
1513 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1514 	    SYSCTL_CHILDREN(bbr_startup),
1515 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1516 	    &bbr_sends_full_iwnd, 1,
1517 	    "Do we not pace but burst out initial windows has our TSO size?");
1518 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1519 	    SYSCTL_CHILDREN(bbr_startup),
1520 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1521 	    &bbr_startup_loss_thresh, 2000,
1522 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1523 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1524 	    SYSCTL_CHILDREN(bbr_startup),
1525 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1526 	    &bbr_use_lower_gain_in_startup, 1,
1527 	    "Should we use a lower hptsi gain if we see loss in startup?");
1528 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1529 	    SYSCTL_CHILDREN(bbr_startup),
1530 	    OID_AUTO, "gain", CTLFLAG_RW,
1531 	    &bbr_start_exit, 25,
1532 	    "What gain percent do we need to see to stay in startup??");
1533 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1534 	    SYSCTL_CHILDREN(bbr_startup),
1535 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1536 	    &bbr_low_start_exit, 15,
1537 	    "What gain percent do we need to see to stay in the lower gain startup??");
1538 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1539 	    SYSCTL_CHILDREN(bbr_startup),
1540 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1541 	    &bbr_exit_startup_at_loss, 1,
1542 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1543 	/* CWND controls */
1544 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1545 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1546 	    OID_AUTO,
1547 	    "cwnd",
1548 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1549 	    "Cwnd controls");
1550 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1551 	    SYSCTL_CHILDREN(bbr_cwnd),
1552 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1553 	    &bbr_cwndtarget_rtt_touse, 0,
1554 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1555 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1556 	    SYSCTL_CHILDREN(bbr_cwnd),
1557 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1558 	    &bbr_cwnd_may_shrink, 0,
1559 	    "Can the cwnd shrink if it would grow to more than the target?");
1560 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1561 	    SYSCTL_CHILDREN(bbr_cwnd),
1562 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1563 	    &bbr_target_cwnd_mult_limit, 8,
1564 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1565 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1566 	    SYSCTL_CHILDREN(bbr_cwnd),
1567 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1568 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1569 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1570 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1571 	    SYSCTL_CHILDREN(bbr_cwnd),
1572 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1573 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1574 	    "What is the min cwnd (rttProp > 1ms)");
1575 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1576 	    SYSCTL_CHILDREN(bbr_cwnd),
1577 	    OID_AUTO, "initwin", CTLFLAG_RW,
1578 	    &bbr_def_init_win, 10,
1579 	    "What is the BBR initial window, if 0 use tcp version");
1580 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1581 	    SYSCTL_CHILDREN(bbr_cwnd),
1582 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1583 	    &bbr_do_red, 600,
1584 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1585 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1586 	    SYSCTL_CHILDREN(bbr_cwnd),
1587 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1588 	    &bbr_red_scale, 20000,
1589 	    "What RTT do we scale with?");
1590 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1591 	    SYSCTL_CHILDREN(bbr_cwnd),
1592 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1593 	    &bbr_red_growth_restrict, 1,
1594 	    "Do we restrict cwnd growth for whats in flight?");
1595 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1596 	    SYSCTL_CHILDREN(bbr_cwnd),
1597 	    OID_AUTO, "red_div", CTLFLAG_RW,
1598 	    &bbr_red_div, 2,
1599 	    "If we reduce whats the divisor?");
1600 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1601 	    SYSCTL_CHILDREN(bbr_cwnd),
1602 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1603 	    &bbr_red_mul, 1,
1604 	    "If we reduce whats the mulitiplier?");
1605 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1606 	    SYSCTL_CHILDREN(bbr_cwnd),
1607 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1608 	    &bbr_target_is_bbunit, 0,
1609 	    "Is the state target the pacing_gain or BBR_UNIT?");
1610 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1611 	    SYSCTL_CHILDREN(bbr_cwnd),
1612 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1613 	    &bbr_drop_limit, 0,
1614 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1615 
1616 	/* Timeout controls */
1617 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1618 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1619 	    OID_AUTO,
1620 	    "timeout",
1621 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1622 	    "Time out controls");
1623 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1624 	    SYSCTL_CHILDREN(bbr_timeout),
1625 	    OID_AUTO, "delack", CTLFLAG_RW,
1626 	    &bbr_delack_time, 100000,
1627 	    "BBR's delayed ack time");
1628 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1629 	    SYSCTL_CHILDREN(bbr_timeout),
1630 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1631 	    &bbr_tlp_type_to_use, 3,
1632 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1633 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1634 	    SYSCTL_CHILDREN(bbr_timeout),
1635 	    OID_AUTO, "persmin", CTLFLAG_RW,
1636 	    &bbr_persist_min, 250000,
1637 	    "What is the minimum time in microseconds between persists");
1638 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1639 	    SYSCTL_CHILDREN(bbr_timeout),
1640 	    OID_AUTO, "persmax", CTLFLAG_RW,
1641 	    &bbr_persist_max, 1000000,
1642 	    "What is the largest delay in microseconds between persists");
1643 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1644 	    SYSCTL_CHILDREN(bbr_timeout),
1645 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1646 	    &bbr_tlp_min, 10000,
1647 	    "TLP Min timeout in usecs");
1648 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1649 	    SYSCTL_CHILDREN(bbr_timeout),
1650 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1651 	    &bbr_delayed_ack_time, 200000,
1652 	    "TLP delayed ack compensation value");
1653 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1654 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1655 	    OID_AUTO, "minrto", CTLFLAG_RW,
1656 	    &bbr_rto_min_ms, 30,
1657 	    "Minimum RTO in ms");
1658 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1659 	    SYSCTL_CHILDREN(bbr_timeout),
1660 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1661 	    &bbr_rto_max_sec, 4,
1662 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1663 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1664 	    SYSCTL_CHILDREN(bbr_timeout),
1665 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1666 	    &bbr_tlp_max_resend, 2,
1667 	    "How many times does TLP retry a single segment or multiple with no ACK");
1668 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1669 	    SYSCTL_CHILDREN(bbr_timeout),
1670 	    OID_AUTO, "minto", CTLFLAG_RW,
1671 	    &bbr_min_to, 1000,
1672 	    "Minimum rack timeout in useconds");
1673 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1674 	    SYSCTL_CHILDREN(bbr_timeout),
1675 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1676 	    &bbr_pkt_delay, 1000,
1677 	    "Extra RACK time (in useconds) besides reordering thresh");
1678 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1679 	    SYSCTL_CHILDREN(bbr_timeout),
1680 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1681 	    &bbr_incr_timers, 1,
1682 	    "Increase the RXT/TLP timer by the pacing time used?");
1683 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1684 	    SYSCTL_CHILDREN(bbr_timeout),
1685 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1686 	    &bbr_marks_rxt_sack_passed, 0,
1687 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1688 	/* Policer controls */
1689 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1690 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1691 	    OID_AUTO,
1692 	    "policer",
1693 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1694 	    "Policer controls");
1695 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1696 	    SYSCTL_CHILDREN(bbr_policer),
1697 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1698 	    &bbr_policer_detection_enabled, 1,
1699 	    "Is policer detection enabled??");
1700 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1701 	    SYSCTL_CHILDREN(bbr_policer),
1702 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1703 	    &bbr_lt_intvl_min_rtts, 4,
1704 	    "Minimum number of PE's?");
1705 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1706 	    SYSCTL_CHILDREN(bbr_policer),
1707 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1708 	    &bbr_lt_bw_diff, (4000/8),
1709 	    "Minimal bw diff?");
1710 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1711 	    SYSCTL_CHILDREN(bbr_policer),
1712 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1713 	    &bbr_lt_bw_ratio, 8,
1714 	    "Minimal bw diff?");
1715 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1716 	    SYSCTL_CHILDREN(bbr_policer),
1717 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1718 	    &bbr_policer_call_from_rack_to, 0,
1719 	    "Do we call the policer detection code from a rack-timeout?");
1720 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1721 	    SYSCTL_CHILDREN(bbr_policer),
1722 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1723 	    &bbr_lt_intvl_fp, 0,
1724 	    "What packet epoch do we do false-positive detection at (0=no)?");
1725 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1726 	    SYSCTL_CHILDREN(bbr_policer),
1727 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1728 	    &bbr_lt_loss_thresh, 196,
1729 	    "Loss threshold 196 = 19.6%?");
1730 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1731 	    SYSCTL_CHILDREN(bbr_policer),
1732 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1733 	    &bbr_lt_fd_thresh, 100,
1734 	    "What percentage is the false detection threshold (150=15.0)?");
1735 	/* All the rest */
1736 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1737 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1738 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1739 	    &bbr_use_rack_resend_cheat, 0,
1740 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1741 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1742 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1743 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1744 	    &bbr_error_base_paceout, 10000,
1745 	    "When we hit an error what is the min to pace out in usec's?");
1746 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1747 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1748 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1749 	    &bbr_max_net_error_cnt, 10,
1750 	    "When we hit this many errors in a row, kill the session?");
1751 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1752 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1753 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1754 	    &bbr_ignore_data_after_close, 1,
1755 	    "Do we hold off sending a RST until all pending data is ack'd");
1756 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1757 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1758 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1759 	    &bbr_resends_use_tso, 0,
1760 	    "Can resends use TSO?");
1761 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1762 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1763 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1764 	    &bbr_sack_block_limit, 128,
1765 	    "When do we start ignoring small sack blocks");
1766 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1767 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1768 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1769 	    &bbr_verbose_logging, 0,
1770 	    "Should BBR black box logging be verbose");
1771 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1772 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1773 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1774 	    &bbr_reorder_thresh, 2,
1775 	    "What factor for rack will be added when seeing reordering (shift right)");
1776 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1777 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1778 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1779 	    &bbr_reorder_fade, 0,
1780 	    "Does reorder detection fade, if so how many ms (0 means never)");
1781 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1782 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1783 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1784 	    &bbr_tlp_thresh, 1,
1785 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1786 	/* Stats and counters */
1787 	/* The pacing counters for hdwr/software can't be in the array */
1788 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1789 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1790 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1791 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1792 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1793 	    &bbr_hdwr_pacing_enobuf,
1794 	    "Total number of enobufs for hardware paced flows");
1795 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1796 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1797 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1798 	    &bbr_nohdwr_pacing_enobuf,
1799 	    "Total number of enobufs for non-hardware paced flows");
1800 
1801 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1802 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1803 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1804 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1805 	    &bbr_flows_whdwr_pacing,
1806 	    "Total number of hardware paced flows");
1807 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1808 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1809 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1810 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1811 	    &bbr_flows_nohdwr_pacing,
1812 	    "Total number of software paced flows");
1813 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1814 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1815 	    OID_AUTO, "stats", CTLFLAG_RD,
1816 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1817 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1818 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1819 	    OID_AUTO, "opts", CTLFLAG_RD,
1820 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1821 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1822 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1823 	    OID_AUTO, "lost", CTLFLAG_RD,
1824 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1825 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1826 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1827 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1828 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1829 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1830 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1831 	    OID_AUTO, "statetime", CTLFLAG_RD,
1832 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1833 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1834 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1835 	    OID_AUTO, "outsize", CTLFLAG_RD,
1836 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1837 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1838 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1839 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1840 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1841 }
1842 
1843 static void
1844 bbr_counter_destroy(void)
1845 {
1846 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1847 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1848 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1849 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1850 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1851 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1852 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1853 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1854 	counter_u64_free(bbr_flows_whdwr_pacing);
1855 	counter_u64_free(bbr_flows_nohdwr_pacing);
1856 
1857 }
1858 
1859 static __inline void
1860 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1861 {
1862 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1863 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1864 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1865 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1866 	l->bw_inuse = bbr_get_bw(bbr);
1867 	l->inflight = ctf_flight_size(bbr->rc_tp,
1868 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1869 	l->applimited = bbr->r_ctl.r_app_limited_until;
1870 	l->delivered = bbr->r_ctl.rc_delivered;
1871 	l->timeStamp = cts;
1872 	l->lost = bbr->r_ctl.rc_lost;
1873 	l->bbr_state = bbr->rc_bbr_state;
1874 	l->bbr_substate = bbr_state_val(bbr);
1875 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1876 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1877 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1878 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1879 	l->inhpts = tcp_in_hpts(bbr->rc_inp);
1880 	l->use_lt_bw = bbr->rc_lt_use_bw;
1881 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1882 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1883 }
1884 
1885 static void
1886 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1887 {
1888 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1889 		union tcp_log_stackspecific log;
1890 
1891 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1892 		log.u_bbr.flex1 = 0;
1893 		log.u_bbr.flex2 = 0;
1894 		log.u_bbr.flex5 = 0;
1895 		log.u_bbr.flex3 = 0;
1896 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1897 		log.u_bbr.flex7 = reason;
1898 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1899 		log.u_bbr.flex8 = 0;
1900 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1901 		    &bbr->rc_inp->inp_socket->so_rcv,
1902 		    &bbr->rc_inp->inp_socket->so_snd,
1903 		    BBR_LOG_BW_RED_EV, 0,
1904 		    0, &log, false, &bbr->rc_tv);
1905 	}
1906 }
1907 
1908 static void
1909 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1910 {
1911 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1912 		union tcp_log_stackspecific log;
1913 
1914 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1915 		log.u_bbr.flex1 = seq;
1916 		log.u_bbr.flex2 = count;
1917 		log.u_bbr.flex8 = mode;
1918 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1919 		    &bbr->rc_inp->inp_socket->so_rcv,
1920 		    &bbr->rc_inp->inp_socket->so_snd,
1921 		    BBR_LOG_LOWGAIN, 0,
1922 		    0, &log, false, &bbr->rc_tv);
1923 	}
1924 }
1925 
1926 static void
1927 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1928     uint8_t reason, uint32_t p_maxseg, int len)
1929 {
1930 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1931 		union tcp_log_stackspecific log;
1932 
1933 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1934 		log.u_bbr.flex1 = p_maxseg;
1935 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1936 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1937 		log.u_bbr.flex4 = reason;
1938 		log.u_bbr.flex5 = bbr->rc_in_persist;
1939 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1940 		log.u_bbr.flex7 = p_maxseg;
1941 		log.u_bbr.flex8 = bbr->rc_in_persist;
1942 		log.u_bbr.pkts_out = 0;
1943 		log.u_bbr.applimited = len;
1944 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1945 		    &bbr->rc_inp->inp_socket->so_rcv,
1946 		    &bbr->rc_inp->inp_socket->so_snd,
1947 		    BBR_LOG_JUSTRET, 0,
1948 		    tlen, &log, false, &bbr->rc_tv);
1949 	}
1950 }
1951 
1952 static void
1953 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1954 {
1955 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1956 		union tcp_log_stackspecific log;
1957 
1958 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1959 		log.u_bbr.flex1 = seq;
1960 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1961 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1962 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1963 		    &bbr->rc_inp->inp_socket->so_rcv,
1964 		    &bbr->rc_inp->inp_socket->so_snd,
1965 		    BBR_LOG_ENTREC, 0,
1966 		    0, &log, false, &bbr->rc_tv);
1967 	}
1968 }
1969 
1970 static void
1971 bbr_log_msgsize_fail(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t len, uint32_t maxseg, uint32_t mtu, int32_t csum_flags, int32_t tso, uint32_t cts)
1972 {
1973 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
1974 		union tcp_log_stackspecific log;
1975 
1976 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1977 		log.u_bbr.flex1 = tso;
1978 		log.u_bbr.flex2 = maxseg;
1979 		log.u_bbr.flex3 = mtu;
1980 		log.u_bbr.flex4 = csum_flags;
1981 		TCP_LOG_EVENTP(tp, NULL,
1982 		    &bbr->rc_inp->inp_socket->so_rcv,
1983 		    &bbr->rc_inp->inp_socket->so_snd,
1984 		    BBR_LOG_MSGSIZE, 0,
1985 		    0, &log, false, &bbr->rc_tv);
1986 	}
1987 }
1988 
1989 static void
1990 bbr_log_flowend(struct tcp_bbr *bbr)
1991 {
1992 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1993 		union tcp_log_stackspecific log;
1994 		struct sockbuf *r, *s;
1995 		struct timeval tv;
1996 
1997 		if (bbr->rc_inp->inp_socket) {
1998 			r = &bbr->rc_inp->inp_socket->so_rcv;
1999 			s = &bbr->rc_inp->inp_socket->so_snd;
2000 		} else {
2001 			r = s = NULL;
2002 		}
2003 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2004 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2005 		    r, s,
2006 		    TCP_LOG_FLOWEND, 0,
2007 		    0, &log, false, &tv);
2008 	}
2009 }
2010 
2011 static void
2012 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2013     uint32_t lost, uint32_t del)
2014 {
2015 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2016 		union tcp_log_stackspecific log;
2017 
2018 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2019 		log.u_bbr.flex1 = lost;
2020 		log.u_bbr.flex2 = del;
2021 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2022 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2023 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2024 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2025 		log.u_bbr.flex7 = line;
2026 		log.u_bbr.flex8 = 0;
2027 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2028 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2029 		    &bbr->rc_inp->inp_socket->so_rcv,
2030 		    &bbr->rc_inp->inp_socket->so_snd,
2031 		    BBR_LOG_PKT_EPOCH, 0,
2032 		    0, &log, false, &bbr->rc_tv);
2033 	}
2034 }
2035 
2036 static void
2037 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2038 {
2039 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2040 		union tcp_log_stackspecific log;
2041 
2042 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2043 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2044 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2045 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2046 		log.u_bbr.flex7 = line;
2047 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2048 		    &bbr->rc_inp->inp_socket->so_rcv,
2049 		    &bbr->rc_inp->inp_socket->so_snd,
2050 		    BBR_LOG_TIME_EPOCH, 0,
2051 		    0, &log, false, &bbr->rc_tv);
2052 	}
2053 }
2054 
2055 static void
2056 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2057 {
2058 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2059 		union tcp_log_stackspecific log;
2060 
2061 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2062 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2063 		log.u_bbr.flex2 = new_tar;
2064 		log.u_bbr.flex3 = line;
2065 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2066 		log.u_bbr.flex5 = bbr_quanta;
2067 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2068 		log.u_bbr.flex7 = bbr->rc_last_options;
2069 		log.u_bbr.flex8 = meth;
2070 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2071 		    &bbr->rc_inp->inp_socket->so_rcv,
2072 		    &bbr->rc_inp->inp_socket->so_snd,
2073 		    BBR_LOG_STATE_TARGET, 0,
2074 		    0, &log, false, &bbr->rc_tv);
2075 	}
2076 
2077 }
2078 
2079 static void
2080 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2081 {
2082 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2083 		union tcp_log_stackspecific log;
2084 
2085 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2086 		log.u_bbr.flex1 = line;
2087 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2088 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2089 		if (bbr_state_is_pkt_epoch)
2090 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2091 		else
2092 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2093 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2094 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2095 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2096 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2097 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2098 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2099 		    &bbr->rc_inp->inp_socket->so_rcv,
2100 		    &bbr->rc_inp->inp_socket->so_snd,
2101 		    BBR_LOG_STATE, 0,
2102 		    0, &log, false, &bbr->rc_tv);
2103 	}
2104 }
2105 
2106 static void
2107 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2108 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2109 {
2110 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2111 		union tcp_log_stackspecific log;
2112 
2113 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2114 		log.u_bbr.flex1 = line;
2115 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2116 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2117 		log.u_bbr.flex4 = applied;
2118 		log.u_bbr.flex5 = rtt;
2119 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2120 		log.u_bbr.flex7 = cond;
2121 		log.u_bbr.flex8 = reas;
2122 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2123 		    &bbr->rc_inp->inp_socket->so_rcv,
2124 		    &bbr->rc_inp->inp_socket->so_snd,
2125 		    BBR_LOG_RTT_SHRINKS, 0,
2126 		    0, &log, false, &bbr->rc_tv);
2127 	}
2128 }
2129 
2130 static void
2131 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2132 {
2133 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2134 		union tcp_log_stackspecific log;
2135 
2136 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2137 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2138 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2139 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2140 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2141 		    &bbr->rc_inp->inp_socket->so_rcv,
2142 		    &bbr->rc_inp->inp_socket->so_snd,
2143 		    BBR_LOG_EXITREC, 0,
2144 		    0, &log, false, &bbr->rc_tv);
2145 	}
2146 }
2147 
2148 static void
2149 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2150     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2151 {
2152 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2153 		union tcp_log_stackspecific log;
2154 
2155 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2156 		log.u_bbr.flex1 = line;
2157 		log.u_bbr.flex2 = prev_acked;
2158 		log.u_bbr.flex3 = bytes_this_ack;
2159 		log.u_bbr.flex4 = chg;
2160 		log.u_bbr.flex5 = th_ack;
2161 		log.u_bbr.flex6 = target;
2162 		log.u_bbr.flex8 = meth;
2163 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2164 		    &bbr->rc_inp->inp_socket->so_rcv,
2165 		    &bbr->rc_inp->inp_socket->so_snd,
2166 		    BBR_LOG_CWND, 0,
2167 		    0, &log, false, &bbr->rc_tv);
2168 	}
2169 }
2170 
2171 static void
2172 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2173 {
2174 	/*
2175 	 * Log the rtt sample we are applying to the srtt algorithm in
2176 	 * useconds.
2177 	 */
2178 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2179 		union tcp_log_stackspecific log;
2180 
2181 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2182 		log.u_bbr.flex1 = rtt;
2183 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2184 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2185 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2186 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2187 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2188 		log.u_bbr.flex6 = tsin;
2189 		log.u_bbr.flex7 = 0;
2190 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2191 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2192 		    &bbr->rc_inp->inp_socket->so_rcv,
2193 		    &bbr->rc_inp->inp_socket->so_snd,
2194 		    TCP_LOG_RTT, 0,
2195 		    0, &log, false, &bbr->rc_tv);
2196 	}
2197 }
2198 
2199 static void
2200 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2201 {
2202 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2203 		union tcp_log_stackspecific log;
2204 
2205 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2206 		log.u_bbr.flex1 = time_in;
2207 		log.u_bbr.flex2 = line;
2208 		log.u_bbr.flex8 = enter_exit;
2209 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2210 		    &bbr->rc_inp->inp_socket->so_rcv,
2211 		    &bbr->rc_inp->inp_socket->so_snd,
2212 		    BBR_LOG_PERSIST, 0,
2213 		    0, &log, false, &bbr->rc_tv);
2214 	}
2215 }
2216 static void
2217 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2218 {
2219 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2220 		union tcp_log_stackspecific log;
2221 
2222 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2223 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2224 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2225 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2226 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2227 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2228 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2229 		    &bbr->rc_inp->inp_socket->so_rcv,
2230 		    &bbr->rc_inp->inp_socket->so_snd,
2231 		    BBR_LOG_ACKCLEAR, 0,
2232 		    0, &log, false, &bbr->rc_tv);
2233 	}
2234 }
2235 
2236 static void
2237 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2238 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2239 {
2240 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2241 		union tcp_log_stackspecific log;
2242 		struct timeval tv;
2243 
2244 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2245 		log.u_bbr.flex1 = nsegs;
2246 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2247 		if (m) {
2248 			struct timespec ts;
2249 
2250 			log.u_bbr.flex3 = m->m_flags;
2251 			if (m->m_flags & M_TSTMP) {
2252 				mbuf_tstmp2timespec(m, &ts);
2253 				tv.tv_sec = ts.tv_sec;
2254 				tv.tv_usec = ts.tv_nsec / 1000;
2255 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2256 			} else {
2257 				log.u_bbr.lt_epoch = 0;
2258 			}
2259 			if (m->m_flags & M_TSTMP_LRO) {
2260 				mbuf_tstmp2timeval(m, &tv);
2261 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2262 			} else {
2263 				/* No arrival timestamp */
2264 				log.u_bbr.flex5 = 0;
2265 			}
2266 
2267 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2268 		} else {
2269 			log.u_bbr.flex3 = 0;
2270 			log.u_bbr.flex5 = 0;
2271 			log.u_bbr.flex6 = 0;
2272 			log.u_bbr.pkts_out = 0;
2273 		}
2274 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2275 		log.u_bbr.flex7 = bbr->r_wanted_output;
2276 		log.u_bbr.flex8 = bbr->rc_in_persist;
2277 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2278 		    &bbr->rc_inp->inp_socket->so_rcv,
2279 		    &bbr->rc_inp->inp_socket->so_snd,
2280 		    TCP_LOG_IN, 0,
2281 		    tlen, &log, true, &bbr->rc_tv);
2282 	}
2283 }
2284 
2285 static void
2286 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2287 {
2288 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2289 		union tcp_log_stackspecific log;
2290 
2291 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2292 		log.u_bbr.flex1 = did_out;
2293 		log.u_bbr.flex2 = nxt_pkt;
2294 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2295 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2296 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2297 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2298 		log.u_bbr.flex7 = bbr->r_wanted_output;
2299 		log.u_bbr.flex8 = bbr->rc_in_persist;
2300 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2301 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2302 		    &bbr->rc_inp->inp_socket->so_rcv,
2303 		    &bbr->rc_inp->inp_socket->so_snd,
2304 		    BBR_LOG_DOSEG_DONE, 0,
2305 		    0, &log, true, &bbr->rc_tv);
2306 	}
2307 }
2308 
2309 static void
2310 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2311     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2312 {
2313 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2314 		union tcp_log_stackspecific log;
2315 
2316 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2317 		log.u_bbr.flex1 = line;
2318 		log.u_bbr.flex2 = o_len;
2319 		log.u_bbr.flex3 = segcnt;
2320 		log.u_bbr.flex4 = segsiz;
2321 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2322 		    &bbr->rc_inp->inp_socket->so_rcv,
2323 		    &bbr->rc_inp->inp_socket->so_snd,
2324 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2325 		    len, &log, true, &bbr->rc_tv);
2326 	}
2327 }
2328 
2329 static void
2330 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2331 {
2332 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2333 		union tcp_log_stackspecific log;
2334 
2335 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2336 		log.u_bbr.flex1 = timers;
2337 		log.u_bbr.flex2 = ret;
2338 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2339 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2340 		log.u_bbr.flex5 = cts;
2341 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2342 		log.u_bbr.flex8 = hpts_calling;
2343 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2344 		    &bbr->rc_inp->inp_socket->so_rcv,
2345 		    &bbr->rc_inp->inp_socket->so_snd,
2346 		    BBR_LOG_TO_PROCESS, 0,
2347 		    0, &log, false, &bbr->rc_tv);
2348 	}
2349 }
2350 
2351 static void
2352 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2353 {
2354 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2355 		union tcp_log_stackspecific log;
2356 		uint64_t ar;
2357 
2358 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2359 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2360 		log.u_bbr.flex2 = 0;
2361 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2362 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2363 		ar >>= 32;
2364 		ar &= 0x00000000ffffffff;
2365 		log.u_bbr.flex4 = (uint32_t)ar;
2366 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2367 		ar &= 0x00000000ffffffff;
2368 		log.u_bbr.flex5 = (uint32_t)ar;
2369 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2370 		log.u_bbr.flex8 = to_num;
2371 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2372 		    &bbr->rc_inp->inp_socket->so_rcv,
2373 		    &bbr->rc_inp->inp_socket->so_snd,
2374 		    BBR_LOG_RTO, 0,
2375 		    0, &log, false, &bbr->rc_tv);
2376 	}
2377 }
2378 
2379 static void
2380 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2381 {
2382 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2383 		union tcp_log_stackspecific log;
2384 
2385 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2386 		log.u_bbr.flex1 = flex1;
2387 		log.u_bbr.flex2 = flex2;
2388 		log.u_bbr.flex3 = flex3;
2389 		log.u_bbr.flex4 = 0;
2390 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2391 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2392 		log.u_bbr.flex8 = reason;
2393 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2394 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2395 		    &bbr->rc_inp->inp_socket->so_rcv,
2396 		    &bbr->rc_inp->inp_socket->so_snd,
2397 		    BBR_LOG_REDUCE, 0,
2398 		    0, &log, false, &bbr->rc_tv);
2399 	}
2400 }
2401 
2402 static void
2403 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2404 {
2405 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2406 		union tcp_log_stackspecific log;
2407 
2408 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2409 		log.u_bbr.flex1 = diag->p_nxt_slot;
2410 		log.u_bbr.flex2 = diag->p_cur_slot;
2411 		log.u_bbr.flex3 = diag->slot_req;
2412 		log.u_bbr.flex4 = diag->inp_hptsslot;
2413 		log.u_bbr.flex5 = diag->slot_remaining;
2414 		log.u_bbr.flex6 = diag->need_new_to;
2415 		log.u_bbr.flex7 = diag->p_hpts_active;
2416 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2417 		/* Hijack other fields as needed  */
2418 		log.u_bbr.epoch = diag->have_slept;
2419 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2420 		log.u_bbr.pkts_out = diag->co_ret;
2421 		log.u_bbr.applimited = diag->hpts_sleep_time;
2422 		log.u_bbr.delivered = diag->p_prev_slot;
2423 		log.u_bbr.inflight = diag->p_runningslot;
2424 		log.u_bbr.bw_inuse = diag->wheel_slot;
2425 		log.u_bbr.rttProp = diag->wheel_cts;
2426 		log.u_bbr.delRate = diag->maxslots;
2427 		log.u_bbr.cur_del_rate = diag->p_curtick;
2428 		log.u_bbr.cur_del_rate <<= 32;
2429 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2430 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2431 		    &bbr->rc_inp->inp_socket->so_rcv,
2432 		    &bbr->rc_inp->inp_socket->so_snd,
2433 		    BBR_LOG_HPTSDIAG, 0,
2434 		    0, &log, false, &bbr->rc_tv);
2435 	}
2436 }
2437 
2438 static void
2439 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2440     uint32_t thresh, uint32_t to)
2441 {
2442 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2443 		union tcp_log_stackspecific log;
2444 
2445 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2446 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2447 		log.u_bbr.flex2 = time_since_sent;
2448 		log.u_bbr.flex3 = srtt;
2449 		log.u_bbr.flex4 = thresh;
2450 		log.u_bbr.flex5 = to;
2451 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2452 		log.u_bbr.flex8 = mode;
2453 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2454 		    &bbr->rc_inp->inp_socket->so_rcv,
2455 		    &bbr->rc_inp->inp_socket->so_snd,
2456 		    BBR_LOG_TIMERPREP, 0,
2457 		    0, &log, false, &bbr->rc_tv);
2458 	}
2459 }
2460 
2461 static void
2462 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2463     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2464 {
2465 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2466 		union tcp_log_stackspecific log;
2467 
2468 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2469 		log.u_bbr.flex1 = usecs;
2470 		log.u_bbr.flex2 = len;
2471 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2472 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2473 		if (override)
2474 			log.u_bbr.flex5 = (1 << 2);
2475 		else
2476 			log.u_bbr.flex5 = 0;
2477 		log.u_bbr.flex6 = override;
2478 		log.u_bbr.flex7 = gain;
2479 		log.u_bbr.flex8 = mod;
2480 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2481 		    &bbr->rc_inp->inp_socket->so_rcv,
2482 		    &bbr->rc_inp->inp_socket->so_snd,
2483 		    BBR_LOG_HPTSI_CALC, 0,
2484 		    len, &log, false, &bbr->rc_tv);
2485 	}
2486 }
2487 
2488 static void
2489 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2490 {
2491 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2492 		union tcp_log_stackspecific log;
2493 
2494 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2495 
2496 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2497 		log.u_bbr.flex2 = to;
2498 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2499 		log.u_bbr.flex4 = slot;
2500 		log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2501 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2502 		log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2503 		log.u_bbr.flex8 = which;
2504 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2505 		    &bbr->rc_inp->inp_socket->so_rcv,
2506 		    &bbr->rc_inp->inp_socket->so_snd,
2507 		    BBR_LOG_TIMERSTAR, 0,
2508 		    0, &log, false, &bbr->rc_tv);
2509 	}
2510 }
2511 
2512 static void
2513 bbr_log_thresh_choice(struct tcp_bbr *bbr, uint32_t cts, uint32_t thresh, uint32_t lro, uint32_t srtt, struct bbr_sendmap *rsm, uint8_t frm)
2514 {
2515 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2516 		union tcp_log_stackspecific log;
2517 
2518 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2519 		log.u_bbr.flex1 = thresh;
2520 		log.u_bbr.flex2 = lro;
2521 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2522 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2523 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2524 		log.u_bbr.flex6 = srtt;
2525 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2526 		log.u_bbr.flex8 = frm;
2527 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2528 		    &bbr->rc_inp->inp_socket->so_rcv,
2529 		    &bbr->rc_inp->inp_socket->so_snd,
2530 		    BBR_LOG_THRESH_CALC, 0,
2531 		    0, &log, false, &bbr->rc_tv);
2532 	}
2533 }
2534 
2535 static void
2536 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2537 {
2538 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2539 		union tcp_log_stackspecific log;
2540 
2541 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2542 		log.u_bbr.flex1 = line;
2543 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2544 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2545 		log.u_bbr.flex4 = bbr->rc_in_persist;
2546 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2547 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2548 		log.u_bbr.flex8 = hpts_removed;
2549 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2550 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2551 		    &bbr->rc_inp->inp_socket->so_rcv,
2552 		    &bbr->rc_inp->inp_socket->so_snd,
2553 		    BBR_LOG_TIMERCANC, 0,
2554 		    0, &log, false, &bbr->rc_tv);
2555 	}
2556 }
2557 
2558 static void
2559 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2560 {
2561 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2562 		union tcp_log_stackspecific log;
2563 
2564 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2565 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2566 		log.u_bbr.flex2 = (peer_delta >> 32);
2567 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2568 		log.u_bbr.flex4 = (delta >> 32);
2569 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2570 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2571 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2572 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2573 		    &bbr->rc_inp->inp_socket->so_rcv,
2574 		    &bbr->rc_inp->inp_socket->so_snd,
2575 		    BBR_LOG_TSTMP_VAL, 0,
2576 		    0, &log, false, &bbr->rc_tv);
2577 	}
2578 }
2579 
2580 static void
2581 bbr_log_type_tsosize(struct tcp_bbr *bbr, uint32_t cts, uint32_t tsosz, uint32_t tls, uint32_t old_val, uint32_t maxseg, int hdwr)
2582 {
2583 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2584 		union tcp_log_stackspecific log;
2585 
2586 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2587 		log.u_bbr.flex1 = tsosz;
2588 		log.u_bbr.flex2 = tls;
2589 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2590 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2591 		log.u_bbr.flex5 = old_val;
2592 		log.u_bbr.flex6 = maxseg;
2593 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2594 		log.u_bbr.flex7 <<= 1;
2595 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2596 		if (hdwr)
2597 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2598 		else
2599 			log.u_bbr.flex8 = bbr->rc_use_google;
2600 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2601 		    &bbr->rc_inp->inp_socket->so_rcv,
2602 		    &bbr->rc_inp->inp_socket->so_snd,
2603 		    BBR_LOG_BBRTSO, 0,
2604 		    0, &log, false, &bbr->rc_tv);
2605 	}
2606 }
2607 
2608 static void
2609 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2610 		      uint32_t flags, uint32_t line)
2611 {
2612 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2613 		union tcp_log_stackspecific log;
2614 
2615 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2616 		log.u_bbr.flex1 = line;
2617 		log.u_bbr.flex2 = rsm->r_start;
2618 		log.u_bbr.flex3 = rsm->r_end;
2619 		log.u_bbr.flex4 = rsm->r_delivered;
2620 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2621 		log.u_bbr.flex6 = rsm->r_dupack;
2622 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2623 		log.u_bbr.flex8 = rsm->r_flags;
2624 		/* Hijack the pkts_out fids */
2625 		log.u_bbr.applimited = flags;
2626 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2627 		    &bbr->rc_inp->inp_socket->so_rcv,
2628 		    &bbr->rc_inp->inp_socket->so_snd,
2629 		    BBR_RSM_CLEARED, 0,
2630 		    0, &log, false, &bbr->rc_tv);
2631 	}
2632 }
2633 
2634 static void
2635 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2636     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2637     uint32_t flex6, uint32_t pkts_out, int flex7,
2638     uint32_t flex4, uint32_t flex1)
2639 {
2640 
2641 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2642 		union tcp_log_stackspecific log;
2643 
2644 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2645 		log.u_bbr.flex1 = flex1;
2646 		log.u_bbr.flex2 = flex2;
2647 		log.u_bbr.flex3 = flex3;
2648 		log.u_bbr.flex4 = flex4;
2649 		log.u_bbr.flex5 = flex5;
2650 		log.u_bbr.flex6 = flex6;
2651 		log.u_bbr.flex7 = flex7;
2652 		/* Hijack the pkts_out fids */
2653 		log.u_bbr.pkts_out = pkts_out;
2654 		log.u_bbr.flex8 = flex8;
2655 		if (bbr->rc_ack_was_delayed)
2656 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2657 		else
2658 			log.u_bbr.epoch = 0;
2659 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2660 		    &bbr->rc_inp->inp_socket->so_rcv,
2661 		    &bbr->rc_inp->inp_socket->so_snd,
2662 		    BBR_LOG_BBRUPD, 0,
2663 		    flex2, &log, false, &bbr->rc_tv);
2664 	}
2665 }
2666 
2667 static void
2668 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2669 	uint32_t newbw, uint32_t obw, uint32_t diff,
2670 	uint32_t tim)
2671 {
2672 	if (/*bbr_verbose_logging && */(bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2673 		union tcp_log_stackspecific log;
2674 
2675 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2676 		log.u_bbr.flex1 = reason;
2677 		log.u_bbr.flex2 = newbw;
2678 		log.u_bbr.flex3 = obw;
2679 		log.u_bbr.flex4 = diff;
2680 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2681 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2682 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2683 		log.u_bbr.pkts_out = tim;
2684 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2685 		if (bbr->rc_lt_use_bw == 0)
2686 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2687 		else
2688 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2689 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2690 		    &bbr->rc_inp->inp_socket->so_rcv,
2691 		    &bbr->rc_inp->inp_socket->so_snd,
2692 		    BBR_LOG_BWSAMP, 0,
2693 		    0, &log, false, &bbr->rc_tv);
2694 	}
2695 }
2696 
2697 static inline void
2698 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2699 {
2700 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2701 		union tcp_log_stackspecific log;
2702 
2703 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2704 		log.u_bbr.flex1 = line;
2705 		log.u_bbr.flex2 = tick;
2706 		log.u_bbr.flex3 = tp->t_maxunacktime;
2707 		log.u_bbr.flex4 = tp->t_acktime;
2708 		log.u_bbr.flex8 = event;
2709 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2710 		    &bbr->rc_inp->inp_socket->so_rcv,
2711 		    &bbr->rc_inp->inp_socket->so_snd,
2712 		    BBR_LOG_PROGRESS, 0,
2713 		    0, &log, false, &bbr->rc_tv);
2714 	}
2715 }
2716 
2717 static void
2718 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2719 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2720 			 int error)
2721 {
2722 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2723 		union tcp_log_stackspecific log;
2724 
2725 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2726 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2727 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2728 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2729 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2730 		log.u_bbr.bw_inuse = rate;
2731 		log.u_bbr.flex5 = line;
2732 		log.u_bbr.flex6 = error;
2733 		log.u_bbr.flex8 = bbr->skip_gain;
2734 		log.u_bbr.flex8 <<= 1;
2735 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2736 		log.u_bbr.flex8 <<= 1;
2737 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2738 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2739 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2740 		    &bbr->rc_inp->inp_socket->so_rcv,
2741 		    &bbr->rc_inp->inp_socket->so_snd,
2742 		    BBR_LOG_HDWR_PACE, 0,
2743 		    0, &log, false, &bbr->rc_tv);
2744 	}
2745 }
2746 
2747 static void
2748 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot, uint32_t del_by, uint32_t cts, uint32_t line, uint32_t prev_delay)
2749 {
2750 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2751 		union tcp_log_stackspecific log;
2752 
2753 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2754 		log.u_bbr.flex1 = slot;
2755 		log.u_bbr.flex2 = del_by;
2756 		log.u_bbr.flex3 = prev_delay;
2757 		log.u_bbr.flex4 = line;
2758 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2759 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2760 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2761 		log.u_bbr.flex8 = bbr->rc_in_persist;
2762 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2763 		    &bbr->rc_inp->inp_socket->so_rcv,
2764 		    &bbr->rc_inp->inp_socket->so_snd,
2765 		    BBR_LOG_BBRSND, 0,
2766 		    len, &log, false, &bbr->rc_tv);
2767 	}
2768 }
2769 
2770 static void
2771 bbr_log_type_bbrrttprop(struct tcp_bbr *bbr, uint32_t t, uint32_t end, uint32_t tsconv, uint32_t cts, int32_t match, uint32_t seq, uint8_t flags)
2772 {
2773 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2774 		union tcp_log_stackspecific log;
2775 
2776 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2777 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2778 		log.u_bbr.flex2 = 0;
2779 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2780 		log.u_bbr.flex4 = end;
2781 		log.u_bbr.flex5 = seq;
2782 		log.u_bbr.flex6 = t;
2783 		log.u_bbr.flex7 = match;
2784 		log.u_bbr.flex8 = flags;
2785 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2786 		    &bbr->rc_inp->inp_socket->so_rcv,
2787 		    &bbr->rc_inp->inp_socket->so_snd,
2788 		    BBR_LOG_BBRRTT, 0,
2789 		    0, &log, false, &bbr->rc_tv);
2790 	}
2791 }
2792 
2793 static void
2794 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2795 {
2796 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2797 		union tcp_log_stackspecific log;
2798 
2799 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2800 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2801 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2802 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2803 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2804 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2805 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2806 		log.u_bbr.flex7 = 0;
2807 		log.u_bbr.flex8 = entry_method;
2808 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2809 		    &bbr->rc_inp->inp_socket->so_rcv,
2810 		    &bbr->rc_inp->inp_socket->so_snd,
2811 		    BBR_LOG_EXIT_GAIN, 0,
2812 		    0, &log, false, &bbr->rc_tv);
2813 	}
2814 }
2815 
2816 static void
2817 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2818 {
2819 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2820 		union tcp_log_stackspecific log;
2821 
2822 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2823 		/* R-HU */
2824 		log.u_bbr.flex1 = 0;
2825 		log.u_bbr.flex2 = 0;
2826 		log.u_bbr.flex3 = 0;
2827 		log.u_bbr.flex4 = 0;
2828 		log.u_bbr.flex7 = 0;
2829 		log.u_bbr.flex8 = settings_desired;
2830 
2831 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2832 		    &bbr->rc_inp->inp_socket->so_rcv,
2833 		    &bbr->rc_inp->inp_socket->so_snd,
2834 		    BBR_LOG_SETTINGS_CHG, 0,
2835 		    0, &log, false, &bbr->rc_tv);
2836 	}
2837 }
2838 
2839 /*
2840  * Returns the bw from the our filter.
2841  */
2842 static inline uint64_t
2843 bbr_get_full_bw(struct tcp_bbr *bbr)
2844 {
2845 	uint64_t bw;
2846 
2847 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2848 
2849 	return (bw);
2850 }
2851 
2852 static inline void
2853 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2854 {
2855 	uint64_t calclr;
2856 	uint32_t lost, del;
2857 
2858 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2859 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2860 	else
2861 		lost = 0;
2862 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2863 	if (lost == 0)  {
2864 		calclr = 0;
2865 	} else if (del) {
2866 		calclr = lost;
2867 		calclr *= (uint64_t)1000;
2868 		calclr /= (uint64_t)del;
2869 	} else {
2870 		/* Nothing delivered? 100.0% loss */
2871 		calclr = 1000;
2872 	}
2873 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2874 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2875 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2876 	bbr->r_ctl.rc_pkt_epoch++;
2877 	if (bbr->rc_no_pacing &&
2878 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2879 		bbr->rc_no_pacing = 0;
2880 		tcp_bbr_tso_size_check(bbr, cts);
2881 	}
2882 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2883 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2884 	/* What was our loss rate */
2885 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2886 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2887 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2888 }
2889 
2890 static inline void
2891 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2892 {
2893 	uint32_t epoch_time;
2894 
2895 	/* Tick the RTT clock */
2896 	bbr->r_ctl.rc_rtt_epoch++;
2897 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2898 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2899 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2900 }
2901 
2902 static inline void
2903 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2904 {
2905 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2906 		bbr->rc_is_pkt_epoch_now = 1;
2907 	}
2908 }
2909 
2910 /*
2911  * Returns the bw from either the b/w filter
2912  * or from the lt_bw (if the connection is being
2913  * policed).
2914  */
2915 static inline uint64_t
2916 __bbr_get_bw(struct tcp_bbr *bbr)
2917 {
2918 	uint64_t bw, min_bw;
2919 	uint64_t rtt;
2920 	int gm_measure_cnt = 1;
2921 
2922 	/*
2923 	 * For startup we make, like google, a
2924 	 * minimum b/w. This is generated from the
2925 	 * IW and the rttProp. We do fall back to srtt
2926 	 * if for some reason (initial handshake) we don't
2927 	 * have a rttProp. We, in the worst case, fall back
2928 	 * to the configured min_bw (rc_initial_hptsi_bw).
2929 	 */
2930 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2931 		/* Attempt first to use rttProp */
2932 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2933 		if (rtt && (rtt < 0xffffffff)) {
2934 measure:
2935 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2936 				((uint64_t)1000000);
2937 			min_bw /= rtt;
2938 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2939 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2940 			}
2941 
2942 		} else if (bbr->rc_tp->t_srtt != 0) {
2943 			/* No rttProp, use srtt? */
2944 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2945 			goto measure;
2946 		} else {
2947 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2948 		}
2949 	} else
2950 		min_bw = 0;
2951 
2952 	if ((bbr->rc_past_init_win == 0) &&
2953 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2954 		bbr->rc_past_init_win = 1;
2955 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2956 		gm_measure_cnt = 0;
2957 	if (gm_measure_cnt &&
2958 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2959 	     (bbr->rc_past_init_win == 0))) {
2960 		/* For google we use our guess rate until we get 1 measurement */
2961 
2962 use_initial_window:
2963 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2964 		if (rtt && (rtt < 0xffffffff)) {
2965 			/*
2966 			 * We have an RTT measurement. Use that in
2967 			 * combination with our initial window to calculate
2968 			 * a b/w.
2969 			 */
2970 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2971 				((uint64_t)1000000);
2972 			bw /= rtt;
2973 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2974 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2975 			}
2976 		} else {
2977 			/* Drop back to the 40 and punt to a default */
2978 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2979 		}
2980 		if (bw < 1)
2981 			/* Probably should panic */
2982 			bw = 1;
2983 		if (bw > min_bw)
2984 			return (bw);
2985 		else
2986 			return (min_bw);
2987 	}
2988 	if (bbr->rc_lt_use_bw)
2989 		bw = bbr->r_ctl.rc_lt_bw;
2990 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2991 		bw = bbr->r_ctl.red_bw;
2992 	else
2993 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2994 	if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
2995 		/*
2996 		 * Enforce user set rate limit, keep in mind that
2997 		 * t_peakrate_thr is in B/s already
2998 		 */
2999 		bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3000 	}
3001 	if (bw == 0) {
3002 		/* We should not be at 0, go to the initial window then  */
3003 		goto use_initial_window;
3004 	}
3005 	if (bw < 1)
3006 		/* Probably should panic */
3007 		bw = 1;
3008 	if (bw < min_bw)
3009 		bw = min_bw;
3010 	return (bw);
3011 }
3012 
3013 static inline uint64_t
3014 bbr_get_bw(struct tcp_bbr *bbr)
3015 {
3016 	uint64_t bw;
3017 
3018 	bw = __bbr_get_bw(bbr);
3019 	return (bw);
3020 }
3021 
3022 static inline void
3023 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3024 {
3025 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3026 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3027 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3028 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3029 }
3030 
3031 static inline void
3032 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3033 {
3034 	bbr->rc_lt_is_sampling = 0;
3035 	bbr->rc_lt_use_bw = 0;
3036 	bbr->r_ctl.rc_lt_bw = 0;
3037 	bbr_reset_lt_bw_interval(bbr, cts);
3038 }
3039 
3040 static inline void
3041 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3042 {
3043 	uint64_t diff;
3044 
3045 	/* Do we have a previous sample? */
3046 	if (bbr->r_ctl.rc_lt_bw) {
3047 		/* Get the diff in bytes per second */
3048 		if (bbr->r_ctl.rc_lt_bw > bw)
3049 			diff = bbr->r_ctl.rc_lt_bw - bw;
3050 		else
3051 			diff = bw - bbr->r_ctl.rc_lt_bw;
3052 		if ((diff <= bbr_lt_bw_diff) ||
3053 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3054 			/* Consider us policed */
3055 			uint32_t saved_bw;
3056 
3057 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3058 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3059 			bbr->rc_lt_use_bw = 1;
3060 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3061 			/*
3062 			 * Use pkt based epoch for measuring length of
3063 			 * policer up
3064 			 */
3065 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3066 			/*
3067 			 * reason 4 is we need to start consider being
3068 			 * policed
3069 			 */
3070 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3071 			return;
3072 		}
3073 	}
3074 	bbr->r_ctl.rc_lt_bw = bw;
3075 	bbr_reset_lt_bw_interval(bbr, cts);
3076 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3077 }
3078 
3079 static void
3080 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3081 {
3082 	uint32_t ran, deduct;
3083 
3084 	ran = arc4random_uniform(bbr_rand_ot);
3085 	if (ran) {
3086 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3087 		bbr->r_ctl.rc_level_state_extra -= deduct;
3088 	}
3089 }
3090 /*
3091  * Return randomly the starting state
3092  * to use in probebw.
3093  */
3094 static uint8_t
3095 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3096 {
3097 	uint32_t ran;
3098 	uint8_t ret_val;
3099 
3100 	/* Initialize the offset to 0 */
3101 	bbr->r_ctl.rc_exta_time_gd = 0;
3102 	bbr->rc_hit_state_1 = 0;
3103 	bbr->r_ctl.rc_level_state_extra = 0;
3104 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3105 	/*
3106 	 * The math works funny here :) the return value is used to set the
3107 	 * substate and then the state change is called which increments by
3108 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3109 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3110 	 * we return 1 - 7, so we dont return 0 and end up starting in
3111 	 * state 1 (DRAIN).
3112 	 */
3113 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3114 	/* Set an epoch */
3115 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3116 		bbr_set_epoch(bbr, cts, __LINE__);
3117 
3118 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3119 	return (ret_val);
3120 }
3121 
3122 static void
3123 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3124 {
3125 	uint32_t diff, d_time;
3126 	uint64_t del_time, bw, lost, delivered;
3127 
3128 	if (bbr->r_use_policer == 0)
3129 		return;
3130 	if (bbr->rc_lt_use_bw) {
3131 		/* We are using lt bw do we stop yet? */
3132 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3133 		if (diff > bbr_lt_bw_max_rtts) {
3134 			/* Reset it all */
3135 reset_all:
3136 			bbr_reset_lt_bw_sampling(bbr, cts);
3137 			if (bbr->rc_filled_pipe) {
3138 				bbr_set_epoch(bbr, cts, __LINE__);
3139 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3140 				bbr_substate_change(bbr, cts, __LINE__, 0);
3141 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3142 				bbr_log_type_statechange(bbr, cts, __LINE__);
3143 			} else {
3144 				/*
3145 				 * This should not happen really
3146 				 * unless we remove the startup/drain
3147 				 * restrictions above.
3148 				 */
3149 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3150 				bbr_set_epoch(bbr, cts, __LINE__);
3151 				bbr->r_ctl.rc_bbr_state_time = cts;
3152 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3153 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3154 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3155 				bbr_set_state_target(bbr, __LINE__);
3156 				bbr_log_type_statechange(bbr, cts, __LINE__);
3157 			}
3158 			/* reason 0 is to stop using lt-bw */
3159 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3160 			return;
3161 		}
3162 		if (bbr_lt_intvl_fp == 0) {
3163 			/* Not doing false-positive detection */
3164 			return;
3165 		}
3166 		/* False positive detection */
3167 		if (diff == bbr_lt_intvl_fp) {
3168 			/* At bbr_lt_intvl_fp we record the lost */
3169 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3170 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3171 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3172 			/* Now is our loss rate still high? */
3173 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3174 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3175 			if ((delivered == 0) ||
3176 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3177 				/* No still below our threshold */
3178 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3179 			} else {
3180 				/* Yikes its still high, it must be a false positive */
3181 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3182 				goto reset_all;
3183 			}
3184 		}
3185 		return;
3186 	}
3187 	/*
3188 	 * Wait for the first loss before sampling, to let the policer
3189 	 * exhaust its tokens and estimate the steady-state rate allowed by
3190 	 * the policer. Starting samples earlier includes bursts that
3191 	 * over-estimate the bw.
3192 	 */
3193 	if (bbr->rc_lt_is_sampling == 0) {
3194 		/* reason 1 is to begin doing the sampling  */
3195 		if (loss_detected == 0)
3196 			return;
3197 		bbr_reset_lt_bw_interval(bbr, cts);
3198 		bbr->rc_lt_is_sampling = 1;
3199 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3200 		return;
3201 	}
3202 	/* Now how long were we delivering long term last> */
3203 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3204 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3205 	else
3206 		d_time = 0;
3207 
3208 	/* To avoid underestimates, reset sampling if we run out of data. */
3209 	if (bbr->r_ctl.r_app_limited_until) {
3210 		/* Can not measure in app-limited state */
3211 		bbr_reset_lt_bw_sampling(bbr, cts);
3212 		/* reason 2 is to reset sampling due to app limits  */
3213 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3214 		return;
3215 	}
3216 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3217 	if (diff < bbr_lt_intvl_min_rtts) {
3218 		/*
3219 		 * need more samples (we don't
3220 		 * start on a round like linux so
3221 		 * we need 1 more).
3222 		 */
3223 		/* 6 is not_enough time or no-loss */
3224 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3225 		return;
3226 	}
3227 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3228 		/*
3229 		 * For now if we wait too long, reset all sampling. We need
3230 		 * to do some research here, its possible that we should
3231 		 * base this on how much loss as occurred.. something like
3232 		 * if its under 10% (or some thresh) reset all otherwise
3233 		 * don't.  Thats for phase II I guess.
3234 		 */
3235 		bbr_reset_lt_bw_sampling(bbr, cts);
3236  		/* reason 3 is to reset sampling due too long of sampling */
3237 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3238 		return;
3239 	}
3240 	/*
3241 	 * End sampling interval when a packet is lost, so we estimate the
3242 	 * policer tokens were exhausted. Stopping the sampling before the
3243 	 * tokens are exhausted under-estimates the policed rate.
3244 	 */
3245 	if (loss_detected == 0) {
3246 		/* 6 is not_enough time or no-loss */
3247 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3248 		return;
3249 	}
3250 	/* Calculate packets lost and delivered in sampling interval. */
3251 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3252 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3253 	if ((delivered == 0) ||
3254 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3255 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3256 		return;
3257 	}
3258 	if (d_time < 1000) {
3259 		/* Not enough time. wait */
3260 		/* 6 is not_enough time or no-loss */
3261 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3262 		return;
3263 	}
3264 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3265 		/* Too long */
3266 		bbr_reset_lt_bw_sampling(bbr, cts);
3267  		/* reason 3 is to reset sampling due too long of sampling */
3268 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3269 		return;
3270 	}
3271 	del_time = d_time;
3272 	bw = delivered;
3273 	bw *= (uint64_t)USECS_IN_SECOND;
3274 	bw /= del_time;
3275 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3276 }
3277 
3278 /*
3279  * Allocate a sendmap from our zone.
3280  */
3281 static struct bbr_sendmap *
3282 bbr_alloc(struct tcp_bbr *bbr)
3283 {
3284 	struct bbr_sendmap *rsm;
3285 
3286 	BBR_STAT_INC(bbr_to_alloc);
3287 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3288 	if (rsm) {
3289 		bbr->r_ctl.rc_num_maps_alloced++;
3290 		return (rsm);
3291 	}
3292 	if (bbr->r_ctl.rc_free_cnt) {
3293 		BBR_STAT_INC(bbr_to_alloc_emerg);
3294 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3295 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3296 		bbr->r_ctl.rc_free_cnt--;
3297 		return (rsm);
3298 	}
3299 	BBR_STAT_INC(bbr_to_alloc_failed);
3300 	return (NULL);
3301 }
3302 
3303 static struct bbr_sendmap *
3304 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3305 {
3306 	if ((V_tcp_map_entries_limit > 0) &&
3307 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3308 		BBR_STAT_INC(bbr_alloc_limited);
3309 		if (!bbr->alloc_limit_reported) {
3310 			bbr->alloc_limit_reported = 1;
3311 			BBR_STAT_INC(bbr_alloc_limited_conns);
3312 		}
3313 		return (NULL);
3314 	}
3315 	return (bbr_alloc(bbr));
3316 }
3317 
3318 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3319 static struct bbr_sendmap *
3320 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3321 {
3322 	struct bbr_sendmap *rsm;
3323 
3324 	if (limit_type) {
3325 		/* currently there is only one limit type */
3326 		if (V_tcp_map_split_limit > 0 &&
3327 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3328 			BBR_STAT_INC(bbr_split_limited);
3329 			if (!bbr->alloc_limit_reported) {
3330 				bbr->alloc_limit_reported = 1;
3331 				BBR_STAT_INC(bbr_alloc_limited_conns);
3332 			}
3333 			return (NULL);
3334 		}
3335 	}
3336 
3337 	/* allocate and mark in the limit type, if set */
3338 	rsm = bbr_alloc(bbr);
3339 	if (rsm != NULL && limit_type) {
3340 		rsm->r_limit_type = limit_type;
3341 		bbr->r_ctl.rc_num_split_allocs++;
3342 	}
3343 	return (rsm);
3344 }
3345 
3346 static void
3347 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3348 {
3349 	if (rsm->r_limit_type) {
3350 		/* currently there is only one limit type */
3351 		bbr->r_ctl.rc_num_split_allocs--;
3352 	}
3353 	if (rsm->r_is_smallmap)
3354 		bbr->r_ctl.rc_num_small_maps_alloced--;
3355 	if (bbr->r_ctl.rc_tlp_send == rsm)
3356 		bbr->r_ctl.rc_tlp_send = NULL;
3357 	if (bbr->r_ctl.rc_resend == rsm) {
3358 		bbr->r_ctl.rc_resend = NULL;
3359 	}
3360 	if (bbr->r_ctl.rc_next == rsm)
3361 		bbr->r_ctl.rc_next = NULL;
3362 	if (bbr->r_ctl.rc_sacklast == rsm)
3363 		bbr->r_ctl.rc_sacklast = NULL;
3364 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3365 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3366 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3367 		rsm->r_limit_type = 0;
3368 		bbr->r_ctl.rc_free_cnt++;
3369 		return;
3370 	}
3371 	bbr->r_ctl.rc_num_maps_alloced--;
3372 	uma_zfree(bbr_zone, rsm);
3373 }
3374 
3375 /*
3376  * Returns the BDP.
3377  */
3378 static uint64_t
3379 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3380 	/*
3381 	 * Calculate the bytes in flight needed given the bw (in bytes per
3382 	 * second) and the specifyed rtt in useconds. We need to put out the
3383 	 * returned value per RTT to match that rate. Gain will normally
3384 	 * raise it up from there.
3385 	 *
3386 	 * This should not overflow as long as the bandwidth is below 1
3387 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3388 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3389 	 */
3390 	uint64_t usec_per_sec;
3391 
3392 	usec_per_sec = USECS_IN_SECOND;
3393 	return ((rtt * bw) / usec_per_sec);
3394 }
3395 
3396 /*
3397  * Return the initial cwnd.
3398  */
3399 static uint32_t
3400 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3401 {
3402 	uint32_t i_cwnd;
3403 
3404 	if (bbr->rc_init_win) {
3405 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3406 	} else if (V_tcp_initcwnd_segments)
3407 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3408 		    max(2 * tp->t_maxseg, 14600));
3409 	else if (V_tcp_do_rfc3390)
3410 		i_cwnd = min(4 * tp->t_maxseg,
3411 		    max(2 * tp->t_maxseg, 4380));
3412 	else {
3413 		/* Per RFC5681 Section 3.1 */
3414 		if (tp->t_maxseg > 2190)
3415 			i_cwnd = 2 * tp->t_maxseg;
3416 		else if (tp->t_maxseg > 1095)
3417 			i_cwnd = 3 * tp->t_maxseg;
3418 		else
3419 			i_cwnd = 4 * tp->t_maxseg;
3420 	}
3421 	return (i_cwnd);
3422 }
3423 
3424 /*
3425  * Given a specified gain, return the target
3426  * cwnd based on that gain.
3427  */
3428 static uint32_t
3429 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3430 {
3431 	uint64_t bdp, rtt;
3432 	uint32_t cwnd;
3433 
3434 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3435 	    (bbr_get_full_bw(bbr) == 0)) {
3436 		/* No measurements yet */
3437 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3438 	}
3439 	/*
3440 	 * Get bytes per RTT needed (rttProp is normally in
3441 	 * bbr_cwndtarget_rtt_touse)
3442 	 */
3443 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3444 	/* Get the bdp from the two values */
3445 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3446 	/* Now apply the gain */
3447 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3448 
3449 	return (cwnd);
3450 }
3451 
3452 static uint32_t
3453 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3454 {
3455 	uint32_t cwnd, mss;
3456 
3457 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3458 	/* Get the base cwnd with gain rounded to a mss */
3459 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3460 	/*
3461 	 * Add in N (2 default since we do not have a
3462 	 * fq layer to trap packets in) quanta's per the I-D
3463 	 * section 4.2.3.2 quanta adjust.
3464 	 */
3465 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3466 	if (bbr->rc_use_google) {
3467 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3468 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3469 			/*
3470 			 * The linux implementation adds
3471 			 * an extra 2 x mss in gain cycle which
3472 			 * is documented no-where except in the code.
3473 			 * so we add more for Neal undocumented feature
3474 			 */
3475 			cwnd += 2 * mss;
3476 		}
3477  		if ((cwnd / mss) & 0x1) {
3478 			/* Round up for odd num mss */
3479 			cwnd += mss;
3480 		}
3481 	}
3482 	/* Are we below the min cwnd? */
3483 	if (cwnd < get_min_cwnd(bbr))
3484 		return (get_min_cwnd(bbr));
3485 	return (cwnd);
3486 }
3487 
3488 static uint16_t
3489 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3490 {
3491 	if (gain < 1)
3492 		gain = 1;
3493 	return (gain);
3494 }
3495 
3496 static uint32_t
3497 bbr_get_header_oh(struct tcp_bbr *bbr)
3498 {
3499 	int seg_oh;
3500 
3501 	seg_oh = 0;
3502 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3503 		/* Do we include TCP overhead? */
3504 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3505 	}
3506 	if (bbr->r_ctl.rc_inc_ip_oh) {
3507 		/* Do we include IP overhead? */
3508 #ifdef INET6
3509 		if (bbr->r_is_v6) {
3510 			seg_oh += sizeof(struct ip6_hdr);
3511 		} else
3512 #endif
3513 		{
3514 
3515 #ifdef INET
3516 			seg_oh += sizeof(struct ip);
3517 #endif
3518 		}
3519 	}
3520 	if (bbr->r_ctl.rc_inc_enet_oh) {
3521 		/* Do we include the ethernet overhead?  */
3522 		seg_oh += sizeof(struct ether_header);
3523 	}
3524 	return(seg_oh);
3525 }
3526 
3527 static uint32_t
3528 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3529 {
3530 	uint64_t divor, res, tim;
3531 
3532 	if (useconds_time == 0)
3533 		return (0);
3534 	gain = bbr_gain_adjust(bbr, gain);
3535 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3536 	tim = useconds_time;
3537 	res = (tim * bw * gain) / divor;
3538 	if (res == 0)
3539 		res = 1;
3540 	return ((uint32_t)res);
3541 }
3542 
3543 /*
3544  * Given a gain and a length return the delay in useconds that
3545  * should be used to evenly space out packets
3546  * on the connection (based on the gain factor).
3547  */
3548 static uint32_t
3549 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3550 {
3551 	uint64_t bw, lentim, res;
3552 	uint32_t usecs, srtt, over = 0;
3553 	uint32_t seg_oh, num_segs, maxseg;
3554 
3555 	if (len == 0)
3556 		return (0);
3557 
3558 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3559 	num_segs = (len + maxseg - 1) / maxseg;
3560 	if (bbr->rc_use_google == 0) {
3561 		seg_oh = bbr_get_header_oh(bbr);
3562 		len += (num_segs * seg_oh);
3563 	}
3564 	gain = bbr_gain_adjust(bbr, gain);
3565 	bw = bbr_get_bw(bbr);
3566 	if (bbr->rc_use_google) {
3567 		uint64_t cbw;
3568 
3569 		/*
3570 		 * Reduce the b/w by the google discount
3571 		 * factor 10 = 1%.
3572 		 */
3573 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3574 		cbw /= (uint64_t)1000;
3575 		/* We don't apply a discount if it results in 0 */
3576 		if (cbw > 0)
3577 			bw = cbw;
3578 	}
3579 	lentim = ((uint64_t)len *
3580 		  (uint64_t)USECS_IN_SECOND *
3581 		  (uint64_t)BBR_UNIT);
3582 	res = lentim / ((uint64_t)gain * bw);
3583 	if (res == 0)
3584 		res = 1;
3585 	usecs = (uint32_t)res;
3586 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3587 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3588 	    (bbr->rc_use_google == 0) &&
3589 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3590 		/*
3591 		 * We cannot let the delay be more than 1/2 the srtt time.
3592 		 * Otherwise we cannot pace out or send properly.
3593 		 */
3594 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3595 		BBR_STAT_INC(bbr_hpts_min_time);
3596 	}
3597 	if (!nolog)
3598 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3599 	return (usecs);
3600 }
3601 
3602 static void
3603 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3604 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3605 {
3606 	uint64_t bw;
3607 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3608 	int32_t meth;
3609 
3610 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3611 
3612 #ifdef STATS
3613 	if ((tp->t_flags & TF_GPUTINPROG) &&
3614 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3615 		/*
3616 		 * Strech acks and compressed acks will cause this to
3617 		 * oscillate but we are doing it the same way as the main
3618 		 * stack so it will be compariable (though possibly not
3619 		 * ideal).
3620 		 */
3621 		int32_t cgput;
3622 		int64_t gput, time_stamp;
3623 
3624 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3625 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3626 		cgput = gput / time_stamp;
3627 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3628 					 cgput);
3629 		if (tp->t_stats_gput_prev > 0)
3630 			stats_voi_update_abs_s32(tp->t_stats,
3631 						 VOI_TCP_GPUT_ND,
3632 						 ((gput - tp->t_stats_gput_prev) * 100) /
3633 						 tp->t_stats_gput_prev);
3634 		tp->t_flags &= ~TF_GPUTINPROG;
3635 		tp->t_stats_gput_prev = cgput;
3636 	}
3637 #endif
3638 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3639 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3640 		/* We don't change anything in probe-rtt */
3641 		return;
3642 	}
3643 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3644 	saved_bytes = bytes_this_ack;
3645 	bytes_this_ack += sack_changed;
3646 	if (bytes_this_ack > prev_acked) {
3647 		bytes_this_ack -= prev_acked;
3648 		/*
3649 		 * A byte ack'd gives us a full mss
3650 		 * to be like linux i.e. they count packets.
3651 		 */
3652 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3653 			bytes_this_ack = maxseg;
3654 	} else {
3655 		/* Unlikely */
3656 		bytes_this_ack = 0;
3657 	}
3658 	cwnd = tp->snd_cwnd;
3659 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3660 	if (bw)
3661 		target_cwnd = bbr_get_target_cwnd(bbr,
3662 						  bw,
3663 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3664 	else
3665 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3666 	if (IN_RECOVERY(tp->t_flags) &&
3667 	    (bbr->bbr_prev_in_rec == 0)) {
3668 		/*
3669 		 * We are entering recovery and
3670 		 * thus packet conservation.
3671 		 */
3672 		bbr->pkt_conservation = 1;
3673 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3674 		cwnd = ctf_flight_size(tp,
3675 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3676 			bytes_this_ack;
3677 	}
3678 	if (IN_RECOVERY(tp->t_flags)) {
3679 		uint32_t flight;
3680 
3681 		bbr->bbr_prev_in_rec = 1;
3682 		if (cwnd > losses) {
3683 			cwnd -= losses;
3684 			if (cwnd < maxseg)
3685 				cwnd = maxseg;
3686 		} else
3687 			cwnd = maxseg;
3688 		flight = ctf_flight_size(tp,
3689 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3690 		bbr_log_type_cwndupd(bbr, flight, 0,
3691 				     losses, 10, 0, 0, line);
3692 		if (bbr->pkt_conservation) {
3693 			uint32_t time_in;
3694 
3695 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3696 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3697 			else
3698 				time_in = 0;
3699 
3700 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3701 				/* Clear packet conservation after an rttProp */
3702 				bbr->pkt_conservation = 0;
3703 			} else {
3704 				if ((flight + bytes_this_ack) > cwnd)
3705 					cwnd = flight + bytes_this_ack;
3706 				if (cwnd < get_min_cwnd(bbr))
3707 					cwnd = get_min_cwnd(bbr);
3708 				tp->snd_cwnd = cwnd;
3709 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3710 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3711 				return;
3712 			}
3713 		}
3714 	} else
3715 		bbr->bbr_prev_in_rec = 0;
3716 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3717 		bbr->r_ctl.restrict_growth--;
3718 		if (bytes_this_ack > maxseg)
3719 			bytes_this_ack = maxseg;
3720 	}
3721 	if (bbr->rc_filled_pipe) {
3722 		/*
3723 		 * Here we have exited startup and filled the pipe. We will
3724 		 * thus allow the cwnd to shrink to the target. We hit here
3725 		 * mostly.
3726 		 */
3727 		uint32_t s_cwnd;
3728 
3729 		meth = 2;
3730 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3731 		if (s_cwnd > cwnd)
3732 			cwnd = s_cwnd;
3733 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3734 			cwnd = s_cwnd;
3735 	} else {
3736 		/*
3737 		 * Here we are still in startup, we increase cwnd by what
3738 		 * has been acked.
3739 		 */
3740 		if ((cwnd < target_cwnd) ||
3741 		    (bbr->rc_past_init_win == 0)) {
3742 			meth = 3;
3743 			cwnd += bytes_this_ack;
3744 		} else {
3745 			/*
3746 			 * Method 4 means we are at target so no gain in
3747 			 * startup and past the initial window.
3748 			 */
3749 			meth = 4;
3750 		}
3751 	}
3752 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3753 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3754 }
3755 
3756 static void
3757 tcp_bbr_partialack(struct tcpcb *tp)
3758 {
3759 	struct tcp_bbr *bbr;
3760 
3761 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3762 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3763 	if (ctf_flight_size(tp,
3764 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3765 	    tp->snd_cwnd) {
3766 		bbr->r_wanted_output = 1;
3767 	}
3768 }
3769 
3770 static void
3771 bbr_post_recovery(struct tcpcb *tp)
3772 {
3773 	struct tcp_bbr *bbr;
3774 	uint32_t  flight;
3775 
3776 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3777 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3778 	/*
3779 	 * Here we just exit recovery.
3780 	 */
3781 	EXIT_RECOVERY(tp->t_flags);
3782 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3783 	bbr->r_recovery_bw = 0;
3784 	tp->snd_recover = tp->snd_una;
3785 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3786 	bbr->pkt_conservation = 0;
3787 	if (bbr->rc_use_google == 0) {
3788 		/*
3789 		 * For non-google mode lets
3790 		 * go ahead and make sure we clear
3791 		 * the recovery state so if we
3792 		 * bounce back in to recovery we
3793 		 * will do PC.
3794 		 */
3795 		bbr->bbr_prev_in_rec = 0;
3796 	}
3797 	bbr_log_type_exit_rec(bbr);
3798 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3799 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3800 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3801 	} else {
3802 		/* For probe-rtt case lets fix up its saved_cwnd */
3803 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3804 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3805 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3806 		}
3807 	}
3808 	flight = ctf_flight_size(tp,
3809 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3810 	if ((bbr->rc_use_google == 0) &&
3811 	    bbr_do_red) {
3812 		uint64_t val, lr2use;
3813 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3814 		uint32_t *cwnd_p;
3815 
3816 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3817 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3818 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3819 			ratio = (uint32_t)val;
3820 		} else
3821 			ratio = 1000;
3822 
3823 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3824 				     bbr->r_ctl.recovery_lr, 21,
3825 				     ratio,
3826 				     bbr->r_ctl.rc_red_cwnd_pe,
3827 				     __LINE__);
3828 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3829 			goto done;
3830 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3831 		     bbr_prtt_slam_cwnd) ||
3832 		    (bbr_sub_drain_slam_cwnd &&
3833 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3834 		     bbr->rc_hit_state_1 &&
3835 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3836 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3837 		     bbr_slam_cwnd_in_main_drain)) {
3838 			/*
3839 			 * Here we must poke at the saved cwnd
3840 			 * as well as the cwnd.
3841 			 */
3842 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3843 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3844 		} else {
3845  			cwnd = tp->snd_cwnd;
3846 			cwnd_p = &tp->snd_cwnd;
3847 		}
3848 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3849 		/* Add the overall lr with the recovery lr */
3850 		if (bbr->r_ctl.rc_lost == 0)
3851 			lr2use = 0;
3852 		else if (bbr->r_ctl.rc_delivered == 0)
3853 			lr2use = 1000;
3854 		else {
3855 			lr2use = bbr->r_ctl.rc_lost * 1000;
3856 			lr2use /= bbr->r_ctl.rc_delivered;
3857 		}
3858 		lr2use += bbr->r_ctl.recovery_lr;
3859 		acks_inflight = (flight / (maxseg * 2));
3860 		if (bbr_red_scale) {
3861 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3862 			lr2use /= bbr_red_scale;
3863 			if ((bbr_red_growth_restrict) &&
3864 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3865 			    bbr->r_ctl.restrict_growth += acks_inflight;
3866 		}
3867 		if (lr2use) {
3868 			val = (uint64_t)cwnd * lr2use;
3869 			val /= 1000;
3870 			if (cwnd > val)
3871 				newcwnd = roundup((cwnd - val), maxseg);
3872 			else
3873 				newcwnd = maxseg;
3874 		} else {
3875 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3876 			val /= (uint64_t)bbr_red_div;
3877 			newcwnd = roundup((uint32_t)val, maxseg);
3878 		}
3879 		/* with standard delayed acks how many acks can I expect? */
3880 		if (bbr_drop_limit == 0) {
3881 			/*
3882 			 * Anticpate how much we will
3883 			 * raise the cwnd based on the acks.
3884 			 */
3885 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3886 				/* We do enforce the min (with the acks) */
3887 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3888 			}
3889 		} else {
3890 			/*
3891 			 * A strict drop limit of N is inplace
3892 			 */
3893 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3894 				newcwnd = bbr_drop_limit * maxseg;
3895 			}
3896 		}
3897 		/* For the next N acks do we restrict the growth */
3898 		*cwnd_p = newcwnd;
3899 		if (tp->snd_cwnd > newcwnd)
3900 			tp->snd_cwnd = newcwnd;
3901 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3902 				     (uint32_t)lr2use,
3903 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3904 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3905 	}
3906 done:
3907 	bbr->r_ctl.recovery_lr = 0;
3908 	if (flight <= tp->snd_cwnd) {
3909 		bbr->r_wanted_output = 1;
3910 	}
3911 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3912 }
3913 
3914 static void
3915 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3916 {
3917 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3918 	/* Limit the drop in b/w to 1/2 our current filter. */
3919 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3920 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3921 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3922 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3923 	tcp_bbr_tso_size_check(bbr, cts);
3924 }
3925 
3926 static void
3927 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3928 {
3929 	struct tcp_bbr *bbr;
3930 
3931 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3932 #ifdef STATS
3933 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3934 #endif
3935 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3936 	switch (type) {
3937 	case CC_NDUPACK:
3938 		if (!IN_RECOVERY(tp->t_flags)) {
3939 			tp->snd_recover = tp->snd_max;
3940 			/* Start a new epoch */
3941 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3942 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3943 				/*
3944 				 * Move forward the lt epoch
3945 				 * so it won't count the truncated
3946 				 * epoch.
3947 				 */
3948 				bbr->r_ctl.rc_lt_epoch++;
3949 			}
3950 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3951 				/*
3952 				 * Just like the policer detection code
3953 				 * if we are in startup we must push
3954 				 * forward the last startup epoch
3955 				 * to hide the truncated PE.
3956 				 */
3957 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3958 			}
3959 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3960 			ENTER_RECOVERY(tp->t_flags);
3961 			bbr->rc_tlp_rtx_out = 0;
3962 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3963 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3964 			if (tcp_in_hpts(bbr->rc_inp) &&
3965 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3966 				/*
3967 				 * When we enter recovery, we need to restart
3968 				 * any timers. This may mean we gain an agg
3969 				 * early, which will be made up for at the last
3970 				 * rxt out.
3971 				 */
3972 				bbr->rc_timer_first = 1;
3973 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3974 			}
3975 			/*
3976 			 * Calculate a new cwnd based on to the current
3977 			 * delivery rate with no gain. We get the bdp
3978 			 * without gaining it up like we normally would and
3979 			 * we use the last cur_del_rate.
3980 			 */
3981 			if ((bbr->rc_use_google == 0) &&
3982 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3983 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3984 				tp->snd_cwnd = ctf_flight_size(tp,
3985 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3986 					(tp->t_maxseg - bbr->rc_last_options);
3987 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3988 					/* We always gate to min cwnd */
3989 					tp->snd_cwnd = get_min_cwnd(bbr);
3990 				}
3991 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3992 			}
3993 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3994 		}
3995 		break;
3996 	case CC_RTO_ERR:
3997 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
3998 		/* RTO was unnecessary, so reset everything. */
3999 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
4000 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
4001 			tp->snd_cwnd = tp->snd_cwnd_prev;
4002 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
4003 			tp->snd_recover = tp->snd_recover_prev;
4004 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
4005 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
4006 		}
4007 		tp->t_badrxtwin = 0;
4008 		break;
4009 	}
4010 }
4011 
4012 /*
4013  * Indicate whether this ack should be delayed.  We can delay the ack if
4014  * following conditions are met:
4015  *	- There is no delayed ack timer in progress.
4016  *	- Our last ack wasn't a 0-sized window. We never want to delay
4017  *	  the ack that opens up a 0-sized window.
4018  *	- LRO wasn't used for this segment. We make sure by checking that the
4019  *	  segment size is not larger than the MSS.
4020  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4021  *	  connection.
4022  *	- The data being acked is less than a full segment (a stretch ack
4023  *        of more than a segment we should ack.
4024  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4025  */
4026 #define DELAY_ACK(tp, bbr, nsegs)				\
4027 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4028 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4029 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4030 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4031 
4032 /*
4033  * Return the lowest RSM in the map of
4034  * packets still in flight that is not acked.
4035  * This should normally find on the first one
4036  * since we remove packets from the send
4037  * map after they are marked ACKED.
4038  */
4039 static struct bbr_sendmap *
4040 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4041 {
4042 	struct bbr_sendmap *rsm;
4043 
4044 	/*
4045 	 * Walk the time-order transmitted list looking for an rsm that is
4046 	 * not acked. This will be the one that was sent the longest time
4047 	 * ago that is still outstanding.
4048 	 */
4049 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4050 		if (rsm->r_flags & BBR_ACKED) {
4051 			continue;
4052 		}
4053 		goto finish;
4054 	}
4055 finish:
4056 	return (rsm);
4057 }
4058 
4059 static struct bbr_sendmap *
4060 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4061 {
4062 	struct bbr_sendmap *prsm;
4063 
4064 	/*
4065 	 * Walk the sequence order list backward until we hit and arrive at
4066 	 * the highest seq not acked. In theory when this is called it
4067 	 * should be the last segment (which it was not).
4068 	 */
4069 	prsm = rsm;
4070 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4071 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4072 			continue;
4073 		}
4074 		return (prsm);
4075 	}
4076 	return (NULL);
4077 }
4078 
4079 /*
4080  * Returns to the caller the number of microseconds that
4081  * the packet can be outstanding before we think we
4082  * should have had an ack returned.
4083  */
4084 static uint32_t
4085 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4086 {
4087 	/*
4088 	 * lro is the flag we use to determine if we have seen reordering.
4089 	 * If it gets set we have seen reordering. The reorder logic either
4090 	 * works in one of two ways:
4091 	 *
4092 	 * If reorder-fade is configured, then we track the last time we saw
4093 	 * re-ordering occur. If we reach the point where enough time as
4094 	 * passed we no longer consider reordering has occuring.
4095 	 *
4096 	 * Or if reorder-face is 0, then once we see reordering we consider
4097 	 * the connection to alway be subject to reordering and just set lro
4098 	 * to 1.
4099 	 *
4100 	 * In the end if lro is non-zero we add the extra time for
4101 	 * reordering in.
4102 	 */
4103 	int32_t lro;
4104 	uint32_t thresh, t_rxtcur;
4105 
4106 	if (srtt == 0)
4107 		srtt = 1;
4108 	if (bbr->r_ctl.rc_reorder_ts) {
4109 		if (bbr->r_ctl.rc_reorder_fade) {
4110 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4111 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4112 				if (lro == 0) {
4113 					/*
4114 					 * No time as passed since the last
4115 					 * reorder, mark it as reordering.
4116 					 */
4117 					lro = 1;
4118 				}
4119 			} else {
4120 				/* Negative time? */
4121 				lro = 0;
4122 			}
4123 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4124 				/* Turn off reordering seen too */
4125 				bbr->r_ctl.rc_reorder_ts = 0;
4126 				lro = 0;
4127 			}
4128 		} else {
4129 			/* Reodering does not fade */
4130 			lro = 1;
4131 		}
4132 	} else {
4133 		lro = 0;
4134 	}
4135 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4136 	if (lro) {
4137 		/* It must be set, if not you get 1/4 rtt */
4138 		if (bbr->r_ctl.rc_reorder_shift)
4139 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4140 		else
4141 			thresh += (srtt >> 2);
4142 	} else {
4143 		thresh += 1000;
4144 	}
4145 	/* We don't let the rack timeout be above a RTO */
4146 	if ((bbr->rc_tp)->t_srtt == 0)
4147 		t_rxtcur = BBR_INITIAL_RTO;
4148 	else
4149 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4150 	if (thresh > t_rxtcur) {
4151 		thresh = t_rxtcur;
4152 	}
4153 	/* And we don't want it above the RTO max either */
4154 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4155 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4156 	}
4157 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4158 	return (thresh);
4159 }
4160 
4161 /*
4162  * Return to the caller the amount of time in mico-seconds
4163  * that should be used for the TLP timer from the last
4164  * send time of this packet.
4165  */
4166 static uint32_t
4167 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4168     struct bbr_sendmap *rsm, uint32_t srtt,
4169     uint32_t cts)
4170 {
4171 	uint32_t thresh, len, maxseg, t_rxtcur;
4172 	struct bbr_sendmap *prsm;
4173 
4174 	if (srtt == 0)
4175 		srtt = 1;
4176 	if (bbr->rc_tlp_threshold)
4177 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4178 	else
4179 		thresh = (srtt * 2);
4180 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4181 	/* Get the previous sent packet, if any  */
4182 	len = rsm->r_end - rsm->r_start;
4183 
4184 	/* 2.1 behavior */
4185 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4186 	if (prsm && (len <= maxseg)) {
4187 		/*
4188 		 * Two packets outstanding, thresh should be (2*srtt) +
4189 		 * possible inter-packet delay (if any).
4190 		 */
4191 		uint32_t inter_gap = 0;
4192 		int idx, nidx;
4193 
4194 		idx = rsm->r_rtr_cnt - 1;
4195 		nidx = prsm->r_rtr_cnt - 1;
4196 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4197 			/* Yes it was sent later (or at the same time) */
4198 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4199 		}
4200 		thresh += inter_gap;
4201 	} else if (len <= maxseg) {
4202 		/*
4203 		 * Possibly compensate for delayed-ack.
4204 		 */
4205 		uint32_t alt_thresh;
4206 
4207 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4208 		if (alt_thresh > thresh)
4209 			thresh = alt_thresh;
4210 	}
4211 	/* Not above the current  RTO */
4212 	if (tp->t_srtt == 0)
4213 		t_rxtcur = BBR_INITIAL_RTO;
4214 	else
4215 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4216 
4217 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4218 	/* Not above an RTO */
4219 	if (thresh > t_rxtcur) {
4220 		thresh = t_rxtcur;
4221 	}
4222 	/* Not above a RTO max */
4223 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4224 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4225 	}
4226 	/* And now apply the user TLP min */
4227 	if (thresh < bbr_tlp_min) {
4228 		thresh = bbr_tlp_min;
4229 	}
4230 	return (thresh);
4231 }
4232 
4233 /*
4234  * Return one of three RTTs to use (in microseconds).
4235  */
4236 static __inline uint32_t
4237 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4238 {
4239 	uint32_t f_rtt;
4240 	uint32_t srtt;
4241 
4242 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4243 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4244 		/* We have no rtt at all */
4245 		if (bbr->rc_tp->t_srtt == 0)
4246 			f_rtt = BBR_INITIAL_RTO;
4247 		else
4248 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4249 		/*
4250 		 * Since we don't know how good the rtt is apply a
4251 		 * delayed-ack min
4252 		 */
4253 		if (f_rtt < bbr_delayed_ack_time) {
4254 			f_rtt = bbr_delayed_ack_time;
4255 		}
4256 	}
4257 	/* Take the filter version or last measured pkt-rtt */
4258 	if (rtt_type == BBR_RTT_PROP) {
4259 		srtt = f_rtt;
4260 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4261 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4262 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4263 		} else {
4264 			/* No pkt rtt yet */
4265 			srtt = f_rtt;
4266 		}
4267 	} else if (rtt_type == BBR_RTT_RACK) {
4268 		srtt = bbr->r_ctl.rc_last_rtt;
4269 		/* We need to add in any internal delay for our timer */
4270 		if (bbr->rc_ack_was_delayed)
4271 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4272 	} else if (rtt_type == BBR_SRTT) {
4273 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4274 	} else {
4275 		/* TSNH */
4276 		srtt = f_rtt;
4277 #ifdef BBR_INVARIANTS
4278 		panic("Unknown rtt request type %d", rtt_type);
4279 #endif
4280 	}
4281 	return (srtt);
4282 }
4283 
4284 static int
4285 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4286 {
4287 	uint32_t thresh;
4288 
4289 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4290 				      cts, rsm);
4291 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4292 		/* It is lost (past time) */
4293 		return (1);
4294 	}
4295 	return (0);
4296 }
4297 
4298 /*
4299  * Return a sendmap if we need to retransmit something.
4300  */
4301 static struct bbr_sendmap *
4302 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4303 {
4304 	/*
4305 	 * Check to see that we don't need to fall into recovery. We will
4306 	 * need to do so if our oldest transmit is past the time we should
4307 	 * have had an ack.
4308 	 */
4309 
4310 	struct bbr_sendmap *rsm;
4311 	int32_t idx;
4312 
4313 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4314 		/* Nothing outstanding that we know of */
4315 		return (NULL);
4316 	}
4317 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4318 	if (rsm == NULL) {
4319 		/* Nothing in the transmit map */
4320 		return (NULL);
4321 	}
4322 	if (tp->t_flags & TF_SENTFIN) {
4323 		/* Fin restricted, don't find anything once a fin is sent */
4324 		return (NULL);
4325 	}
4326 	if (rsm->r_flags & BBR_ACKED) {
4327 		/*
4328 		 * Ok the first one is acked (this really should not happen
4329 		 * since we remove the from the tmap once they are acked)
4330 		 */
4331 		rsm = bbr_find_lowest_rsm(bbr);
4332 		if (rsm == NULL)
4333 			return (NULL);
4334 	}
4335 	idx = rsm->r_rtr_cnt - 1;
4336 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4337 		/* Send timestamp is the same or less? can't be ready */
4338 		return (NULL);
4339 	}
4340 	/* Get our RTT time */
4341 	if (bbr_is_lost(bbr, rsm, cts) &&
4342 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4343 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4344 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4345 			rsm->r_flags |= BBR_MARKED_LOST;
4346 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4347 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4348 		}
4349 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4350 #ifdef BBR_INVARIANTS
4351 		if ((rsm->r_end - rsm->r_start) == 0)
4352 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4353 #endif
4354 		return (rsm);
4355 	}
4356 	return (NULL);
4357 }
4358 
4359 /*
4360  * RACK Timer, here we simply do logging and house keeping.
4361  * the normal bbr_output_wtime() function will call the
4362  * appropriate thing to check if we need to do a RACK retransmit.
4363  * We return 1, saying don't proceed with bbr_output_wtime only
4364  * when all timers have been stopped (destroyed PCB?).
4365  */
4366 static int
4367 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4368 {
4369 	/*
4370 	 * This timer simply provides an internal trigger to send out data.
4371 	 * The check_recovery_mode call will see if there are needed
4372 	 * retransmissions, if so we will enter fast-recovery. The output
4373 	 * call may or may not do the same thing depending on sysctl
4374 	 * settings.
4375 	 */
4376 	uint32_t lost;
4377 
4378 	if (bbr->rc_all_timers_stopped) {
4379 		return (1);
4380 	}
4381 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4382 		/* Its not time yet */
4383 		return (0);
4384 	}
4385 	BBR_STAT_INC(bbr_to_tot);
4386 	lost = bbr->r_ctl.rc_lost;
4387 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4388 		bbr_set_state(tp, bbr, 0);
4389 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4390 	if (bbr->r_ctl.rc_resend == NULL) {
4391 		/* Lets do the check here */
4392 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4393 	}
4394 	if (bbr_policer_call_from_rack_to)
4395 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4396 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4397 	return (0);
4398 }
4399 
4400 static __inline void
4401 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4402 {
4403 	int idx;
4404 
4405 	nrsm->r_start = start;
4406 	nrsm->r_end = rsm->r_end;
4407 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4408 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4409 	nrsm->r_flags = rsm->r_flags;
4410 	/* We don't transfer forward the SYN flag */
4411 	nrsm->r_flags &= ~BBR_HAS_SYN;
4412 	/* We move forward the FIN flag, not that this should happen */
4413 	rsm->r_flags &= ~BBR_HAS_FIN;
4414 	nrsm->r_dupack = rsm->r_dupack;
4415 	nrsm->r_rtr_bytes = 0;
4416 	nrsm->r_is_gain = rsm->r_is_gain;
4417 	nrsm->r_is_drain = rsm->r_is_drain;
4418 	nrsm->r_delivered = rsm->r_delivered;
4419 	nrsm->r_ts_valid = rsm->r_ts_valid;
4420 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4421 	nrsm->r_del_time = rsm->r_del_time;
4422 	nrsm->r_app_limited = rsm->r_app_limited;
4423 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4424 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4425 	/* We split a piece the lower section looses any just_ret flag. */
4426 	nrsm->r_bbr_state = rsm->r_bbr_state;
4427 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4428 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4429 	}
4430 	rsm->r_end = nrsm->r_start;
4431 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4432 	idx /= 8;
4433 	/* Check if we got too small */
4434 	if ((rsm->r_is_smallmap == 0) &&
4435 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4436 		bbr->r_ctl.rc_num_small_maps_alloced++;
4437 		rsm->r_is_smallmap = 1;
4438 	}
4439 	/* Check the new one as well */
4440 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4441 		bbr->r_ctl.rc_num_small_maps_alloced++;
4442 		nrsm->r_is_smallmap = 1;
4443 	}
4444 }
4445 
4446 static int
4447 bbr_sack_mergable(struct bbr_sendmap *at,
4448 		  uint32_t start, uint32_t end)
4449 {
4450 	/*
4451 	 * Given a sack block defined by
4452 	 * start and end, and a current position
4453 	 * at. Return 1 if either side of at
4454 	 * would show that the block is mergable
4455 	 * to that side. A block to be mergable
4456 	 * must have overlap with the start/end
4457 	 * and be in the SACK'd state.
4458 	 */
4459 	struct bbr_sendmap *l_rsm;
4460 	struct bbr_sendmap *r_rsm;
4461 
4462 	/* first get the either side blocks */
4463 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4464 	r_rsm = TAILQ_NEXT(at, r_next);
4465 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4466 		/* Potentially mergeable */
4467 		if ((l_rsm->r_end == start) ||
4468 		    (SEQ_LT(start, l_rsm->r_end) &&
4469 		     SEQ_GT(end, l_rsm->r_end))) {
4470 			    /*
4471 			     * map blk   |------|
4472 			     * sack blk         |------|
4473 			     * <or>
4474 			     * map blk   |------|
4475 			     * sack blk      |------|
4476 			     */
4477 			    return (1);
4478 		    }
4479 	}
4480 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4481 		/* Potentially mergeable */
4482 		if ((r_rsm->r_start == end) ||
4483 		    (SEQ_LT(start, r_rsm->r_start) &&
4484 		     SEQ_GT(end, r_rsm->r_start))) {
4485 			/*
4486 			 * map blk          |---------|
4487 			 * sack blk    |----|
4488 			 * <or>
4489 			 * map blk          |---------|
4490 			 * sack blk    |-------|
4491 			 */
4492 			return (1);
4493 		}
4494 	}
4495 	return (0);
4496 }
4497 
4498 static struct bbr_sendmap *
4499 bbr_merge_rsm(struct tcp_bbr *bbr,
4500 	      struct bbr_sendmap *l_rsm,
4501 	      struct bbr_sendmap *r_rsm)
4502 {
4503 	/*
4504 	 * We are merging two ack'd RSM's,
4505 	 * the l_rsm is on the left (lower seq
4506 	 * values) and the r_rsm is on the right
4507 	 * (higher seq value). The simplest way
4508 	 * to merge these is to move the right
4509 	 * one into the left. I don't think there
4510 	 * is any reason we need to try to find
4511 	 * the oldest (or last oldest retransmitted).
4512 	 */
4513 	l_rsm->r_end = r_rsm->r_end;
4514 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4515 		l_rsm->r_dupack = r_rsm->r_dupack;
4516 	if (r_rsm->r_rtr_bytes)
4517 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4518 	if (r_rsm->r_in_tmap) {
4519 		/* This really should not happen */
4520 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4521 	}
4522 	if (r_rsm->r_app_limited)
4523 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4524 	/* Now the flags */
4525 	if (r_rsm->r_flags & BBR_HAS_FIN)
4526 		l_rsm->r_flags |= BBR_HAS_FIN;
4527 	if (r_rsm->r_flags & BBR_TLP)
4528 		l_rsm->r_flags |= BBR_TLP;
4529 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4530 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4531 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4532 		/* This really should not happen */
4533 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4534 	}
4535 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4536 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4537 		/* Transfer the split limit to the map we free */
4538 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4539 		l_rsm->r_limit_type = 0;
4540 	}
4541 	bbr_free(bbr, r_rsm);
4542 	return(l_rsm);
4543 }
4544 
4545 /*
4546  * TLP Timer, here we simply setup what segment we want to
4547  * have the TLP expire on, the normal bbr_output_wtime() will then
4548  * send it out.
4549  *
4550  * We return 1, saying don't proceed with bbr_output_wtime only
4551  * when all timers have been stopped (destroyed PCB?).
4552  */
4553 static int
4554 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4555 {
4556 	/*
4557 	 * Tail Loss Probe.
4558 	 */
4559 	struct bbr_sendmap *rsm = NULL;
4560 	struct socket *so;
4561 	uint32_t amm;
4562 	uint32_t out, avail;
4563 	uint32_t maxseg;
4564 	int collapsed_win = 0;
4565 
4566 	if (bbr->rc_all_timers_stopped) {
4567 		return (1);
4568 	}
4569 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4570 		/* Its not time yet */
4571 		return (0);
4572 	}
4573 	if (ctf_progress_timeout_check(tp, true)) {
4574 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4575 		return (-ETIMEDOUT);	/* tcp_drop() */
4576 	}
4577 	/* Did we somehow get into persists? */
4578 	if (bbr->rc_in_persist) {
4579 		return (0);
4580 	}
4581 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4582 		bbr_set_state(tp, bbr, 0);
4583 	BBR_STAT_INC(bbr_tlp_tot);
4584 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4585 	/*
4586 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4587 	 * need to figure out how to force a full MSS segment out.
4588 	 */
4589 	so = tptosocket(tp);
4590 	avail = sbavail(&so->so_snd);
4591 	out = ctf_outstanding(tp);
4592 	if (out > tp->snd_wnd) {
4593 		/* special case, we need a retransmission */
4594 		collapsed_win = 1;
4595 		goto need_retran;
4596 	}
4597 	if (avail > out) {
4598 		/* New data is available */
4599 		amm = avail - out;
4600 		if (amm > maxseg) {
4601 			amm = maxseg;
4602 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4603 			/* not enough to fill a MTU and no-delay is off */
4604 			goto need_retran;
4605 		}
4606 		/* Set the send-new override */
4607 		if ((out + amm) <= tp->snd_wnd) {
4608 			bbr->rc_tlp_new_data = 1;
4609 		} else {
4610 			goto need_retran;
4611 		}
4612 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4613 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4614 		bbr->r_ctl.rc_tlp_send = NULL;
4615 		/* cap any slots */
4616 		BBR_STAT_INC(bbr_tlp_newdata);
4617 		goto send;
4618 	}
4619 need_retran:
4620 	/*
4621 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4622 	 * optionally the first un-acked segment.
4623 	 */
4624 	if (collapsed_win == 0) {
4625 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4626 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4627 			rsm = bbr_find_high_nonack(bbr, rsm);
4628 		}
4629 		if (rsm == NULL) {
4630 			goto restore;
4631 		}
4632 	} else {
4633 		/*
4634 		 * We must find the last segment
4635 		 * that was acceptable by the client.
4636 		 */
4637 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4638 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4639 				/* Found one */
4640 				break;
4641 			}
4642 		}
4643 		if (rsm == NULL) {
4644 			/* None? if so send the first */
4645 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4646 			if (rsm == NULL)
4647 				goto restore;
4648 		}
4649 	}
4650 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4651 		/*
4652 		 * We need to split this the last segment in two.
4653 		 */
4654 		struct bbr_sendmap *nrsm;
4655 
4656 		nrsm = bbr_alloc_full_limit(bbr);
4657 		if (nrsm == NULL) {
4658 			/*
4659 			 * We can't get memory to split, we can either just
4660 			 * not split it. Or retransmit the whole piece, lets
4661 			 * do the large send (BTLP :-) ).
4662 			 */
4663 			goto go_for_it;
4664 		}
4665 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4666 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4667 		if (rsm->r_in_tmap) {
4668 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4669 			nrsm->r_in_tmap = 1;
4670 		}
4671 		rsm->r_flags &= (~BBR_HAS_FIN);
4672 		rsm = nrsm;
4673 	}
4674 go_for_it:
4675 	bbr->r_ctl.rc_tlp_send = rsm;
4676 	bbr->rc_tlp_rtx_out = 1;
4677 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4678 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4679 		tp->t_rxtshift++;
4680 	} else {
4681 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4682 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4683 	}
4684 send:
4685 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4686 		/*
4687 		 * Can't [re]/transmit a segment we have retransmitted the
4688 		 * max times. We need the retransmit timer to take over.
4689 		 */
4690 restore:
4691 		bbr->rc_tlp_new_data = 0;
4692 		bbr->r_ctl.rc_tlp_send = NULL;
4693 		if (rsm)
4694 			rsm->r_flags &= ~BBR_TLP;
4695 		BBR_STAT_INC(bbr_tlp_retran_fail);
4696 		return (0);
4697 	} else if (rsm) {
4698 		rsm->r_flags |= BBR_TLP;
4699 	}
4700 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4701 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4702 		/*
4703 		 * We have retransmitted to many times for TLP. Switch to
4704 		 * the regular RTO timer
4705 		 */
4706 		goto restore;
4707 	}
4708 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4709 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4710 	return (0);
4711 }
4712 
4713 /*
4714  * Delayed ack Timer, here we simply need to setup the
4715  * ACK_NOW flag and remove the DELACK flag. From there
4716  * the output routine will send the ack out.
4717  *
4718  * We only return 1, saying don't proceed, if all timers
4719  * are stopped (destroyed PCB?).
4720  */
4721 static int
4722 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4723 {
4724 	if (bbr->rc_all_timers_stopped) {
4725 		return (1);
4726 	}
4727 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4728 	tp->t_flags &= ~TF_DELACK;
4729 	tp->t_flags |= TF_ACKNOW;
4730 	KMOD_TCPSTAT_INC(tcps_delack);
4731 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4732 	return (0);
4733 }
4734 
4735 /*
4736  * Here we send a KEEP-ALIVE like probe to the
4737  * peer, we do not send data.
4738  *
4739  * We only return 1, saying don't proceed, if all timers
4740  * are stopped (destroyed PCB?).
4741  */
4742 static int
4743 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4744 {
4745 	struct tcptemp *t_template;
4746 	int32_t retval = 1;
4747 
4748 	if (bbr->rc_all_timers_stopped) {
4749 		return (1);
4750 	}
4751 	if (bbr->rc_in_persist == 0)
4752 		return (0);
4753 
4754 	/*
4755 	 * Persistence timer into zero window. Force a byte to be output, if
4756 	 * possible.
4757 	 */
4758 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4759 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4760 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4761 	/*
4762 	 * Have we exceeded the user specified progress time?
4763 	 */
4764 	if (ctf_progress_timeout_check(tp, true)) {
4765 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4766 		return (-ETIMEDOUT);	/* tcp_drop() */
4767 	}
4768 	/*
4769 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4770 	 * window is closed.  After a full backoff, drop the connection if
4771 	 * the idle time (no responses to probes) reaches the maximum
4772 	 * backoff that we would use if retransmitting.
4773 	 */
4774 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4775 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4776 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4777 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4778 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4779 		return (-ETIMEDOUT);	/* tcp_drop() */
4780 	}
4781 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4782 	    tp->snd_una == tp->snd_max) {
4783 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4784 		retval = 0;
4785 		goto out;
4786 	}
4787 	/*
4788 	 * If the user has closed the socket then drop a persisting
4789 	 * connection after a much reduced timeout.
4790 	 */
4791 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4792 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4793 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4794 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4795 		return (-ETIMEDOUT);	/* tcp_drop() */
4796 	}
4797 	t_template = tcpip_maketemplate(bbr->rc_inp);
4798 	if (t_template) {
4799 		tcp_respond(tp, t_template->tt_ipgen,
4800 			    &t_template->tt_t, (struct mbuf *)NULL,
4801 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4802 		/* This sends an ack */
4803 		if (tp->t_flags & TF_DELACK)
4804 			tp->t_flags &= ~TF_DELACK;
4805 		free(t_template, M_TEMP);
4806 	}
4807 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4808 		tp->t_rxtshift++;
4809 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4810 out:
4811 	return (retval);
4812 }
4813 
4814 /*
4815  * If a keepalive goes off, we had no other timers
4816  * happening. We always return 1 here since this
4817  * routine either drops the connection or sends
4818  * out a segment with respond.
4819  */
4820 static int
4821 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4822 {
4823 	struct tcptemp *t_template;
4824 	struct inpcb *inp = tptoinpcb(tp);
4825 
4826 	if (bbr->rc_all_timers_stopped) {
4827 		return (1);
4828 	}
4829 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4830 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4831 	/*
4832 	 * Keep-alive timer went off; send something or drop connection if
4833 	 * idle for too long.
4834 	 */
4835 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4836 	if (tp->t_state < TCPS_ESTABLISHED)
4837 		goto dropit;
4838 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4839 	    tp->t_state <= TCPS_CLOSING) {
4840 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4841 			goto dropit;
4842 		/*
4843 		 * Send a packet designed to force a response if the peer is
4844 		 * up and reachable: either an ACK if the connection is
4845 		 * still alive, or an RST if the peer has closed the
4846 		 * connection due to timeout or reboot. Using sequence
4847 		 * number tp->snd_una-1 causes the transmitted zero-length
4848 		 * segment to lie outside the receive window; by the
4849 		 * protocol spec, this requires the correspondent TCP to
4850 		 * respond.
4851 		 */
4852 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4853 		t_template = tcpip_maketemplate(inp);
4854 		if (t_template) {
4855 			tcp_respond(tp, t_template->tt_ipgen,
4856 			    &t_template->tt_t, (struct mbuf *)NULL,
4857 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4858 			free(t_template, M_TEMP);
4859 		}
4860 	}
4861 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4862 	return (1);
4863 dropit:
4864 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4865 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4866 	return (-ETIMEDOUT);	/* tcp_drop() */
4867 }
4868 
4869 /*
4870  * Retransmit helper function, clear up all the ack
4871  * flags and take care of important book keeping.
4872  */
4873 static void
4874 bbr_remxt_tmr(struct tcpcb *tp)
4875 {
4876 	/*
4877 	 * The retransmit timer went off, all sack'd blocks must be
4878 	 * un-acked.
4879 	 */
4880 	struct bbr_sendmap *rsm, *trsm = NULL;
4881 	struct tcp_bbr *bbr;
4882 	uint32_t cts, lost;
4883 
4884 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4885 	cts = tcp_get_usecs(&bbr->rc_tv);
4886 	lost = bbr->r_ctl.rc_lost;
4887 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4888 		bbr_set_state(tp, bbr, 0);
4889 
4890 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4891 		if (rsm->r_flags & BBR_ACKED) {
4892 			uint32_t old_flags;
4893 
4894 			rsm->r_dupack = 0;
4895 			if (rsm->r_in_tmap == 0) {
4896 				/* We must re-add it back to the tlist */
4897 				if (trsm == NULL) {
4898 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4899 				} else {
4900 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4901 				}
4902 				rsm->r_in_tmap = 1;
4903 			}
4904 			old_flags = rsm->r_flags;
4905 			rsm->r_flags |= BBR_RXT_CLEARED;
4906 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4907 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4908 		} else {
4909 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4910 			    (rsm->r_start == tp->snd_una)) {
4911 				/*
4912 				 * Special case for TCP FO. Where
4913 				 * we sent more data beyond the snd_max.
4914 				 * We don't mark that as lost and stop here.
4915 				 */
4916 				break;
4917 			}
4918 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4919 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4920 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4921 			}
4922 			if (bbr_marks_rxt_sack_passed) {
4923 				/*
4924 				 * With this option, we will rack out
4925 				 * in 1ms increments the rest of the packets.
4926 				 */
4927 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4928 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4929 			} else {
4930 				/*
4931 				 * With this option we only mark them lost
4932 				 * and remove all sack'd markings. We will run
4933 				 * another RXT or a TLP. This will cause
4934 				 * us to eventually send more based on what
4935 				 * ack's come in.
4936 				 */
4937 				rsm->r_flags |= BBR_MARKED_LOST;
4938 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4939 				rsm->r_flags &= ~BBR_SACK_PASSED;
4940 			}
4941 		}
4942 		trsm = rsm;
4943 	}
4944 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4945 	/* Clear the count (we just un-acked them) */
4946 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4947 	bbr->rc_tlp_new_data = 0;
4948 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4949 	/* zap the behindness on a rxt */
4950 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4951 	bbr->r_agg_early_set = 0;
4952 	bbr->r_ctl.rc_agg_early = 0;
4953 	bbr->rc_tlp_rtx_out = 0;
4954 	bbr->r_ctl.rc_sacked = 0;
4955 	bbr->r_ctl.rc_sacklast = NULL;
4956 	bbr->r_timer_override = 1;
4957 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4958 }
4959 
4960 /*
4961  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4962  * we will setup to retransmit the lowest seq number outstanding.
4963  */
4964 static int
4965 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4966 {
4967 	struct inpcb *inp = tptoinpcb(tp);
4968 	int32_t rexmt;
4969 	int32_t retval = 0;
4970 	bool isipv6;
4971 
4972 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4973 	if (bbr->rc_all_timers_stopped) {
4974 		return (1);
4975 	}
4976 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4977 	    (tp->snd_una == tp->snd_max)) {
4978 		/* Nothing outstanding .. nothing to do */
4979 		return (0);
4980 	}
4981 	/*
4982 	 * Retransmission timer went off.  Message has not been acked within
4983 	 * retransmit interval.  Back off to a longer retransmit interval
4984 	 * and retransmit one segment.
4985 	 */
4986 	if (ctf_progress_timeout_check(tp, true)) {
4987 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4988 		return (-ETIMEDOUT);	/* tcp_drop() */
4989 	}
4990 	bbr_remxt_tmr(tp);
4991 	if ((bbr->r_ctl.rc_resend == NULL) ||
4992 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4993 		/*
4994 		 * If the rwnd collapsed on
4995 		 * the one we are retransmitting
4996 		 * it does not count against the
4997 		 * rxt count.
4998 		 */
4999 		tp->t_rxtshift++;
5000 	}
5001 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5002 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
5003 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
5004 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
5005 		/* XXXGL: previously t_softerror was casted to uint16_t */
5006 		MPASS(tp->t_softerror >= 0);
5007 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
5008 		return (retval);	/* tcp_drop() */
5009 	}
5010 	if (tp->t_state == TCPS_SYN_SENT) {
5011 		/*
5012 		 * If the SYN was retransmitted, indicate CWND to be limited
5013 		 * to 1 segment in cc_conn_init().
5014 		 */
5015 		tp->snd_cwnd = 1;
5016 	} else if (tp->t_rxtshift == 1) {
5017 		/*
5018 		 * first retransmit; record ssthresh and cwnd so they can be
5019 		 * recovered if this turns out to be a "bad" retransmit. A
5020 		 * retransmit is considered "bad" if an ACK for this segment
5021 		 * is received within RTT/2 interval; the assumption here is
5022 		 * that the ACK was already in flight.  See "On Estimating
5023 		 * End-to-End Network Path Properties" by Allman and Paxson
5024 		 * for more details.
5025 		 */
5026 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5027 		if (!IN_RECOVERY(tp->t_flags)) {
5028 			tp->snd_cwnd_prev = tp->snd_cwnd;
5029 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5030 			tp->snd_recover_prev = tp->snd_recover;
5031 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5032 			tp->t_flags |= TF_PREVVALID;
5033 		} else {
5034 			tp->t_flags &= ~TF_PREVVALID;
5035 		}
5036 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5037 	} else {
5038 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5039 		tp->t_flags &= ~TF_PREVVALID;
5040 	}
5041 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5042 	if ((tp->t_state == TCPS_SYN_SENT) ||
5043 	    (tp->t_state == TCPS_SYN_RECEIVED))
5044 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5045 	else
5046 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5047 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5048 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5049 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5050 	/*
5051 	 * We enter the path for PLMTUD if connection is established or, if
5052 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5053 	 * amount of data we send is very small, we could send it in couple
5054 	 * of packets and process straight to FIN. In that case we won't
5055 	 * catch ESTABLISHED state.
5056 	 */
5057 #ifdef INET6
5058 	isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
5059 #else
5060 	isipv6 = false;
5061 #endif
5062 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5063 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5064 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5065 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5066 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5067 		/*
5068 		 * Idea here is that at each stage of mtu probe (usually,
5069 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5070 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5071 		 * should take care of that.
5072 		 */
5073 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5074 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5075 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5076 		    tp->t_rxtshift % 2 == 0)) {
5077 			/*
5078 			 * Enter Path MTU Black-hole Detection mechanism: -
5079 			 * Disable Path MTU Discovery (IP "DF" bit). -
5080 			 * Reduce MTU to lower value than what we negotiated
5081 			 * with peer.
5082 			 */
5083 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5084 				/*
5085 				 * Record that we may have found a black
5086 				 * hole.
5087 				 */
5088 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5089 				/* Keep track of previous MSS. */
5090 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5091 			}
5092 			/*
5093 			 * Reduce the MSS to blackhole value or to the
5094 			 * default in an attempt to retransmit.
5095 			 */
5096 #ifdef INET6
5097 			isipv6 = bbr->r_is_v6;
5098 			if (isipv6 &&
5099 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5100 				/* Use the sysctl tuneable blackhole MSS. */
5101 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5102 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5103 			} else if (isipv6) {
5104 				/* Use the default MSS. */
5105 				tp->t_maxseg = V_tcp_v6mssdflt;
5106 				/*
5107 				 * Disable Path MTU Discovery when we switch
5108 				 * to minmss.
5109 				 */
5110 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5111 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5112 			}
5113 #endif
5114 #if defined(INET6) && defined(INET)
5115 			else
5116 #endif
5117 #ifdef INET
5118 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5119 				/* Use the sysctl tuneable blackhole MSS. */
5120 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5121 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5122 			} else {
5123 				/* Use the default MSS. */
5124 				tp->t_maxseg = V_tcp_mssdflt;
5125 				/*
5126 				 * Disable Path MTU Discovery when we switch
5127 				 * to minmss.
5128 				 */
5129 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5130 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5131 			}
5132 #endif
5133 		} else {
5134 			/*
5135 			 * If further retransmissions are still unsuccessful
5136 			 * with a lowered MTU, maybe this isn't a blackhole
5137 			 * and we restore the previous MSS and blackhole
5138 			 * detection flags. The limit '6' is determined by
5139 			 * giving each probe stage (1448, 1188, 524) 2
5140 			 * chances to recover.
5141 			 */
5142 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5143 			    (tp->t_rxtshift >= 6)) {
5144 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5145 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5146 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5147 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5148 			}
5149 		}
5150 	}
5151 	/*
5152 	 * Disable RFC1323 and SACK if we haven't got any response to our
5153 	 * third SYN to work-around some broken terminal servers (most of
5154 	 * which have hopefully been retired) that have bad VJ header
5155 	 * compression code which trashes TCP segments containing
5156 	 * unknown-to-them TCP options.
5157 	 */
5158 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5159 	    (tp->t_rxtshift == 3))
5160 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5161 	/*
5162 	 * If we backed off this far, our srtt estimate is probably bogus.
5163 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5164 	 * move the current srtt into rttvar to keep the current retransmit
5165 	 * times until then.
5166 	 */
5167 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5168 #ifdef INET6
5169 		if (bbr->r_is_v6)
5170 			in6_losing(inp);
5171 		else
5172 #endif
5173 			in_losing(inp);
5174 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5175 		tp->t_srtt = 0;
5176 	}
5177 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5178 	tp->snd_recover = tp->snd_max;
5179 	tp->t_flags |= TF_ACKNOW;
5180 	tp->t_rtttime = 0;
5181 
5182 	return (retval);
5183 }
5184 
5185 static int
5186 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5187 {
5188 	int32_t ret = 0;
5189 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5190 
5191 	if (timers == 0) {
5192 		return (0);
5193 	}
5194 	if (tp->t_state == TCPS_LISTEN) {
5195 		/* no timers on listen sockets */
5196 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5197 			return (0);
5198 		return (1);
5199 	}
5200 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5201 		uint32_t left;
5202 
5203 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5204 			ret = -1;
5205 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5206 			return (0);
5207 		}
5208 		if (hpts_calling == 0) {
5209 			ret = -2;
5210 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5211 			return (0);
5212 		}
5213 		/*
5214 		 * Ok our timer went off early and we are not paced false
5215 		 * alarm, go back to sleep.
5216 		 */
5217 		left = bbr->r_ctl.rc_timer_exp - cts;
5218 		ret = -3;
5219 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5220 		tcp_hpts_insert(tptoinpcb(tp), HPTS_USEC_TO_SLOTS(left));
5221 		return (1);
5222 	}
5223 	bbr->rc_tmr_stopped = 0;
5224 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5225 	if (timers & PACE_TMR_DELACK) {
5226 		ret = bbr_timeout_delack(tp, bbr, cts);
5227 	} else if (timers & PACE_TMR_PERSIT) {
5228 		ret = bbr_timeout_persist(tp, bbr, cts);
5229 	} else if (timers & PACE_TMR_RACK) {
5230 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5231 		ret = bbr_timeout_rack(tp, bbr, cts);
5232 	} else if (timers & PACE_TMR_TLP) {
5233 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5234 		ret = bbr_timeout_tlp(tp, bbr, cts);
5235 	} else if (timers & PACE_TMR_RXT) {
5236 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5237 		ret = bbr_timeout_rxt(tp, bbr, cts);
5238 	} else if (timers & PACE_TMR_KEEP) {
5239 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5240 	}
5241 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5242 	return (ret);
5243 }
5244 
5245 static void
5246 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5247 {
5248 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5249 		uint8_t hpts_removed = 0;
5250 
5251 		if (tcp_in_hpts(bbr->rc_inp) &&
5252 		    (bbr->rc_timer_first == 1)) {
5253 			/*
5254 			 * If we are canceling timer's when we have the
5255 			 * timer ahead of the output being paced. We also
5256 			 * must remove ourselves from the hpts.
5257 			 */
5258 			hpts_removed = 1;
5259 			tcp_hpts_remove(bbr->rc_inp);
5260 			if (bbr->r_ctl.rc_last_delay_val) {
5261 				/* Update the last hptsi delay too */
5262 				uint32_t time_since_send;
5263 
5264 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5265 					time_since_send = cts - bbr->rc_pacer_started;
5266 				else
5267 					time_since_send = 0;
5268 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5269 					/* Cut down our slot time */
5270 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5271 				} else {
5272 					bbr->r_ctl.rc_last_delay_val = 0;
5273 				}
5274 				bbr->rc_pacer_started = cts;
5275 			}
5276 		}
5277 		bbr->rc_timer_first = 0;
5278 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5279 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5280 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5281 	}
5282 }
5283 
5284 static int
5285 bbr_stopall(struct tcpcb *tp)
5286 {
5287 	struct tcp_bbr *bbr;
5288 
5289 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5290 	bbr->rc_all_timers_stopped = 1;
5291 	return (0);
5292 }
5293 
5294 static uint32_t
5295 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5296 {
5297 	struct bbr_sendmap *rsm;
5298 
5299 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5300 	if ((rsm == NULL) || (u_rsm == rsm))
5301 		return (cts);
5302 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5303 }
5304 
5305 static void
5306 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5307      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5308 {
5309 	int32_t idx;
5310 
5311 	rsm->r_rtr_cnt++;
5312 	rsm->r_dupack = 0;
5313 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5314 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5315 		rsm->r_flags |= BBR_OVERMAX;
5316 	}
5317 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5318 		/* Take off the collapsed flag at rxt */
5319 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5320 	}
5321 	if (rsm->r_flags & BBR_MARKED_LOST) {
5322 		/* We have retransmitted, its no longer lost */
5323 		rsm->r_flags &= ~BBR_MARKED_LOST;
5324 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5325 	}
5326 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5327 		/*
5328 		 * We hit a RXT timer on it and
5329 		 * we cleared the "acked" flag.
5330 		 * We now have it going back into
5331 		 * flight, we can remove the cleared
5332 		 * flag and possibly do accounting on
5333 		 * this piece.
5334 		 */
5335 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5336 	}
5337 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5338 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5339 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5340 	}
5341 	idx = rsm->r_rtr_cnt - 1;
5342 	rsm->r_tim_lastsent[idx] = cts;
5343 	rsm->r_pacing_delay = pacing_time;
5344 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5345 	rsm->r_ts_valid = bbr->rc_ts_valid;
5346 	if (bbr->rc_ts_valid)
5347 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5348 	if (bbr->r_ctl.r_app_limited_until)
5349 		rsm->r_app_limited = 1;
5350 	else
5351 		rsm->r_app_limited = 0;
5352 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5353 		rsm->r_bbr_state = bbr_state_val(bbr);
5354 	else
5355 		rsm->r_bbr_state = 8;
5356 	if (rsm->r_flags & BBR_ACKED) {
5357 		/* Problably MTU discovery messing with us */
5358 		uint32_t old_flags;
5359 
5360 		old_flags = rsm->r_flags;
5361 		rsm->r_flags &= ~BBR_ACKED;
5362 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5363 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5364 		if (bbr->r_ctl.rc_sacked == 0)
5365 			bbr->r_ctl.rc_sacklast = NULL;
5366 	}
5367 	if (rsm->r_in_tmap) {
5368 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5369 	}
5370 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5371 	rsm->r_in_tmap = 1;
5372 	if (rsm->r_flags & BBR_SACK_PASSED) {
5373 		/* We have retransmitted due to the SACK pass */
5374 		rsm->r_flags &= ~BBR_SACK_PASSED;
5375 		rsm->r_flags |= BBR_WAS_SACKPASS;
5376 	}
5377 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5378 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5379 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5380 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5381 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5382 		rsm->r_is_gain = 1;
5383 		rsm->r_is_drain = 0;
5384 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5385 		rsm->r_is_drain = 1;
5386 		rsm->r_is_gain = 0;
5387 	} else {
5388 		rsm->r_is_drain = 0;
5389 		rsm->r_is_gain = 0;
5390 	}
5391 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5392 }
5393 
5394 /*
5395  * Returns 0, or the sequence where we stopped
5396  * updating. We also update the lenp to be the amount
5397  * of data left.
5398  */
5399 
5400 static uint32_t
5401 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5402     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5403 {
5404 	/*
5405 	 * We (re-)transmitted starting at rsm->r_start for some length
5406 	 * (possibly less than r_end.
5407 	 */
5408 	struct bbr_sendmap *nrsm;
5409 	uint32_t c_end;
5410 	int32_t len;
5411 
5412 	len = *lenp;
5413 	c_end = rsm->r_start + len;
5414 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5415 		/*
5416 		 * We retransmitted the whole piece or more than the whole
5417 		 * slopping into the next rsm.
5418 		 */
5419 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5420 		if (c_end == rsm->r_end) {
5421 			*lenp = 0;
5422 			return (0);
5423 		} else {
5424 			int32_t act_len;
5425 
5426 			/* Hangs over the end return whats left */
5427 			act_len = rsm->r_end - rsm->r_start;
5428 			*lenp = (len - act_len);
5429 			return (rsm->r_end);
5430 		}
5431 		/* We don't get out of this block. */
5432 	}
5433 	/*
5434 	 * Here we retransmitted less than the whole thing which means we
5435 	 * have to split this into what was transmitted and what was not.
5436 	 */
5437 	nrsm = bbr_alloc_full_limit(bbr);
5438 	if (nrsm == NULL) {
5439 		*lenp = 0;
5440 		return (0);
5441 	}
5442 	/*
5443 	 * So here we are going to take the original rsm and make it what we
5444 	 * retransmitted. nrsm will be the tail portion we did not
5445 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5446 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5447 	 * 1, 6 and the new piece will be 6, 11.
5448 	 */
5449 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5450 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5451 	nrsm->r_dupack = 0;
5452 	if (rsm->r_in_tmap) {
5453 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5454 		nrsm->r_in_tmap = 1;
5455 	}
5456 	rsm->r_flags &= (~BBR_HAS_FIN);
5457 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5458 	*lenp = 0;
5459 	return (0);
5460 }
5461 
5462 static uint64_t
5463 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5464 {
5465 	uint64_t bw;
5466 
5467 	bw = bbr_get_bw(bbr);
5468 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5469 	bw /= (uint64_t)BBR_UNIT;
5470 	return(bw);
5471 }
5472 
5473 static void
5474 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5475 		       uint64_t act_rate, uint64_t rate_wanted)
5476 {
5477 	/*
5478 	 * We could not get a full gains worth
5479 	 * of rate.
5480 	 */
5481 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5482 		/* we can't even get the real rate */
5483 		uint64_t red;
5484 
5485 		bbr->skip_gain = 1;
5486 		bbr->gain_is_limited = 0;
5487 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5488 		if (red)
5489 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5490 	} else {
5491 		/* We can use a lower gain */
5492 		bbr->skip_gain = 0;
5493 		bbr->gain_is_limited = 1;
5494 	}
5495 }
5496 
5497 static void
5498 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5499 {
5500 	const struct tcp_hwrate_limit_table *nrte;
5501 	int error, rate = -1;
5502 
5503 	if (bbr->r_ctl.crte == NULL)
5504 		return;
5505 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5506 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5507 		/* Lost our routes? */
5508 		/* Clear the way for a re-attempt */
5509 		bbr->bbr_attempt_hdwr_pace = 0;
5510 lost_rate:
5511 		bbr->gain_is_limited = 0;
5512 		bbr->skip_gain = 0;
5513 		bbr->bbr_hdrw_pacing = 0;
5514 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5515 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5516 		tcp_bbr_tso_size_check(bbr, cts);
5517 		return;
5518 	}
5519 	rate = bbr_get_hardware_rate(bbr);
5520 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5521 				   bbr->rc_tp,
5522 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5523 				   rate,
5524 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5525 				   &error, NULL);
5526 	if (nrte == NULL) {
5527 		goto lost_rate;
5528 	}
5529 	if (nrte != bbr->r_ctl.crte) {
5530 		bbr->r_ctl.crte = nrte;
5531 		if (error == 0)  {
5532 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5533 			if (bbr->r_ctl.crte->rate < rate) {
5534 				/* We have a problem */
5535 				bbr_setup_less_of_rate(bbr, cts,
5536 						       bbr->r_ctl.crte->rate, rate);
5537 			} else {
5538 				/* We are good */
5539 				bbr->gain_is_limited = 0;
5540 				bbr->skip_gain = 0;
5541 			}
5542 		} else {
5543 			/* A failure should release the tag */
5544 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5545 			bbr->gain_is_limited = 0;
5546 			bbr->skip_gain = 0;
5547 			bbr->bbr_hdrw_pacing = 0;
5548 		}
5549 		bbr_type_log_hdwr_pacing(bbr,
5550 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5551 					 rate,
5552 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5553 					 __LINE__,
5554 					 cts,
5555 					 error);
5556 	}
5557 }
5558 
5559 static void
5560 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5561 {
5562 	/*
5563 	 * If we have hardware pacing support
5564 	 * we need to factor that in for our
5565 	 * TSO size.
5566 	 */
5567 	const struct tcp_hwrate_limit_table *rlp;
5568 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5569 
5570 	if ((bbr->bbr_hdrw_pacing == 0) ||
5571 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5572 	    (bbr->r_ctl.crte == NULL))
5573 		return;
5574 	if (bbr->hw_pacing_set == 0) {
5575 		/* Not yet by the hdwr pacing count delay */
5576 		return;
5577 	}
5578 	if (bbr_hdwr_pace_adjust == 0) {
5579 		/* No adjustment */
5580 		return;
5581 	}
5582 	rlp = bbr->r_ctl.crte;
5583 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5584 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5585 	else
5586 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5587 	/*
5588 	 * So lets first get the
5589 	 * time we will take between
5590 	 * TSO sized sends currently without
5591 	 * hardware help.
5592 	 */
5593 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5594 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5595 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5596 	hdwr_delay *= rlp->time_between;
5597 	if (cur_delay > hdwr_delay)
5598 		delta = cur_delay - hdwr_delay;
5599 	else
5600 		delta = 0;
5601 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5602 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5603 			     1);
5604 	if (delta &&
5605 	    (delta < (max(rlp->time_between,
5606 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5607 		/*
5608 		 * Now lets divide by the pacing
5609 		 * time between each segment the
5610 		 * hardware sends rounding up and
5611 		 * derive a bytes from that. We multiply
5612 		 * that by bbr_hdwr_pace_adjust to get
5613 		 * more bang for our buck.
5614 		 *
5615 		 * The goal is to have the software pacer
5616 		 * waiting no more than an additional
5617 		 * pacing delay if we can (without the
5618 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5619 		 */
5620 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5621 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5622 		seg_sz *= bbr_hdwr_pace_adjust;
5623 		if (bbr_hdwr_pace_floor &&
5624 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5625 			/* Currently hardware paces
5626 			 * out rs_min_seg segments at a time.
5627 			 * We need to make sure we always send at least
5628 			 * a full burst of bbr_hdwr_pace_floor down.
5629 			 */
5630 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5631 		}
5632 		seg_sz *= maxseg;
5633 	} else if (delta == 0) {
5634 		/*
5635 		 * The highest pacing rate is
5636 		 * above our b/w gained. This means
5637 		 * we probably are going quite fast at
5638 		 * the hardware highest rate. Lets just multiply
5639 		 * the calculated TSO size by the
5640 		 * multiplier factor (its probably
5641 		 * 4 segments in the default config for
5642 		 * mlx).
5643 		 */
5644 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5645 		if (bbr_hdwr_pace_floor &&
5646 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5647 			/* Currently hardware paces
5648 			 * out rs_min_seg segments at a time.
5649 			 * We need to make sure we always send at least
5650 			 * a full burst of bbr_hdwr_pace_floor down.
5651 			 */
5652 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5653 		}
5654 	} else {
5655 		/*
5656 		 * The pacing time difference is so
5657 		 * big that the hardware will
5658 		 * pace out more rapidly then we
5659 		 * really want and then we
5660 		 * will have a long delay. Lets just keep
5661 		 * the same TSO size so its as if
5662 		 * we were not using hdwr pacing (we
5663 		 * just gain a bit of spacing from the
5664 		 * hardware if seg_sz > 1).
5665 		 */
5666 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5667 	}
5668 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5669 		new_tso = seg_sz;
5670 	else
5671 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5672 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5673 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5674 
5675 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5676 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5677 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5678 	}
5679 }
5680 
5681 static void
5682 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5683 {
5684 	uint64_t bw;
5685 	uint32_t old_tso = 0, new_tso;
5686 	uint32_t maxseg, bytes;
5687 	uint32_t tls_seg=0;
5688 	/*
5689 	 * Google/linux uses the following algorithm to determine
5690 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5691 	 *
5692 	 *  bytes = bw_in_bytes_per_second / 1000
5693 	 *  bytes = min(bytes, 64k)
5694 	 *  tso_segs = bytes / MSS
5695 	 *  if (bw < 1.2Mbs)
5696 	 *      min_tso_segs = 1
5697 	 *  else
5698 	 *	min_tso_segs = 2
5699 	 * tso_segs = max(tso_segs, min_tso_segs)
5700 	 *
5701 	 * * Note apply a device specific limit (we apply this in the
5702 	 *   tcp_m_copym).
5703 	 * Note that before the initial measurement is made google bursts out
5704 	 * a full iwnd just like new-reno/cubic.
5705 	 *
5706 	 * We do not use this algorithm. Instead we
5707 	 * use a two phased approach:
5708 	 *
5709 	 *  if ( bw <= per-tcb-cross-over)
5710 	 *     goal_tso =  calculate how much with this bw we
5711 	 *                 can send in goal-time seconds.
5712 	 *     if (goal_tso > mss)
5713 	 *         seg = goal_tso / mss
5714 	 *         tso = seg * mss
5715 	 *     else
5716 	 *         tso = mss
5717 	 *     if (tso > per-tcb-max)
5718 	 *         tso = per-tcb-max
5719 	 *  else if ( bw > 512Mbps)
5720 	 *     tso = max-tso (64k/mss)
5721 	 *  else
5722 	 *     goal_tso = bw / per-tcb-divsor
5723 	 *     seg = (goal_tso + mss-1)/mss
5724 	 *     tso = seg * mss
5725 	 *
5726 	 * if (tso < per-tcb-floor)
5727 	 *    tso = per-tcb-floor
5728 	 * if (tso > per-tcb-utter_max)
5729 	 *    tso = per-tcb-utter_max
5730 	 *
5731 	 * Note the default per-tcb-divisor is 1000 (same as google).
5732 	 * the goal cross over is 30Mbps however. To recreate googles
5733 	 * algorithm you need to set:
5734 	 *
5735 	 * cross-over = 23,168,000 bps
5736 	 * goal-time = 18000
5737 	 * per-tcb-max = 2
5738 	 * per-tcb-divisor = 1000
5739 	 * per-tcb-floor = 1
5740 	 *
5741 	 * This will get you "google bbr" behavior with respect to tso size.
5742 	 *
5743 	 * Note we do set anything TSO size until we are past the initial
5744 	 * window. Before that we gnerally use either a single MSS
5745 	 * or we use the full IW size (so we burst a IW at a time)
5746 	 */
5747 
5748 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5749 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5750 	} else {
5751 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5752 	}
5753 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5754 	if (bbr->rc_past_init_win == 0) {
5755 		/*
5756 		 * Not enough data has been acknowledged to make a
5757 		 * judgement. Set up the initial TSO based on if we
5758 		 * are sending a full IW at once or not.
5759 		 */
5760 		if (bbr->rc_use_google)
5761 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5762 		else if (bbr->bbr_init_win_cheat)
5763 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5764 		else
5765 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5766 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5767 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5768 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5769 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5770 		}
5771 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5772 			bbr_adjust_for_hw_pacing(bbr, cts);
5773 		return;
5774 	}
5775 	/**
5776 	 * Now lets set the TSO goal based on our delivery rate in
5777 	 * bytes per second. Note we only do this if
5778 	 * we have acked at least the initial cwnd worth of data.
5779 	 */
5780 	bw = bbr_get_bw(bbr);
5781 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5782 	     (bbr->rc_use_google == 0)) {
5783 		/* We clamp to one MSS in recovery */
5784 		new_tso = maxseg;
5785 	} else if (bbr->rc_use_google) {
5786 		int min_tso_segs;
5787 
5788 		/* Google considers the gain too */
5789 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5790 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5791 			bw /= BBR_UNIT;
5792 		}
5793 		bytes = bw / 1024;
5794 		if (bytes > (64 * 1024))
5795 			bytes = 64 * 1024;
5796 		new_tso = bytes / maxseg;
5797 		if (bw < ONE_POINT_TWO_MEG)
5798 			min_tso_segs = 1;
5799 		else
5800 			min_tso_segs = 2;
5801 		if (new_tso < min_tso_segs)
5802 			new_tso = min_tso_segs;
5803 		new_tso *= maxseg;
5804 	} else if (bbr->rc_no_pacing) {
5805 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5806 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5807 		/*
5808 		 * Calculate the worse case b/w TSO if we are inserting no
5809 		 * more than a delay_target number of TSO's.
5810 		 */
5811 		uint32_t tso_len, min_tso;
5812 
5813 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5814 		if (tso_len > maxseg) {
5815 			new_tso = tso_len / maxseg;
5816 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5817 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5818 			new_tso *= maxseg;
5819 		} else {
5820 			/*
5821 			 * less than a full sized frame yikes.. long rtt or
5822 			 * low bw?
5823 			 */
5824 			min_tso = bbr_minseg(bbr);
5825 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5826 				new_tso = rounddown(tso_len, min_tso);
5827 			else
5828 				new_tso = min_tso;
5829 		}
5830 	} else if (bw > FIVETWELVE_MBPS) {
5831 		/*
5832 		 * This guy is so fast b/w wise that we can TSO as large as
5833 		 * possible of segments that the NIC will allow.
5834 		 */
5835 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5836 	} else {
5837 		/*
5838 		 * This formula is based on attempting to send a segment or
5839 		 * more every bbr_hptsi_per_second. The default is 1000
5840 		 * which means you are targeting what you can send every 1ms
5841 		 * based on the peers bw.
5842 		 *
5843 		 * If the number drops to say 500, then you are looking more
5844 		 * at 2ms and you will raise how much we send in a single
5845 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5846 		 * trade off of course is you will send more at once and
5847 		 * thus tend to clump up the sends into larger "bursts"
5848 		 * building a queue.
5849 		 */
5850 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5851 		new_tso = roundup(bw, (uint64_t)maxseg);
5852 		/*
5853 		 * Gate the floor to match what our lower than 48Mbps
5854 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5855 		 * becomes the floor for this calculation.
5856 		 */
5857 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5858 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5859 	}
5860 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5861 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5862 	if (new_tso > PACE_MAX_IP_BYTES)
5863 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5864 	/* Enforce an utter maximum. */
5865 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5866 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5867 	}
5868 	if (old_tso != new_tso) {
5869 		/* Only log changes */
5870 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5871 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5872 	}
5873 	/* We have hardware pacing! */
5874 	bbr_adjust_for_hw_pacing(bbr, cts);
5875 }
5876 
5877 static void
5878 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5879     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5880     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5881     struct sockbuf *sb)
5882 {
5883 
5884 	struct bbr_sendmap *rsm, *nrsm;
5885 	register uint32_t snd_max, snd_una;
5886 	uint32_t pacing_time;
5887 	/*
5888 	 * Add to the RACK log of packets in flight or retransmitted. If
5889 	 * there is a TS option we will use the TS echoed, if not we will
5890 	 * grab a TS.
5891 	 *
5892 	 * Retransmissions will increment the count and move the ts to its
5893 	 * proper place. Note that if options do not include TS's then we
5894 	 * won't be able to effectively use the ACK for an RTT on a retran.
5895 	 *
5896 	 * Notes about r_start and r_end. Lets consider a send starting at
5897 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5898 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5899 	 * This means that r_end is actually the first sequence for the next
5900 	 * slot (11).
5901 	 *
5902 	 */
5903 	INP_WLOCK_ASSERT(tptoinpcb(tp));
5904 	if (err) {
5905 		/*
5906 		 * We don't log errors -- we could but snd_max does not
5907 		 * advance in this case either.
5908 		 */
5909 		return;
5910 	}
5911 	if (th_flags & TH_RST) {
5912 		/*
5913 		 * We don't log resets and we return immediately from
5914 		 * sending
5915 		 */
5916 		*abandon = 1;
5917 		return;
5918 	}
5919 	snd_una = tp->snd_una;
5920 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5921 		/*
5922 		 * The call to bbr_log_output is made before bumping
5923 		 * snd_max. This means we can record one extra byte on a SYN
5924 		 * or FIN if seq_out is adding more on and a FIN is present
5925 		 * (and we are not resending).
5926 		 */
5927 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5928 			len++;
5929 		if (th_flags & TH_FIN)
5930 			len++;
5931 	}
5932 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5933 		/* Are sending an old segment to induce an ack (keep-alive)? */
5934 		return;
5935 	}
5936 	if (SEQ_LT(seq_out, snd_una)) {
5937 		/* huh? should we panic? */
5938 		uint32_t end;
5939 
5940 		end = seq_out + len;
5941 		seq_out = snd_una;
5942 		len = end - seq_out;
5943 	}
5944 	snd_max = tp->snd_max;
5945 	if (len == 0) {
5946 		/* We don't log zero window probes */
5947 		return;
5948 	}
5949 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5950 	/* First question is it a retransmission? */
5951 	if (seq_out == snd_max) {
5952 again:
5953 		rsm = bbr_alloc(bbr);
5954 		if (rsm == NULL) {
5955 			return;
5956 		}
5957 		rsm->r_flags = 0;
5958 		if (th_flags & TH_SYN)
5959 			rsm->r_flags |= BBR_HAS_SYN;
5960 		if (th_flags & TH_FIN)
5961 			rsm->r_flags |= BBR_HAS_FIN;
5962 		rsm->r_tim_lastsent[0] = cts;
5963 		rsm->r_rtr_cnt = 1;
5964 		rsm->r_rtr_bytes = 0;
5965 		rsm->r_start = seq_out;
5966 		rsm->r_end = rsm->r_start + len;
5967 		rsm->r_dupack = 0;
5968 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5969 		rsm->r_pacing_delay = pacing_time;
5970 		rsm->r_ts_valid = bbr->rc_ts_valid;
5971 		if (bbr->rc_ts_valid)
5972 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5973 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
5974 		if (bbr->r_ctl.r_app_limited_until)
5975 			rsm->r_app_limited = 1;
5976 		else
5977 			rsm->r_app_limited = 0;
5978 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5979 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5980 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5981 		/*
5982 		 * Here we must also add in this rsm since snd_max
5983 		 * is updated after we return from a new send.
5984 		 */
5985 		rsm->r_flight_at_send += len;
5986 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
5987 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5988 		rsm->r_in_tmap = 1;
5989 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5990 			rsm->r_bbr_state = bbr_state_val(bbr);
5991 		else
5992 			rsm->r_bbr_state = 8;
5993 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5994 			rsm->r_is_gain = 1;
5995 			rsm->r_is_drain = 0;
5996 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5997 			rsm->r_is_drain = 1;
5998 			rsm->r_is_gain = 0;
5999 		} else {
6000 			rsm->r_is_drain = 0;
6001 			rsm->r_is_gain = 0;
6002 		}
6003 		return;
6004 	}
6005 	/*
6006 	 * If we reach here its a retransmission and we need to find it.
6007 	 */
6008 more:
6009 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6010 		rsm = hintrsm;
6011 		hintrsm = NULL;
6012 	} else if (bbr->r_ctl.rc_next) {
6013 		/* We have a hint from a previous run */
6014 		rsm = bbr->r_ctl.rc_next;
6015 	} else {
6016 		/* No hints sorry */
6017 		rsm = NULL;
6018 	}
6019 	if ((rsm) && (rsm->r_start == seq_out)) {
6020 		/*
6021 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6022 		 * likely case.
6023 		 */
6024 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6025 		if (len == 0) {
6026 			return;
6027 		} else {
6028 			goto more;
6029 		}
6030 	}
6031 	/* Ok it was not the last pointer go through it the hard way. */
6032 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6033 		if (rsm->r_start == seq_out) {
6034 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6035 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6036 			if (len == 0) {
6037 				return;
6038 			} else {
6039 				continue;
6040 			}
6041 		}
6042 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6043 			/* Transmitted within this piece */
6044 			/*
6045 			 * Ok we must split off the front and then let the
6046 			 * update do the rest
6047 			 */
6048 			nrsm = bbr_alloc_full_limit(bbr);
6049 			if (nrsm == NULL) {
6050 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6051 				return;
6052 			}
6053 			/*
6054 			 * copy rsm to nrsm and then trim the front of rsm
6055 			 * to not include this part.
6056 			 */
6057 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6058 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6059 			if (rsm->r_in_tmap) {
6060 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6061 				nrsm->r_in_tmap = 1;
6062 			}
6063 			rsm->r_flags &= (~BBR_HAS_FIN);
6064 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6065 			if (len == 0) {
6066 				return;
6067 			}
6068 		}
6069 	}
6070 	/*
6071 	 * Hmm not found in map did they retransmit both old and on into the
6072 	 * new?
6073 	 */
6074 	if (seq_out == tp->snd_max) {
6075 		goto again;
6076 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6077 #ifdef BBR_INVARIANTS
6078 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6079 		    seq_out, len, tp->snd_una, tp->snd_max);
6080 		printf("Starting Dump of all rack entries\n");
6081 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6082 			printf("rsm:%p start:%u end:%u\n",
6083 			    rsm, rsm->r_start, rsm->r_end);
6084 		}
6085 		printf("Dump complete\n");
6086 		panic("seq_out not found rack:%p tp:%p",
6087 		    bbr, tp);
6088 #endif
6089 	} else {
6090 #ifdef BBR_INVARIANTS
6091 		/*
6092 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6093 		 * flag)
6094 		 */
6095 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6096 		    seq_out, len, tp->snd_max, tp);
6097 #endif
6098 	}
6099 }
6100 
6101 static void
6102 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6103 {
6104 	/*
6105 	 * Collapse timeout back the cum-ack moved.
6106 	 */
6107 	tp->t_rxtshift = 0;
6108 	tp->t_softerror = 0;
6109 }
6110 
6111 static void
6112 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6113 {
6114 	bbr->rtt_valid = 1;
6115 	bbr->r_ctl.cur_rtt = rtt_usecs;
6116 	bbr->r_ctl.ts_in = tsin;
6117 	if (rsm_send_time)
6118 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6119 }
6120 
6121 static void
6122 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6123 {
6124 	/**
6125 	 * We have in our bbr control:
6126 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6127 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6128 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6129 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6130 	 *
6131 	 * Now we can calculate the time between the sends by doing:
6132 	 *
6133 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6134 	 *
6135 	 * And the peer's time between receiving them by doing:
6136 	 *
6137 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6138 	 *
6139 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6140 	 * We also may find that we can't use the timestamps if say we see
6141 	 * that the peer_delta indicates that though we may have taken 10ms to
6142 	 * pace out the data, it only saw 1ms between the two packets. This would
6143 	 * indicate that somewhere on the path is a batching entity that is giving
6144 	 * out time-slices of the actual b/w. This would mean we could not use
6145 	 * reliably the peers timestamps.
6146 	 *
6147 	 * We expect delta > peer_delta initially. Until we figure out the
6148 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6149 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6150 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6151 	 * put a 1 there. If the value is faster then ours, we will disable the
6152 	 * use of timestamps (though we could revist this later if we find it to be not
6153 	 * just an isolated one or two flows)).
6154 	 *
6155 	 * To detect the batching middle boxes we will come up with our compensation and
6156 	 * if with it in place, we find the peer is drastically off (by some margin) in
6157 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6158 	 *
6159 	 */
6160 	uint64_t delta, peer_delta, delta_up;
6161 
6162 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6163 	if (delta < bbr_min_usec_delta) {
6164 		/*
6165 		 * Have not seen a min amount of time
6166 		 * between our send times so we can
6167 		 * make a determination of the timestamp
6168 		 * yet.
6169 		 */
6170 		return;
6171 	}
6172 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6173 	if (peer_delta < bbr_min_peer_delta) {
6174 		/*
6175 		 * We may have enough in the form of
6176 		 * our delta but the peers number
6177 		 * has not changed that much. It could
6178 		 * be its clock ratio is such that
6179 		 * we need more data (10ms tick) or
6180 		 * there may be other compression scenarios
6181 		 * going on. In any event we need the
6182 		 * spread to be larger.
6183 		 */
6184 		return;
6185 	}
6186 	/* Ok lets first see which way our delta is going */
6187 	if (peer_delta > delta) {
6188 		/* Very unlikely, the peer without
6189 		 * compensation shows that it saw
6190 		 * the two sends arrive further apart
6191 		 * then we saw then in micro-seconds.
6192 		 */
6193 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6194 			/* well it looks like the peer is a micro-second clock. */
6195 			bbr->rc_ts_clock_set = 1;
6196 			bbr->r_ctl.bbr_peer_tsratio = 1;
6197 		} else {
6198 			bbr->rc_ts_cant_be_used = 1;
6199 			bbr->rc_ts_clock_set = 1;
6200 		}
6201 		return;
6202 	}
6203 	/* Ok we know that the peer_delta is smaller than our send distance */
6204 	bbr->rc_ts_clock_set = 1;
6205 	/* First question is it within the percentage that they are using usec time? */
6206 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6207 	if ((peer_delta + delta_up) >= delta) {
6208 		/* Its a usec clock */
6209 		bbr->r_ctl.bbr_peer_tsratio = 1;
6210 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6211 		return;
6212 	}
6213 	/* Ok if not usec, what about 10usec (though unlikely)? */
6214 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6215 	if (((peer_delta * 10) + delta_up) >= delta) {
6216 		bbr->r_ctl.bbr_peer_tsratio = 10;
6217 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6218 		return;
6219 	}
6220 	/* And what about 100usec (though again unlikely)? */
6221 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6222 	if (((peer_delta * 100) + delta_up) >= delta) {
6223 		bbr->r_ctl.bbr_peer_tsratio = 100;
6224 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6225 		return;
6226 	}
6227 	/* And how about 1 msec (the most likely one)? */
6228 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6229 	if (((peer_delta * 1000) + delta_up) >= delta) {
6230 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6231 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6232 		return;
6233 	}
6234 	/* Ok if not msec could it be 10 msec? */
6235 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6236 	if (((peer_delta * 10000) + delta_up) >= delta) {
6237 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6238 		return;
6239 	}
6240 	/* If we fall down here the clock tick so slowly we can't use it */
6241 	bbr->rc_ts_cant_be_used = 1;
6242 	bbr->r_ctl.bbr_peer_tsratio = 0;
6243 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6244 }
6245 
6246 /*
6247  * Collect new round-trip time estimate
6248  * and update averages and current timeout.
6249  */
6250 static void
6251 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6252 {
6253 	int32_t delta;
6254 	uint32_t rtt, tsin;
6255 	int32_t rtt_ticks;
6256 
6257 	if (bbr->rtt_valid == 0)
6258 		/* No valid sample */
6259 		return;
6260 
6261 	rtt = bbr->r_ctl.cur_rtt;
6262 	tsin = bbr->r_ctl.ts_in;
6263 	if (bbr->rc_prtt_set_ts) {
6264 		/*
6265 		 * We are to force feed the rttProp filter due
6266 		 * to an entry into PROBE_RTT. This assures
6267 		 * that the times are sync'd between when we
6268 		 * go into PROBE_RTT and the filter expiration.
6269 		 *
6270 		 * Google does not use a true filter, so they do
6271 		 * this implicitly since they only keep one value
6272 		 * and when they enter probe-rtt they update the
6273 		 * value to the newest rtt.
6274 		 */
6275 		uint32_t rtt_prop;
6276 
6277 		bbr->rc_prtt_set_ts = 0;
6278 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6279 		if (rtt > rtt_prop)
6280 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6281 		else
6282 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6283 	}
6284 	if (bbr->rc_ack_was_delayed)
6285 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6286 
6287 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6288 		bbr->r_ctl.rc_lowest_rtt = rtt;
6289 	bbr_log_rtt_sample(bbr, rtt, tsin);
6290 	if (bbr->r_init_rtt) {
6291 		/*
6292 		 * The initial rtt is not-trusted, nuke it and lets get
6293 		 * our first valid measurement in.
6294 		 */
6295 		bbr->r_init_rtt = 0;
6296 		tp->t_srtt = 0;
6297 	}
6298 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6299 		/*
6300 		 * So we have not yet figured out
6301 		 * what the peers TSTMP value is
6302 		 * in (most likely ms). We need a
6303 		 * series of cum-ack's to determine
6304 		 * this reliably.
6305 		 */
6306 		if (bbr->rc_ack_is_cumack) {
6307 			if (bbr->rc_ts_data_set) {
6308 				/* Lets attempt to determine the timestamp granularity. */
6309 				bbr_make_timestamp_determination(bbr);
6310 			} else {
6311 				bbr->rc_ts_data_set = 1;
6312 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6313 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6314 			}
6315 		} else {
6316 			/*
6317 			 * We have to have consecutive acks
6318 			 * reset any "filled" state to none.
6319 			 */
6320 			bbr->rc_ts_data_set = 0;
6321 		}
6322 	}
6323 	/* Round it up */
6324 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6325 	if (rtt_ticks == 0)
6326 		rtt_ticks = 1;
6327 	if (tp->t_srtt != 0) {
6328 		/*
6329 		 * srtt is stored as fixed point with 5 bits after the
6330 		 * binary point (i.e., scaled by 8).  The following magic is
6331 		 * equivalent to the smoothing algorithm in rfc793 with an
6332 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6333 		 * Adjust rtt to origin 0.
6334 		 */
6335 
6336 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6337 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6338 
6339 		tp->t_srtt += delta;
6340 		if (tp->t_srtt <= 0)
6341 			tp->t_srtt = 1;
6342 
6343 		/*
6344 		 * We accumulate a smoothed rtt variance (actually, a
6345 		 * smoothed mean difference), then set the retransmit timer
6346 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6347 		 * is stored as fixed point with 4 bits after the binary
6348 		 * point (scaled by 16).  The following is equivalent to
6349 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6350 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6351 		 * wired-in beta.
6352 		 */
6353 		if (delta < 0)
6354 			delta = -delta;
6355 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6356 		tp->t_rttvar += delta;
6357 		if (tp->t_rttvar <= 0)
6358 			tp->t_rttvar = 1;
6359 	} else {
6360 		/*
6361 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6362 		 * variance to half the rtt (so our first retransmit happens
6363 		 * at 3*rtt).
6364 		 */
6365 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6366 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6367 	}
6368 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6369 	if (tp->t_rttupdated < UCHAR_MAX)
6370 		tp->t_rttupdated++;
6371 #ifdef STATS
6372 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6373 #endif
6374 	/*
6375 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6376 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6377 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6378 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6379 	 * uncertainty in the firing of the timer.  The bias will give us
6380 	 * exactly the 1.5 tick we need.  But, because the bias is
6381 	 * statistical, we have to test that we don't drop below the minimum
6382 	 * feasible timer (which is 2 ticks).
6383 	 */
6384 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6385 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6386 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6387 
6388 	/*
6389 	 * We received an ack for a packet that wasn't retransmitted; it is
6390 	 * probably safe to discard any error indications we've received
6391 	 * recently.  This isn't quite right, but close enough for now (a
6392 	 * route might have failed after we sent a segment, and the return
6393 	 * path might not be symmetrical).
6394 	 */
6395 	tp->t_softerror = 0;
6396 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6397 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6398 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6399 }
6400 
6401 static void
6402 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6403 {
6404 	bbr->r_ctl.rc_rtt_shrinks = cts;
6405 	if (bbr_can_force_probertt &&
6406 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6407 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6408 		/*
6409 		 * We should enter probe-rtt its been too long
6410 		 * since we have been there.
6411 		 */
6412 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6413 	} else
6414 		bbr_check_probe_rtt_limits(bbr, cts);
6415 }
6416 
6417 static void
6418 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6419 {
6420 	uint64_t orig_bw;
6421 
6422 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6423 		/* We never apply a zero measurement */
6424 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6425 				    0, 0, 0, 0, 0, 0);
6426 		return;
6427 	}
6428 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6429 		bbr->r_ctl.r_measurement_count++;
6430 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6431 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6432 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6433 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6434 			    0, 0, 0, 0, 0, 0);
6435 	if (orig_bw &&
6436 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6437 		if (bbr->bbr_hdrw_pacing) {
6438 			/*
6439 			 * Apply a new rate to the hardware
6440 			 * possibly.
6441 			 */
6442 			bbr_update_hardware_pacing_rate(bbr, cts);
6443 		}
6444 		bbr_set_state_target(bbr, __LINE__);
6445 		tcp_bbr_tso_size_check(bbr, cts);
6446 		if (bbr->r_recovery_bw)  {
6447 			bbr_setup_red_bw(bbr, cts);
6448 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6449 		}
6450 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6451 		tcp_bbr_tso_size_check(bbr, cts);
6452 }
6453 
6454 static void
6455 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6456 {
6457 	if (bbr->rc_in_persist == 0) {
6458 		/* We log only when not in persist */
6459 		/* Translate to a Bytes Per Second */
6460 		uint64_t tim, bw, ts_diff, ts_bw;
6461 		uint32_t delivered;
6462 
6463 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6464 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6465 		else
6466 			tim = 1;
6467 		/*
6468 		 * Now that we have processed the tim (skipping the sample
6469 		 * or possibly updating the time, go ahead and
6470 		 * calculate the cdr.
6471 		 */
6472 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6473 		bw = (uint64_t)delivered;
6474 		bw *= (uint64_t)USECS_IN_SECOND;
6475 		bw /= tim;
6476 		if (bw == 0) {
6477 			/* We must have a calculatable amount */
6478 			return;
6479 		}
6480 		/*
6481 		 * If we are using this b/w shove it in now so we
6482 		 * can see in the trace viewer if it gets over-ridden.
6483 		 */
6484 		if (rsm->r_ts_valid &&
6485 		    bbr->rc_ts_valid &&
6486 		    bbr->rc_ts_clock_set &&
6487 		    (bbr->rc_ts_cant_be_used == 0) &&
6488 		    bbr->rc_use_ts_limit) {
6489 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6490 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6491 			if ((delivered == 0) ||
6492 			    (rtt < 1000)) {
6493 				/* Can't use the ts */
6494 				bbr_log_type_bbrupd(bbr, 61, cts,
6495 						    ts_diff,
6496 						    bbr->r_ctl.last_inbound_ts,
6497 						    rsm->r_del_ack_ts, 0,
6498 						    0, 0, 0, delivered);
6499 			} else {
6500 				ts_bw = (uint64_t)delivered;
6501 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6502 				ts_bw /= ts_diff;
6503 				bbr_log_type_bbrupd(bbr, 62, cts,
6504 						    (ts_bw >> 32),
6505 						    (ts_bw & 0xffffffff), 0, 0,
6506 						    0, 0, ts_diff, delivered);
6507 				if ((bbr->ts_can_raise) &&
6508 				    (ts_bw > bw)) {
6509 					bbr_log_type_bbrupd(bbr, 8, cts,
6510 							    delivered,
6511 							    ts_diff,
6512 							    (bw >> 32),
6513 							    (bw & 0x00000000ffffffff),
6514 							    0, 0, 0, 0);
6515 					bw = ts_bw;
6516 				} else if (ts_bw && (ts_bw < bw)) {
6517 					bbr_log_type_bbrupd(bbr, 7, cts,
6518 							    delivered,
6519 							    ts_diff,
6520 							    (bw >> 32),
6521 							    (bw & 0x00000000ffffffff),
6522 							    0, 0, 0, 0);
6523 					bw = ts_bw;
6524 				}
6525 			}
6526 		}
6527 		if (rsm->r_first_sent_time &&
6528 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6529 			uint64_t sbw, sti;
6530 			/*
6531 			 * We use what was in flight at the time of our
6532 			 * send  and the size of this send to figure
6533 			 * out what we have been sending at (amount).
6534 			 * For the time we take from the time of
6535 			 * the send of the first send outstanding
6536 			 * until this send plus this sends pacing
6537 			 * time. This gives us a good calculation
6538 			 * as to the rate we have been sending at.
6539 			 */
6540 
6541 			sbw = (uint64_t)(rsm->r_flight_at_send);
6542 			sbw *= (uint64_t)USECS_IN_SECOND;
6543 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6544 			sti += rsm->r_pacing_delay;
6545 			sbw /= sti;
6546 			if (sbw < bw) {
6547 				bbr_log_type_bbrupd(bbr, 6, cts,
6548 						    delivered,
6549 						    (uint32_t)sti,
6550 						    (bw >> 32),
6551 						    (uint32_t)bw,
6552 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6553 						    (uint32_t)sbw);
6554 				bw = sbw;
6555 			}
6556 		}
6557 		/* Use the google algorithm for b/w measurements */
6558 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6559 		if ((rsm->r_app_limited == 0) ||
6560 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6561 			tcp_bbr_commit_bw(bbr, cts);
6562 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6563 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6564 		}
6565 	}
6566 }
6567 
6568 static void
6569 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6570 {
6571 	if (bbr->rc_in_persist == 0) {
6572 		/* We log only when not in persist */
6573 		/* Translate to a Bytes Per Second */
6574 		uint64_t tim, bw;
6575 		uint32_t delivered;
6576 		int no_apply = 0;
6577 
6578 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6579 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6580 		else
6581 			tim = 1;
6582 		/*
6583 		 * Now that we have processed the tim (skipping the sample
6584 		 * or possibly updating the time, go ahead and
6585 		 * calculate the cdr.
6586 		 */
6587 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6588 		bw = (uint64_t)delivered;
6589 		bw *= (uint64_t)USECS_IN_SECOND;
6590 		bw /= tim;
6591 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6592 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6593 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6594 
6595 			no_apply = 1;
6596 		}
6597 		/*
6598 		 * If we are using this b/w shove it in now so we
6599 		 * can see in the trace viewer if it gets over-ridden.
6600 		 */
6601 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6602 		/* Gate by the sending rate */
6603 		if (rsm->r_first_sent_time &&
6604 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6605 			uint64_t sbw, sti;
6606 			/*
6607 			 * We use what was in flight at the time of our
6608 			 * send  and the size of this send to figure
6609 			 * out what we have been sending at (amount).
6610 			 * For the time we take from the time of
6611 			 * the send of the first send outstanding
6612 			 * until this send plus this sends pacing
6613 			 * time. This gives us a good calculation
6614 			 * as to the rate we have been sending at.
6615 			 */
6616 
6617 			sbw = (uint64_t)(rsm->r_flight_at_send);
6618 			sbw *= (uint64_t)USECS_IN_SECOND;
6619 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6620 			sti += rsm->r_pacing_delay;
6621 			sbw /= sti;
6622 			if (sbw < bw) {
6623 				bbr_log_type_bbrupd(bbr, 6, cts,
6624 						    delivered,
6625 						    (uint32_t)sti,
6626 						    (bw >> 32),
6627 						    (uint32_t)bw,
6628 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6629 						    (uint32_t)sbw);
6630 				bw = sbw;
6631 			}
6632 			if ((sti > tim) &&
6633 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6634 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6635 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6636 				no_apply = 1;
6637 			} else
6638 				no_apply = 0;
6639 		}
6640 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6641 		if ((no_apply == 0) &&
6642 		    ((rsm->r_app_limited == 0) ||
6643 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6644 			tcp_bbr_commit_bw(bbr, cts);
6645 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6646 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6647 		}
6648 	}
6649 }
6650 
6651 static void
6652 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6653     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6654 {
6655 	uint64_t old_rttprop;
6656 
6657 	/* Update our delivery time and amount */
6658 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6659 	bbr->r_ctl.rc_del_time = cts;
6660 	if (rtt == 0) {
6661 		/*
6662 		 * 0 means its a retransmit, for now we don't use these for
6663 		 * the rest of BBR.
6664 		 */
6665 		return;
6666 	}
6667 	if ((bbr->rc_use_google == 0) &&
6668 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6669 	    (match != BBR_RTT_BY_TIMESTAMP)){
6670 		/*
6671 		 * We get a lot of rtt updates, lets not pay attention to
6672 		 * any that are not an exact match. That way we don't have
6673 		 * to worry about timestamps and the whole nonsense of
6674 		 * unsure if its a retransmission etc (if we ever had the
6675 		 * timestamp fixed to always have the last thing sent this
6676 		 * would not be a issue).
6677 		 */
6678 		return;
6679 	}
6680 	if ((bbr_no_retran && bbr->rc_use_google) &&
6681 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6682 	    (match != BBR_RTT_BY_TIMESTAMP)){
6683 		/*
6684 		 * We only do measurements in google mode
6685 		 * with bbr_no_retran on for sure things.
6686 		 */
6687 		return;
6688 	}
6689 	/* Only update srtt if we know by exact match */
6690 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6691 	if (ack_type == BBR_CUM_ACKED)
6692 		bbr->rc_ack_is_cumack = 1;
6693 	else
6694 		bbr->rc_ack_is_cumack = 0;
6695 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6696 	/*
6697 	 * Note the following code differs to the original
6698 	 * BBR spec. It calls for <= not <. However after a
6699 	 * long discussion in email with Neal, he acknowledged
6700 	 * that it should be < than so that we will have flows
6701 	 * going into probe-rtt (we were seeing cases where that
6702 	 * did not happen and caused ugly things to occur). We
6703 	 * have added this agreed upon fix to our code base.
6704 	 */
6705 	if (rtt < old_rttprop) {
6706 		/* Update when we last saw a rtt drop */
6707 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6708 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6709 	}
6710 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6711 	    match, rsm->r_start, rsm->r_flags);
6712 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6713 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6714 		/*
6715 		 * The RTT-prop moved, reset the target (may be a
6716 		 * nop for some states).
6717 		 */
6718 		bbr_set_state_target(bbr, __LINE__);
6719 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6720 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6721 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6722 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6723 			/* It went up */
6724 			bbr_check_probe_rtt_limits(bbr, cts);
6725 	}
6726 	if ((bbr->rc_use_google == 0) &&
6727 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6728 		/*
6729 		 * We don't do b/w update with
6730 		 * these since they are not really
6731 		 * reliable.
6732 		 */
6733 		return;
6734 	}
6735 	if (bbr->r_ctl.r_app_limited_until &&
6736 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6737 		/* We are no longer app-limited */
6738 		bbr->r_ctl.r_app_limited_until = 0;
6739 	}
6740 	if (bbr->rc_use_google) {
6741 		bbr_google_measurement(bbr, rsm, rtt, cts);
6742 	} else {
6743 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6744 	}
6745 }
6746 
6747 /*
6748  * Convert a timestamp that the main stack
6749  * uses (milliseconds) into one that bbr uses
6750  * (microseconds). Return that converted timestamp.
6751  */
6752 static uint32_t
6753 bbr_ts_convert(uint32_t cts) {
6754 	uint32_t sec, msec;
6755 
6756 	sec = cts / MS_IN_USEC;
6757 	msec = cts - (MS_IN_USEC * sec);
6758 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6759 }
6760 
6761 /*
6762  * Return 0 if we did not update the RTT time, return
6763  * 1 if we did.
6764  */
6765 static int
6766 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6767     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6768 {
6769 	int32_t i;
6770 	uint32_t t, uts = 0;
6771 
6772 	if ((rsm->r_flags & BBR_ACKED) ||
6773 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6774 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6775 		/* Already done */
6776 		return (0);
6777 	}
6778 	if (rsm->r_rtt_not_allowed) {
6779 		/* Not allowed */
6780 		return (0);
6781 	}
6782 	if (rsm->r_rtr_cnt == 1) {
6783 		/*
6784 		 * Only one transmit. Hopefully the normal case.
6785 		 */
6786 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6787 			t = cts - rsm->r_tim_lastsent[0];
6788 		else
6789 			t = 1;
6790 		if ((int)t <= 0)
6791 			t = 1;
6792 		bbr->r_ctl.rc_last_rtt = t;
6793 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6794 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6795 		return (1);
6796 	}
6797 	/* Convert to usecs */
6798 	if ((bbr_can_use_ts_for_rtt == 1) &&
6799 	    (bbr->rc_use_google == 1) &&
6800 	    (ack_type == BBR_CUM_ACKED) &&
6801 	    (to->to_flags & TOF_TS) &&
6802 	    (to->to_tsecr != 0)) {
6803 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6804 		if (t < 1)
6805 			t = 1;
6806 		t *= MS_IN_USEC;
6807 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6808 				    BBR_RTT_BY_TIMESTAMP,
6809 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6810 				    ack_type, to);
6811 		return (1);
6812 	}
6813 	uts = bbr_ts_convert(to->to_tsecr);
6814 	if ((to->to_flags & TOF_TS) &&
6815 	    (to->to_tsecr != 0) &&
6816 	    (ack_type == BBR_CUM_ACKED) &&
6817 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6818 		/*
6819 		 * Now which timestamp does it match? In this block the ACK
6820 		 * may be coming from a previous transmission.
6821 		 */
6822 		uint32_t fudge;
6823 
6824 		fudge = BBR_TIMER_FUDGE;
6825 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6826 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6827 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6828 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6829 					t = cts - rsm->r_tim_lastsent[i];
6830 				else
6831 					t = 1;
6832 				if ((int)t <= 0)
6833 					t = 1;
6834 				bbr->r_ctl.rc_last_rtt = t;
6835 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6836 						    rsm->r_tim_lastsent[i], ack_type, to);
6837 				if ((i + 1) < rsm->r_rtr_cnt) {
6838 					/* Likely */
6839 					return (0);
6840 				} else if (rsm->r_flags & BBR_TLP) {
6841 					bbr->rc_tlp_rtx_out = 0;
6842 				}
6843 				return (1);
6844 			}
6845 		}
6846 		/* Fall through if we can't find a matching timestamp */
6847 	}
6848 	/*
6849 	 * Ok its a SACK block that we retransmitted. or a windows
6850 	 * machine without timestamps. We can tell nothing from the
6851 	 * time-stamp since its not there or the time the peer last
6852 	 * recieved a segment that moved forward its cum-ack point.
6853 	 *
6854 	 * Lets look at the last retransmit and see what we can tell
6855 	 * (with BBR for space we only keep 2 note we have to keep
6856 	 * at least 2 so the map can not be condensed more).
6857 	 */
6858 	i = rsm->r_rtr_cnt - 1;
6859 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6860 		t = cts - rsm->r_tim_lastsent[i];
6861 	else
6862 		goto not_sure;
6863 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6864 		/*
6865 		 * We retransmitted and the ack came back in less
6866 		 * than the smallest rtt we have observed in the
6867 		 * windowed rtt. We most likey did an improper
6868 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6869 		 * the rack-draft.
6870 		 *
6871 		 * Use the prior transmission to update all the
6872 		 * information as long as there is only one prior
6873 		 * transmission.
6874 		 */
6875 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6876 #ifdef BBR_INVARIANTS
6877 			if (rsm->r_rtr_cnt == 1)
6878 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6879 #endif
6880 			i = rsm->r_rtr_cnt - 2;
6881 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6882 				t = cts - rsm->r_tim_lastsent[i];
6883 			else
6884 				t = 1;
6885 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6886 					    rsm->r_tim_lastsent[i], ack_type, to);
6887 			return (0);
6888 		} else {
6889 			/*
6890 			 * Too many prior transmissions, just
6891 			 * updated BBR delivered
6892 			 */
6893 not_sure:
6894 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6895 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6896 		}
6897 	} else {
6898 		/*
6899 		 * We retransmitted it and the retransmit did the
6900 		 * job.
6901 		 */
6902 		if (rsm->r_flags & BBR_TLP)
6903 			bbr->rc_tlp_rtx_out = 0;
6904 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6905 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6906 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6907 		else
6908 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6909 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6910 		return (1);
6911 	}
6912 	return (0);
6913 }
6914 
6915 /*
6916  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6917  */
6918 static void
6919 bbr_log_sack_passed(struct tcpcb *tp,
6920     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6921 {
6922 	struct bbr_sendmap *nrsm;
6923 
6924 	nrsm = rsm;
6925 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6926 	    bbr_head, r_tnext) {
6927 		if (nrsm == rsm) {
6928 			/* Skip original segment he is acked */
6929 			continue;
6930 		}
6931 		if (nrsm->r_flags & BBR_ACKED) {
6932 			/* Skip ack'd segments */
6933 			continue;
6934 		}
6935 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6936 			/*
6937 			 * We found one that is already marked
6938 			 * passed, we have been here before and
6939 			 * so all others below this are marked.
6940 			 */
6941 			break;
6942 		}
6943 		BBR_STAT_INC(bbr_sack_passed);
6944 		nrsm->r_flags |= BBR_SACK_PASSED;
6945 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6946 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6947 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6948 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6949 			nrsm->r_flags |= BBR_MARKED_LOST;
6950 		}
6951 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6952 	}
6953 }
6954 
6955 /*
6956  * Returns the number of bytes that were
6957  * newly ack'd by sack blocks.
6958  */
6959 static uint32_t
6960 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6961     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6962 {
6963 	int32_t times = 0;
6964 	uint32_t start, end, changed = 0;
6965 	struct bbr_sendmap *rsm, *nrsm;
6966 	int32_t used_ref = 1;
6967 	uint8_t went_back = 0, went_fwd = 0;
6968 
6969 	start = sack->start;
6970 	end = sack->end;
6971 	rsm = *prsm;
6972 	if (rsm == NULL)
6973 		used_ref = 0;
6974 
6975 	/* Do we locate the block behind where we last were? */
6976 	if (rsm && SEQ_LT(start, rsm->r_start)) {
6977 		went_back = 1;
6978 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
6979 			if (SEQ_GEQ(start, rsm->r_start) &&
6980 			    SEQ_LT(start, rsm->r_end)) {
6981 				goto do_rest_ofb;
6982 			}
6983 		}
6984 	}
6985 start_at_beginning:
6986 	went_fwd = 1;
6987 	/*
6988 	 * Ok lets locate the block where this guy is fwd from rsm (if its
6989 	 * set)
6990 	 */
6991 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
6992 		if (SEQ_GEQ(start, rsm->r_start) &&
6993 		    SEQ_LT(start, rsm->r_end)) {
6994 			break;
6995 		}
6996 	}
6997 do_rest_ofb:
6998 	if (rsm == NULL) {
6999 		/*
7000 		 * This happens when we get duplicate sack blocks with the
7001 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7002 		 * will not change there location so we would just start at
7003 		 * the end of the first one and get lost.
7004 		 */
7005 		if (tp->t_flags & TF_SENTFIN) {
7006 			/*
7007 			 * Check to see if we have not logged the FIN that
7008 			 * went out.
7009 			 */
7010 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7011 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7012 				/*
7013 				 * Ok we did not get the FIN logged.
7014 				 */
7015 				nrsm->r_end++;
7016 				rsm = nrsm;
7017 				goto do_rest_ofb;
7018 			}
7019 		}
7020 		if (times == 1) {
7021 #ifdef BBR_INVARIANTS
7022 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7023 			    tp, bbr, sack, to, prsm);
7024 #else
7025 			goto out;
7026 #endif
7027 		}
7028 		times++;
7029 		BBR_STAT_INC(bbr_sack_proc_restart);
7030 		rsm = NULL;
7031 		goto start_at_beginning;
7032 	}
7033 	/* Ok we have an ACK for some piece of rsm */
7034 	if (rsm->r_start != start) {
7035 		/*
7036 		 * Need to split this in two pieces the before and after.
7037 		 */
7038 		if (bbr_sack_mergable(rsm, start, end))
7039 			nrsm = bbr_alloc_full_limit(bbr);
7040 		else
7041 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7042 		if (nrsm == NULL) {
7043 			/* We could not allocate ignore the sack */
7044 			struct sackblk blk;
7045 
7046 			blk.start = start;
7047 			blk.end = end;
7048 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7049 			goto out;
7050 		}
7051 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7052 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7053 		if (rsm->r_in_tmap) {
7054 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7055 			nrsm->r_in_tmap = 1;
7056 		}
7057 		rsm->r_flags &= (~BBR_HAS_FIN);
7058 		rsm = nrsm;
7059 	}
7060 	if (SEQ_GEQ(end, rsm->r_end)) {
7061 		/*
7062 		 * The end of this block is either beyond this guy or right
7063 		 * at this guy.
7064 		 */
7065 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7066 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7067 			changed += (rsm->r_end - rsm->r_start);
7068 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7069 			bbr_log_sack_passed(tp, bbr, rsm);
7070 			if (rsm->r_flags & BBR_MARKED_LOST) {
7071 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7072 			}
7073 			/* Is Reordering occuring? */
7074 			if (rsm->r_flags & BBR_SACK_PASSED) {
7075 				BBR_STAT_INC(bbr_reorder_seen);
7076 				bbr->r_ctl.rc_reorder_ts = cts;
7077 				if (rsm->r_flags & BBR_MARKED_LOST) {
7078 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7079 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7080 						/* LT sampling also needs adjustment */
7081 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7082 				}
7083 			}
7084 			rsm->r_flags |= BBR_ACKED;
7085 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7086 			if (rsm->r_in_tmap) {
7087 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7088 				rsm->r_in_tmap = 0;
7089 			}
7090 		}
7091 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7092 		if (end == rsm->r_end) {
7093 			/* This block only - done */
7094 			goto out;
7095 		}
7096 		/* There is more not coverend by this rsm move on */
7097 		start = rsm->r_end;
7098 		nrsm = TAILQ_NEXT(rsm, r_next);
7099 		rsm = nrsm;
7100 		times = 0;
7101 		goto do_rest_ofb;
7102 	}
7103 	if (rsm->r_flags & BBR_ACKED) {
7104 		/* Been here done that */
7105 		goto out;
7106 	}
7107 	/* Ok we need to split off this one at the tail */
7108 	if (bbr_sack_mergable(rsm, start, end))
7109 		nrsm = bbr_alloc_full_limit(bbr);
7110 	else
7111 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7112 	if (nrsm == NULL) {
7113 		/* failed XXXrrs what can we do but loose the sack info? */
7114 		struct sackblk blk;
7115 
7116 		blk.start = start;
7117 		blk.end = end;
7118 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7119 		goto out;
7120 	}
7121 	/* Clone it */
7122 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7123 	/* The sack block does not cover this guy fully */
7124 	rsm->r_flags &= (~BBR_HAS_FIN);
7125 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7126 	if (rsm->r_in_tmap) {
7127 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7128 		nrsm->r_in_tmap = 1;
7129 	}
7130 	nrsm->r_dupack = 0;
7131 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7132 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7133 	changed += (rsm->r_end - rsm->r_start);
7134 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7135 	bbr_log_sack_passed(tp, bbr, rsm);
7136 	/* Is Reordering occuring? */
7137 	if (rsm->r_flags & BBR_MARKED_LOST) {
7138 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7139 	}
7140 	if (rsm->r_flags & BBR_SACK_PASSED) {
7141 		BBR_STAT_INC(bbr_reorder_seen);
7142 		bbr->r_ctl.rc_reorder_ts = cts;
7143 		if (rsm->r_flags & BBR_MARKED_LOST) {
7144 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7145 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7146 				/* LT sampling also needs adjustment */
7147 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7148 		}
7149 	}
7150 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7151 	rsm->r_flags |= BBR_ACKED;
7152 	if (rsm->r_in_tmap) {
7153 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7154 		rsm->r_in_tmap = 0;
7155 	}
7156 out:
7157 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7158 		/*
7159 		 * Now can we merge this newly acked
7160 		 * block with either the previous or
7161 		 * next block?
7162 		 */
7163 		nrsm = TAILQ_NEXT(rsm, r_next);
7164 		if (nrsm &&
7165 		    (nrsm->r_flags & BBR_ACKED)) {
7166 			/* yep this and next can be merged */
7167 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7168 		}
7169 		/* Now what about the previous? */
7170 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7171 		if (nrsm &&
7172 		    (nrsm->r_flags & BBR_ACKED)) {
7173 			/* yep the previous and this can be merged */
7174 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7175 		}
7176 	}
7177 	if (used_ref == 0) {
7178 		BBR_STAT_INC(bbr_sack_proc_all);
7179 	} else {
7180 		BBR_STAT_INC(bbr_sack_proc_short);
7181 	}
7182 	if (went_fwd && went_back) {
7183 		BBR_STAT_INC(bbr_sack_search_both);
7184 	} else if (went_fwd) {
7185 		BBR_STAT_INC(bbr_sack_search_fwd);
7186 	} else if (went_back) {
7187 		BBR_STAT_INC(bbr_sack_search_back);
7188 	}
7189 	/* Save off where the next seq is */
7190 	if (rsm)
7191 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7192 	else
7193 		bbr->r_ctl.rc_sacklast = NULL;
7194 	*prsm = rsm;
7195 	return (changed);
7196 }
7197 
7198 static void inline
7199 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7200 {
7201 	struct bbr_sendmap *tmap;
7202 
7203 	BBR_STAT_INC(bbr_reneges_seen);
7204 	tmap = NULL;
7205 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7206 		/* Its no longer sacked, mark it so */
7207 		uint32_t oflags;
7208 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7209 #ifdef BBR_INVARIANTS
7210 		if (rsm->r_in_tmap) {
7211 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7212 			    bbr, rsm, rsm->r_flags);
7213 		}
7214 #endif
7215 		oflags = rsm->r_flags;
7216 		if (rsm->r_flags & BBR_MARKED_LOST) {
7217 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7218 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7219 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7220 				/* LT sampling also needs adjustment */
7221 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7222 		}
7223 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7224 		rsm->r_flags |= BBR_WAS_RENEGED;
7225 		rsm->r_flags |= BBR_RXT_CLEARED;
7226 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7227 		/* Rebuild it into our tmap */
7228 		if (tmap == NULL) {
7229 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7230 			tmap = rsm;
7231 		} else {
7232 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7233 			tmap = rsm;
7234 		}
7235 		tmap->r_in_tmap = 1;
7236 		/*
7237 		 * XXXrrs Delivered? Should we do anything here?
7238 		 *
7239 		 * Of course we don't on a rxt timeout so maybe its ok that
7240 		 * we don't?
7241 		 *
7242 		 * For now lets not.
7243 		 */
7244 		rsm = TAILQ_NEXT(rsm, r_next);
7245 	}
7246 	/*
7247 	 * Now lets possibly clear the sack filter so we start recognizing
7248 	 * sacks that cover this area.
7249 	 */
7250 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7251 }
7252 
7253 static void
7254 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7255 {
7256 	struct tcp_bbr *bbr;
7257 	struct bbr_sendmap *rsm;
7258 	uint32_t cts;
7259 
7260 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7261 	cts = bbr->r_ctl.rc_rcvtime;
7262 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7263 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7264 		if ((rsm->r_end - rsm->r_start) <= 1) {
7265 			/* Log out the SYN completely */
7266 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7267 			rsm->r_rtr_bytes = 0;
7268 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7269 			if (rsm->r_in_tmap) {
7270 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7271 				rsm->r_in_tmap = 0;
7272 			}
7273 			if (bbr->r_ctl.rc_next == rsm) {
7274 				/* scoot along the marker */
7275 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7276 			}
7277 			if (to != NULL)
7278 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7279 			bbr_free(bbr, rsm);
7280 		} else {
7281 			/* There is more (Fast open)? strip out SYN. */
7282 			rsm->r_flags &= ~BBR_HAS_SYN;
7283 			rsm->r_start++;
7284 		}
7285 	}
7286 }
7287 
7288 /*
7289  * Returns the number of bytes that were
7290  * acknowledged by SACK blocks.
7291  */
7292 
7293 static uint32_t
7294 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7295     uint32_t *prev_acked)
7296 {
7297 	uint32_t changed, last_seq, entered_recovery = 0;
7298 	struct tcp_bbr *bbr;
7299 	struct bbr_sendmap *rsm;
7300 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7301 	register uint32_t th_ack;
7302 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7303 	uint32_t cts, acked, ack_point, sack_changed = 0;
7304 	uint32_t p_maxseg, maxseg, p_acked = 0;
7305 
7306 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7307 	if (tcp_get_flags(th) & TH_RST) {
7308 		/* We don't log resets */
7309 		return (0);
7310 	}
7311 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7312 	cts = bbr->r_ctl.rc_rcvtime;
7313 
7314 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7315 	changed = 0;
7316 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7317 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7318 	th_ack = th->th_ack;
7319 	if (SEQ_GT(th_ack, tp->snd_una)) {
7320 		acked = th_ack - tp->snd_una;
7321 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7322 		bbr->rc_tp->t_acktime = ticks;
7323 	} else
7324 		acked = 0;
7325 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7326 		/* Only sent here for sack processing */
7327 		goto proc_sack;
7328 	}
7329 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7330 		changed = th_ack - rsm->r_start;
7331 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7332 		/*
7333 		 * For the SYN incoming case we will not have called
7334 		 * tcp_output for the sending of the SYN, so there will be
7335 		 * no map. All other cases should probably be a panic.
7336 		 */
7337 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7338 			/*
7339 			 * We have a timestamp that can be used to generate
7340 			 * an initial RTT.
7341 			 */
7342 			uint32_t ts, now, rtt;
7343 
7344 			ts = bbr_ts_convert(to->to_tsecr);
7345 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7346 			rtt = now - ts;
7347 			if (rtt < 1)
7348 				rtt = 1;
7349 			bbr_log_type_bbrrttprop(bbr, rtt,
7350 						tp->iss, 0, cts,
7351 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7352 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7353 			changed = 1;
7354 			bbr->r_wanted_output = 1;
7355 			goto out;
7356 		}
7357 		goto proc_sack;
7358 	} else if (rsm == NULL) {
7359 		goto out;
7360 	}
7361 	if (changed) {
7362 		/*
7363 		 * The ACK point is advancing to th_ack, we must drop off
7364 		 * the packets in the rack log and calculate any eligble
7365 		 * RTT's.
7366 		 */
7367 		bbr->r_wanted_output = 1;
7368 more:
7369 		if (rsm == NULL) {
7370 			if (tp->t_flags & TF_SENTFIN) {
7371 				/* if we send a FIN we will not hav a map */
7372 				goto proc_sack;
7373 			}
7374 #ifdef BBR_INVARIANTS
7375 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7376 			    tp,
7377 			    th, tp->t_state, bbr,
7378 			    tp->snd_una, tp->snd_max, changed);
7379 #endif
7380 			goto proc_sack;
7381 		}
7382 	}
7383 	if (SEQ_LT(th_ack, rsm->r_start)) {
7384 		/* Huh map is missing this */
7385 #ifdef BBR_INVARIANTS
7386 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7387 		    rsm->r_start,
7388 		    th_ack, tp->t_state,
7389 		    bbr->r_state, bbr);
7390 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7391 #endif
7392 		goto proc_sack;
7393 	} else if (th_ack == rsm->r_start) {
7394 		/* None here to ack */
7395 		goto proc_sack;
7396 	}
7397 	/*
7398 	 * Clear the dup ack counter, it will
7399 	 * either be freed or if there is some
7400 	 * remaining we need to start it at zero.
7401 	 */
7402 	rsm->r_dupack = 0;
7403 	/* Now do we consume the whole thing? */
7404 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7405 		/* Its all consumed. */
7406 		uint32_t left;
7407 
7408 		if (rsm->r_flags & BBR_ACKED) {
7409 			/*
7410 			 * It was acked on the scoreboard -- remove it from
7411 			 * total
7412 			 */
7413 			p_acked += (rsm->r_end - rsm->r_start);
7414 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7415 			if (bbr->r_ctl.rc_sacked == 0)
7416 				bbr->r_ctl.rc_sacklast = NULL;
7417 		} else {
7418 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7419 			if (rsm->r_flags & BBR_MARKED_LOST) {
7420 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7421 			}
7422 			if (rsm->r_flags & BBR_SACK_PASSED) {
7423 				/*
7424 				 * There are acked segments ACKED on the
7425 				 * scoreboard further up. We are seeing
7426 				 * reordering.
7427 				 */
7428 				BBR_STAT_INC(bbr_reorder_seen);
7429 				bbr->r_ctl.rc_reorder_ts = cts;
7430 				if (rsm->r_flags & BBR_MARKED_LOST) {
7431 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7432 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7433 						/* LT sampling also needs adjustment */
7434 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7435 				}
7436 			}
7437 			rsm->r_flags &= ~BBR_MARKED_LOST;
7438 		}
7439 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7440 		rsm->r_rtr_bytes = 0;
7441 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7442 		if (rsm->r_in_tmap) {
7443 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7444 			rsm->r_in_tmap = 0;
7445 		}
7446 		if (bbr->r_ctl.rc_next == rsm) {
7447 			/* scoot along the marker */
7448 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7449 		}
7450 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7451 		/* Adjust the packet counts */
7452 		left = th_ack - rsm->r_end;
7453 		/* Free back to zone */
7454 		bbr_free(bbr, rsm);
7455 		if (left) {
7456 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7457 			goto more;
7458 		}
7459 		goto proc_sack;
7460 	}
7461 	if (rsm->r_flags & BBR_ACKED) {
7462 		/*
7463 		 * It was acked on the scoreboard -- remove it from total
7464 		 * for the part being cum-acked.
7465 		 */
7466 		p_acked += (rsm->r_end - rsm->r_start);
7467 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7468 		if (bbr->r_ctl.rc_sacked == 0)
7469 			bbr->r_ctl.rc_sacklast = NULL;
7470 	} else {
7471 		/*
7472 		 * It was acked up to th_ack point for the first time
7473 		 */
7474 		struct bbr_sendmap lrsm;
7475 
7476 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7477 		lrsm.r_end = th_ack;
7478 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7479 	}
7480 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7481 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7482 		/*
7483 		 * It was marked lost and partly ack'd now
7484 		 * for the first time. We lower the rc_lost_bytes
7485 		 * and still leave it MARKED.
7486 		 */
7487 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7488 	}
7489 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7490 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7491 	rsm->r_rtr_bytes = 0;
7492 	/* adjust packet count */
7493 	rsm->r_start = th_ack;
7494 proc_sack:
7495 	/* Check for reneging */
7496 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7497 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7498 		/*
7499 		 * The peer has moved snd_una up to the edge of this send,
7500 		 * i.e. one that it had previously acked. The only way that
7501 		 * can be true if the peer threw away data (space issues)
7502 		 * that it had previously sacked (else it would have given
7503 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7504 		 * markings here.
7505 		 *
7506 		 * Note we have to look to make sure th_ack is our
7507 		 * rsm->r_start in case we get an old ack where th_ack is
7508 		 * behind snd_una.
7509 		 */
7510 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7511 	}
7512 	if ((to->to_flags & TOF_SACK) == 0) {
7513 		/* We are done nothing left to log */
7514 		goto out;
7515 	}
7516 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7517 	if (rsm) {
7518 		last_seq = rsm->r_end;
7519 	} else {
7520 		last_seq = tp->snd_max;
7521 	}
7522 	/* Sack block processing */
7523 	if (SEQ_GT(th_ack, tp->snd_una))
7524 		ack_point = th_ack;
7525 	else
7526 		ack_point = tp->snd_una;
7527 	for (i = 0; i < to->to_nsacks; i++) {
7528 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7529 		    &sack, sizeof(sack));
7530 		sack.start = ntohl(sack.start);
7531 		sack.end = ntohl(sack.end);
7532 		if (SEQ_GT(sack.end, sack.start) &&
7533 		    SEQ_GT(sack.start, ack_point) &&
7534 		    SEQ_LT(sack.start, tp->snd_max) &&
7535 		    SEQ_GT(sack.end, ack_point) &&
7536 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7537 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7538 			    (SEQ_LT(sack.end, last_seq)) &&
7539 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7540 				/*
7541 				 * Not the last piece and its smaller than
7542 				 * 1/8th of a p_maxseg. We ignore this.
7543 				 */
7544 				BBR_STAT_INC(bbr_runt_sacks);
7545 				continue;
7546 			}
7547 			sack_blocks[num_sack_blks] = sack;
7548 			num_sack_blks++;
7549 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7550 		    SEQ_LEQ(sack.end, th_ack)) {
7551 			/*
7552 			 * Its a D-SACK block.
7553 			 */
7554 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7555 		}
7556 	}
7557 	if (num_sack_blks == 0)
7558 		goto out;
7559 	/*
7560 	 * Sort the SACK blocks so we can update the rack scoreboard with
7561 	 * just one pass.
7562 	 */
7563 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7564 				  num_sack_blks, th->th_ack);
7565 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7566 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7567 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7568 	num_sack_blks = new_sb;
7569 	if (num_sack_blks < 2) {
7570 		goto do_sack_work;
7571 	}
7572 	/* Sort the sacks */
7573 	for (i = 0; i < num_sack_blks; i++) {
7574 		for (j = i + 1; j < num_sack_blks; j++) {
7575 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7576 				sack = sack_blocks[i];
7577 				sack_blocks[i] = sack_blocks[j];
7578 				sack_blocks[j] = sack;
7579 			}
7580 		}
7581 	}
7582 	/*
7583 	 * Now are any of the sack block ends the same (yes some
7584 	 * implememtations send these)?
7585 	 */
7586 again:
7587 	if (num_sack_blks > 1) {
7588 		for (i = 0; i < num_sack_blks; i++) {
7589 			for (j = i + 1; j < num_sack_blks; j++) {
7590 				if (sack_blocks[i].end == sack_blocks[j].end) {
7591 					/*
7592 					 * Ok these two have the same end we
7593 					 * want the smallest end and then
7594 					 * throw away the larger and start
7595 					 * again.
7596 					 */
7597 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7598 						/*
7599 						 * The second block covers
7600 						 * more area use that
7601 						 */
7602 						sack_blocks[i].start = sack_blocks[j].start;
7603 					}
7604 					/*
7605 					 * Now collapse out the dup-sack and
7606 					 * lower the count
7607 					 */
7608 					for (k = (j + 1); k < num_sack_blks; k++) {
7609 						sack_blocks[j].start = sack_blocks[k].start;
7610 						sack_blocks[j].end = sack_blocks[k].end;
7611 						j++;
7612 					}
7613 					num_sack_blks--;
7614 					goto again;
7615 				}
7616 			}
7617 		}
7618 	}
7619 do_sack_work:
7620 	rsm = bbr->r_ctl.rc_sacklast;
7621 	for (i = 0; i < num_sack_blks; i++) {
7622 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7623 		if (acked) {
7624 			bbr->r_wanted_output = 1;
7625 			changed += acked;
7626 			sack_changed += acked;
7627 		}
7628 	}
7629 out:
7630 	*prev_acked = p_acked;
7631 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7632 		/*
7633 		 * Ok we have a high probability that we need to go in to
7634 		 * recovery since we have data sack'd
7635 		 */
7636 		struct bbr_sendmap *rsm;
7637 
7638 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7639 		if (rsm) {
7640 			/* Enter recovery */
7641 			entered_recovery = 1;
7642 			bbr->r_wanted_output = 1;
7643 			/*
7644 			 * When we enter recovery we need to assure we send
7645 			 * one packet.
7646 			 */
7647 			if (bbr->r_ctl.rc_resend == NULL) {
7648 				bbr->r_ctl.rc_resend = rsm;
7649 			}
7650 		}
7651 	}
7652 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7653 		/*
7654 		 * See if we need to rack-retransmit anything if so set it
7655 		 * up as the thing to resend assuming something else is not
7656 		 * already in that position.
7657 		 */
7658 		if (bbr->r_ctl.rc_resend == NULL) {
7659 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7660 		}
7661 	}
7662 	/*
7663 	 * We return the amount that changed via sack, this is used by the
7664 	 * ack-received code to augment what was changed between th_ack <->
7665 	 * snd_una.
7666 	 */
7667 	return (sack_changed);
7668 }
7669 
7670 static void
7671 bbr_strike_dupack(struct tcp_bbr *bbr)
7672 {
7673 	struct bbr_sendmap *rsm;
7674 
7675 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7676 	if (rsm && (rsm->r_dupack < 0xff)) {
7677 		rsm->r_dupack++;
7678 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7679 			bbr->r_wanted_output = 1;
7680 	}
7681 }
7682 
7683 /*
7684  * Return value of 1, we do not need to call bbr_process_data().
7685  * return value of 0, bbr_process_data can be called.
7686  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7687  * its unlocked and probably unsafe to touch the TCB.
7688  */
7689 static int
7690 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7691     struct tcpcb *tp, struct tcpopt *to,
7692     uint32_t tiwin, int32_t tlen,
7693     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7694 {
7695 	int32_t ourfinisacked = 0;
7696 	int32_t acked_amount;
7697 	uint16_t nsegs;
7698 	int32_t acked;
7699 	uint32_t lost, sack_changed = 0;
7700 	struct mbuf *mfree;
7701 	struct tcp_bbr *bbr;
7702 	uint32_t prev_acked = 0;
7703 
7704 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7705 	lost = bbr->r_ctl.rc_lost;
7706 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7707 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7708 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7709 		bbr->r_wanted_output = 1;
7710 		return (1);
7711 	}
7712 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7713 		/* Process the ack */
7714 		if (bbr->rc_in_persist)
7715 			tp->t_rxtshift = 0;
7716 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7717 			bbr_strike_dupack(bbr);
7718 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7719 	}
7720 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7721 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7722 		/*
7723 		 * Old ack, behind the last one rcv'd or a duplicate ack
7724 		 * with SACK info.
7725 		 */
7726 		if (th->th_ack == tp->snd_una) {
7727 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7728 			if (bbr->r_state == TCPS_SYN_SENT) {
7729 				/*
7730 				 * Special case on where we sent SYN. When
7731 				 * the SYN-ACK is processed in syn_sent
7732 				 * state it bumps the snd_una. This causes
7733 				 * us to hit here even though we did ack 1
7734 				 * byte.
7735 				 *
7736 				 * Go through the nothing left case so we
7737 				 * send data.
7738 				 */
7739 				goto nothing_left;
7740 			}
7741 		}
7742 		return (0);
7743 	}
7744 	/*
7745 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7746 	 * something we sent.
7747 	 */
7748 	if (tp->t_flags & TF_NEEDSYN) {
7749 		/*
7750 		 * T/TCP: Connection was half-synchronized, and our SYN has
7751 		 * been ACK'd (so connection is now fully synchronized).  Go
7752 		 * to non-starred state, increment snd_una for ACK of SYN,
7753 		 * and check if we can do window scaling.
7754 		 */
7755 		tp->t_flags &= ~TF_NEEDSYN;
7756 		tp->snd_una++;
7757 		/* Do window scaling? */
7758 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7759 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7760 			tp->rcv_scale = tp->request_r_scale;
7761 			/* Send window already scaled. */
7762 		}
7763 	}
7764 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7765 
7766 	acked = BYTES_THIS_ACK(tp, th);
7767 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7768 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7769 
7770 	/*
7771 	 * If we just performed our first retransmit, and the ACK arrives
7772 	 * within our recovery window, then it was a mistake to do the
7773 	 * retransmit in the first place.  Recover our original cwnd and
7774 	 * ssthresh, and proceed to transmit where we left off.
7775 	 */
7776 	if (tp->t_flags & TF_PREVVALID) {
7777 		tp->t_flags &= ~TF_PREVVALID;
7778 		if (tp->t_rxtshift == 1 &&
7779 		    (int)(ticks - tp->t_badrxtwin) < 0)
7780 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7781 	}
7782 	SOCKBUF_LOCK(&so->so_snd);
7783 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7784 	tp->snd_wnd -= acked_amount;
7785 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7786 	/* NB: sowwakeup_locked() does an implicit unlock. */
7787 	sowwakeup_locked(so);
7788 	m_freem(mfree);
7789 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7790 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7791 	}
7792 	tp->snd_una = th->th_ack;
7793 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7794 	if (IN_RECOVERY(tp->t_flags)) {
7795 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7796 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7797 			tcp_bbr_partialack(tp);
7798 		} else {
7799 			bbr_post_recovery(tp);
7800 		}
7801 	}
7802 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7803 		tp->snd_recover = tp->snd_una;
7804 	}
7805 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7806 		tp->snd_nxt = tp->snd_max;
7807 	}
7808 	if (tp->snd_una == tp->snd_max) {
7809 		/* Nothing left outstanding */
7810 nothing_left:
7811 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7812 		if (sbavail(&so->so_snd) == 0)
7813 			bbr->rc_tp->t_acktime = 0;
7814 		if ((sbused(&so->so_snd) == 0) &&
7815 		    (tp->t_flags & TF_SENTFIN)) {
7816 			ourfinisacked = 1;
7817 		}
7818 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7819 		if (bbr->rc_in_persist == 0) {
7820 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7821 		}
7822 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7823 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7824 		/*
7825 		 * We invalidate the last ack here since we
7826 		 * don't want to transfer forward the time
7827 		 * for our sum's calculations.
7828 		 */
7829 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7830 		    (sbavail(&so->so_snd) == 0) &&
7831 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7832 			/*
7833 			 * The socket was gone and the peer sent data, time
7834 			 * to reset him.
7835 			 */
7836 			*ret_val = 1;
7837 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7838 			/* tcp_close will kill the inp pre-log the Reset */
7839 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7840 			tp = tcp_close(tp);
7841 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7842 			BBR_STAT_INC(bbr_dropped_af_data);
7843 			return (1);
7844 		}
7845 		/* Set need output so persist might get set */
7846 		bbr->r_wanted_output = 1;
7847 	}
7848 	if (ofia)
7849 		*ofia = ourfinisacked;
7850 	return (0);
7851 }
7852 
7853 static void
7854 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7855 {
7856 	if (bbr->rc_in_persist == 0) {
7857 		bbr_timer_cancel(bbr, __LINE__, cts);
7858 		bbr->r_ctl.rc_last_delay_val = 0;
7859 		tp->t_rxtshift = 0;
7860 		bbr->rc_in_persist = 1;
7861 		bbr->r_ctl.rc_went_idle_time = cts;
7862 		/* We should be capped when rw went to 0 but just in case */
7863 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7864 		/* Time freezes for the state, so do the accounting now */
7865 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7866 			uint32_t time_in;
7867 
7868 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7869 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7870 				int32_t idx;
7871 
7872 				idx = bbr_state_val(bbr);
7873 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7874 			} else {
7875 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7876 			}
7877 		}
7878 		bbr->r_ctl.rc_bbr_state_time = cts;
7879 	}
7880 }
7881 
7882 static void
7883 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7884 {
7885 	/*
7886 	 * Note that if idle time does not exceed our
7887 	 * threshold, we do nothing continuing the state
7888 	 * transitions we were last walking through.
7889 	 */
7890 	if (idle_time >= bbr_idle_restart_threshold) {
7891 		if (bbr->rc_use_idle_restart) {
7892 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7893 			/*
7894 			 * Set our target using BBR_UNIT, so
7895 			 * we increase at a dramatic rate but
7896 			 * we stop when we get the pipe
7897 			 * full again for our current b/w estimate.
7898 			 */
7899 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7900 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7901 			bbr_set_state_target(bbr, __LINE__);
7902 			/* Now setup our gains to ramp up */
7903 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7904 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7905 			bbr_log_type_statechange(bbr, cts, __LINE__);
7906 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7907 			bbr_substate_change(bbr, cts, __LINE__, 1);
7908 		}
7909 	}
7910 }
7911 
7912 static void
7913 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7914 {
7915 	uint32_t idle_time;
7916 
7917 	if (bbr->rc_in_persist == 0)
7918 		return;
7919 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7920 	bbr->rc_in_persist = 0;
7921 	bbr->rc_hit_state_1 = 0;
7922 	bbr->r_ctl.rc_del_time = cts;
7923 	/*
7924 	 * We invalidate the last ack here since we
7925 	 * don't want to transfer forward the time
7926 	 * for our sum's calculations.
7927 	 */
7928 	if (tcp_in_hpts(bbr->rc_inp)) {
7929 		tcp_hpts_remove(bbr->rc_inp);
7930 		bbr->rc_timer_first = 0;
7931 		bbr->r_ctl.rc_hpts_flags = 0;
7932 		bbr->r_ctl.rc_last_delay_val = 0;
7933 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7934 		bbr->r_agg_early_set = 0;
7935 		bbr->r_ctl.rc_agg_early = 0;
7936 	}
7937 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7938 	if (idle_time >= bbr_rtt_probe_time) {
7939 		/*
7940 		 * This qualifies as a RTT_PROBE session since we drop the
7941 		 * data outstanding to nothing and waited more than
7942 		 * bbr_rtt_probe_time.
7943 		 */
7944 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7945 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7946 	}
7947 	tp->t_rxtshift = 0;
7948 	/*
7949 	 * If in probeBW and we have persisted more than an RTT lets do
7950 	 * special handling.
7951 	 */
7952 	/* Force a time based epoch */
7953 	bbr_set_epoch(bbr, cts, __LINE__);
7954 	/*
7955 	 * Setup the lost so we don't count anything against the guy
7956 	 * we have been stuck with during persists.
7957 	 */
7958 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7959 	/* Time un-freezes for the state */
7960 	bbr->r_ctl.rc_bbr_state_time = cts;
7961 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7962 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7963 		/*
7964 		 * If we are going back to probe-bw
7965 		 * or probe_rtt, we may need to possibly
7966 		 * do a fast restart.
7967 		 */
7968 		bbr_restart_after_idle(bbr, cts, idle_time);
7969 	}
7970 }
7971 
7972 static void
7973 bbr_collapsed_window(struct tcp_bbr *bbr)
7974 {
7975 	/*
7976 	 * Now we must walk the
7977 	 * send map and divide the
7978 	 * ones left stranded. These
7979 	 * guys can't cause us to abort
7980 	 * the connection and are really
7981 	 * "unsent". However if a buggy
7982 	 * client actually did keep some
7983 	 * of the data i.e. collapsed the win
7984 	 * and refused to ack and then opened
7985 	 * the win and acked that data. We would
7986 	 * get into an ack war, the simplier
7987 	 * method then of just pretending we
7988 	 * did not send those segments something
7989 	 * won't work.
7990 	 */
7991 	struct bbr_sendmap *rsm, *nrsm;
7992 	tcp_seq max_seq;
7993 	uint32_t maxseg;
7994 	int can_split = 0;
7995 	int fnd = 0;
7996 
7997 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
7998 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
7999 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8000 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8001 		/* Find the first seq past or at maxseq */
8002 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8003 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8004 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8005 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8006 			fnd = 1;
8007 			break;
8008 		}
8009 	}
8010 	bbr->rc_has_collapsed = 0;
8011 	if (!fnd) {
8012 		/* Nothing to do strange */
8013 		return;
8014 	}
8015 	/*
8016 	 * Now can we split?
8017 	 *
8018 	 * We don't want to split if splitting
8019 	 * would generate too many small segments
8020 	 * less we let an attacker fragment our
8021 	 * send_map and leave us out of memory.
8022 	 */
8023 	if ((max_seq != rsm->r_start) &&
8024 	    (max_seq != rsm->r_end)){
8025 		/* can we split? */
8026 		int res1, res2;
8027 
8028 		res1 = max_seq - rsm->r_start;
8029 		res2 = rsm->r_end - max_seq;
8030 		if ((res1 >= (maxseg/8)) &&
8031 		    (res2 >= (maxseg/8))) {
8032 			/* No small pieces here */
8033 			can_split = 1;
8034 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8035 			/* We are under the limit */
8036 			can_split = 1;
8037 		}
8038 	}
8039 	/* Ok do we need to split this rsm? */
8040 	if (max_seq == rsm->r_start) {
8041 		/* It's this guy no split required */
8042 		nrsm = rsm;
8043 	} else if (max_seq == rsm->r_end) {
8044 		/* It's the next one no split required. */
8045 		nrsm = TAILQ_NEXT(rsm, r_next);
8046 		if (nrsm == NULL) {
8047 			/* Huh? */
8048 			return;
8049 		}
8050 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8051 		/* yep we need to split it */
8052 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8053 		if (nrsm == NULL) {
8054 			/* failed XXXrrs what can we do mark the whole? */
8055 			nrsm = rsm;
8056 			goto no_split;
8057 		}
8058 		/* Clone it */
8059 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8060 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8061 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8062 		if (rsm->r_in_tmap) {
8063 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8064 			nrsm->r_in_tmap = 1;
8065 		}
8066 	} else {
8067 		/*
8068 		 * Split not allowed just start here just
8069 		 * use this guy.
8070 		 */
8071 		nrsm = rsm;
8072 	}
8073 no_split:
8074 	BBR_STAT_INC(bbr_collapsed_win);
8075 	/* reuse fnd as a count */
8076 	fnd = 0;
8077 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8078 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8079 		fnd++;
8080 		bbr->rc_has_collapsed = 1;
8081 	}
8082 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8083 }
8084 
8085 static void
8086 bbr_un_collapse_window(struct tcp_bbr *bbr)
8087 {
8088 	struct bbr_sendmap *rsm;
8089 	int cleared = 0;
8090 
8091 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8092 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8093 			/* Clear the flag */
8094 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8095 			cleared++;
8096 		} else
8097 			break;
8098 	}
8099 	bbr_log_type_rwnd_collapse(bbr,
8100 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8101 	bbr->rc_has_collapsed = 0;
8102 }
8103 
8104 /*
8105  * Return value of 1, the TCB is unlocked and most
8106  * likely gone, return value of 0, the TCB is still
8107  * locked.
8108  */
8109 static int
8110 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8111     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8112     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8113 {
8114 	/*
8115 	 * Update window information. Don't look at window if no ACK: TAC's
8116 	 * send garbage on first SYN.
8117 	 */
8118 	uint16_t nsegs;
8119 	int32_t tfo_syn;
8120 	struct tcp_bbr *bbr;
8121 
8122 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8123 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8124 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8125 	if ((thflags & TH_ACK) &&
8126 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8127 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8128 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8129 		/* keep track of pure window updates */
8130 		if (tlen == 0 &&
8131 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8132 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8133 		tp->snd_wnd = tiwin;
8134 		tp->snd_wl1 = th->th_seq;
8135 		tp->snd_wl2 = th->th_ack;
8136 		if (tp->snd_wnd > tp->max_sndwnd)
8137 			tp->max_sndwnd = tp->snd_wnd;
8138 		bbr->r_wanted_output = 1;
8139 	} else if (thflags & TH_ACK) {
8140 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8141 			tp->snd_wnd = tiwin;
8142 			tp->snd_wl1 = th->th_seq;
8143 			tp->snd_wl2 = th->th_ack;
8144 		}
8145 	}
8146 	if (tp->snd_wnd < ctf_outstanding(tp))
8147 		/* The peer collapsed its window on us */
8148 		bbr_collapsed_window(bbr);
8149  	else if (bbr->rc_has_collapsed)
8150 		bbr_un_collapse_window(bbr);
8151 	/* Was persist timer active and now we have window space? */
8152 	if ((bbr->rc_in_persist != 0) &&
8153 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8154 				bbr_minseg(bbr)))) {
8155 		/*
8156 		 * Make the rate persist at end of persist mode if idle long
8157 		 * enough
8158 		 */
8159 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8160 
8161 		/* Make sure we output to start the timer */
8162 		bbr->r_wanted_output = 1;
8163 	}
8164 	/* Do we need to enter persist? */
8165 	if ((bbr->rc_in_persist == 0) &&
8166 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8167 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8168 	    (tp->snd_max == tp->snd_una) &&
8169 	    sbavail(&so->so_snd) &&
8170 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8171 		/* No send window.. we must enter persist */
8172 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8173 	}
8174 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8175 		m_freem(m);
8176 		return (0);
8177 	}
8178 	/*
8179 	 * We don't support urgent data but
8180 	 * drag along the up just to make sure
8181 	 * if there is a stack switch no one
8182 	 * is surprised.
8183 	 */
8184 	tp->rcv_up = tp->rcv_nxt;
8185 
8186 	/*
8187 	 * Process the segment text, merging it into the TCP sequencing
8188 	 * queue, and arranging for acknowledgment of receipt if necessary.
8189 	 * This process logically involves adjusting tp->rcv_wnd as data is
8190 	 * presented to the user (this happens in tcp_usrreq.c, case
8191 	 * PRU_RCVD).  If a FIN has already been received on this connection
8192 	 * then we just ignore the text.
8193 	 */
8194 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8195 		   IS_FASTOPEN(tp->t_flags));
8196 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8197 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8198 		tcp_seq save_start = th->th_seq;
8199 		tcp_seq save_rnxt  = tp->rcv_nxt;
8200 		int     save_tlen  = tlen;
8201 
8202 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8203 		/*
8204 		 * Insert segment which includes th into TCP reassembly
8205 		 * queue with control block tp.  Set thflags to whether
8206 		 * reassembly now includes a segment with FIN.  This handles
8207 		 * the common case inline (segment is the next to be
8208 		 * received on an established connection, and the queue is
8209 		 * empty), avoiding linkage into and removal from the queue
8210 		 * and repetition of various conversions. Set DELACK for
8211 		 * segments received in order, but ack immediately when
8212 		 * segments are out of order (so fast retransmit can work).
8213 		 */
8214 		if (th->th_seq == tp->rcv_nxt &&
8215 		    SEGQ_EMPTY(tp) &&
8216 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8217 		    tfo_syn)) {
8218 #ifdef NETFLIX_SB_LIMITS
8219 			u_int mcnt, appended;
8220 
8221 			if (so->so_rcv.sb_shlim) {
8222 				mcnt = m_memcnt(m);
8223 				appended = 0;
8224 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8225 				    CFO_NOSLEEP, NULL) == false) {
8226 					counter_u64_add(tcp_sb_shlim_fails, 1);
8227 					m_freem(m);
8228 					return (0);
8229 				}
8230 			}
8231 
8232 #endif
8233 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8234 				bbr->bbr_segs_rcvd += max(1, nsegs);
8235 				tp->t_flags |= TF_DELACK;
8236 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8237 			} else {
8238 				bbr->r_wanted_output = 1;
8239 				tp->t_flags |= TF_ACKNOW;
8240 			}
8241 			tp->rcv_nxt += tlen;
8242 			if (tlen &&
8243 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8244 			    (tp->t_fbyte_in == 0)) {
8245 				tp->t_fbyte_in = ticks;
8246 				if (tp->t_fbyte_in == 0)
8247 					tp->t_fbyte_in = 1;
8248 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8249 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8250 			}
8251 			thflags = tcp_get_flags(th) & TH_FIN;
8252 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8253 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8254 			SOCKBUF_LOCK(&so->so_rcv);
8255 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8256 				m_freem(m);
8257 			else
8258 #ifdef NETFLIX_SB_LIMITS
8259 				appended =
8260 #endif
8261 					sbappendstream_locked(&so->so_rcv, m, 0);
8262 			/* NB: sorwakeup_locked() does an implicit unlock. */
8263 			sorwakeup_locked(so);
8264 #ifdef NETFLIX_SB_LIMITS
8265 			if (so->so_rcv.sb_shlim && appended != mcnt)
8266 				counter_fo_release(so->so_rcv.sb_shlim,
8267 				    mcnt - appended);
8268 #endif
8269 
8270 		} else {
8271 			/*
8272 			 * XXX: Due to the header drop above "th" is
8273 			 * theoretically invalid by now.  Fortunately
8274 			 * m_adj() doesn't actually frees any mbufs when
8275 			 * trimming from the head.
8276 			 */
8277 			tcp_seq temp = save_start;
8278 
8279 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8280 			tp->t_flags |= TF_ACKNOW;
8281 			if (tp->t_flags & TF_WAKESOR) {
8282 				tp->t_flags &= ~TF_WAKESOR;
8283 				/* NB: sorwakeup_locked() does an implicit unlock. */
8284 				sorwakeup_locked(so);
8285 			}
8286 		}
8287 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8288 		    (save_tlen > 0) &&
8289 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8290 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8291 				/*
8292 				 * DSACK actually handled in the fastpath
8293 				 * above.
8294 				 */
8295 				tcp_update_sack_list(tp, save_start,
8296 				    save_start + save_tlen);
8297 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8298 				if ((tp->rcv_numsacks >= 1) &&
8299 				    (tp->sackblks[0].end == save_start)) {
8300 					/*
8301 					 * Partial overlap, recorded at todrop
8302 					 * above.
8303 					 */
8304 					tcp_update_sack_list(tp,
8305 					    tp->sackblks[0].start,
8306 					    tp->sackblks[0].end);
8307 				} else {
8308 					tcp_update_dsack_list(tp, save_start,
8309 					    save_start + save_tlen);
8310 				}
8311 			} else if (tlen >= save_tlen) {
8312 				/* Update of sackblks. */
8313 				tcp_update_dsack_list(tp, save_start,
8314 				    save_start + save_tlen);
8315 			} else if (tlen > 0) {
8316 				tcp_update_dsack_list(tp, save_start,
8317 				    save_start + tlen);
8318 			}
8319 		}
8320 	} else {
8321 		m_freem(m);
8322 		thflags &= ~TH_FIN;
8323 	}
8324 
8325 	/*
8326 	 * If FIN is received ACK the FIN and let the user know that the
8327 	 * connection is closing.
8328 	 */
8329 	if (thflags & TH_FIN) {
8330 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8331 			/* The socket upcall is handled by socantrcvmore. */
8332 			socantrcvmore(so);
8333 			/*
8334 			 * If connection is half-synchronized (ie NEEDSYN
8335 			 * flag on) then delay ACK, so it may be piggybacked
8336 			 * when SYN is sent. Otherwise, since we received a
8337 			 * FIN then no more input can be expected, send ACK
8338 			 * now.
8339 			 */
8340 			if (tp->t_flags & TF_NEEDSYN) {
8341 				tp->t_flags |= TF_DELACK;
8342 				bbr_timer_cancel(bbr,
8343 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8344 			} else {
8345 				tp->t_flags |= TF_ACKNOW;
8346 			}
8347 			tp->rcv_nxt++;
8348 		}
8349 		switch (tp->t_state) {
8350 			/*
8351 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8352 			 * CLOSE_WAIT state.
8353 			 */
8354 		case TCPS_SYN_RECEIVED:
8355 			tp->t_starttime = ticks;
8356 			/* FALLTHROUGH */
8357 		case TCPS_ESTABLISHED:
8358 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8359 			break;
8360 
8361 			/*
8362 			 * If still in FIN_WAIT_1 STATE FIN has not been
8363 			 * acked so enter the CLOSING state.
8364 			 */
8365 		case TCPS_FIN_WAIT_1:
8366 			tcp_state_change(tp, TCPS_CLOSING);
8367 			break;
8368 
8369 			/*
8370 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8371 			 * starting the time-wait timer, turning off the
8372 			 * other standard timers.
8373 			 */
8374 		case TCPS_FIN_WAIT_2:
8375 			bbr->rc_timer_first = 1;
8376 			bbr_timer_cancel(bbr,
8377 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8378 			tcp_twstart(tp);
8379 			return (1);
8380 		}
8381 	}
8382 	/*
8383 	 * Return any desired output.
8384 	 */
8385 	if ((tp->t_flags & TF_ACKNOW) ||
8386 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8387 		bbr->r_wanted_output = 1;
8388 	}
8389 	return (0);
8390 }
8391 
8392 /*
8393  * Here nothing is really faster, its just that we
8394  * have broken out the fast-data path also just like
8395  * the fast-ack. Return 1 if we processed the packet
8396  * return 0 if you need to take the "slow-path".
8397  */
8398 static int
8399 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8400     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8401     uint32_t tiwin, int32_t nxt_pkt)
8402 {
8403 	uint16_t nsegs;
8404 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8405 	struct tcp_bbr *bbr;
8406 #ifdef NETFLIX_SB_LIMITS
8407 	u_int mcnt, appended;
8408 #endif
8409 
8410 	/* On the hpts and we would have called output */
8411 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8412 
8413 	/*
8414 	 * If last ACK falls within this segment's sequence numbers, record
8415 	 * the timestamp. NOTE that the test is modified according to the
8416 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8417 	 */
8418 	if (bbr->r_ctl.rc_resend != NULL) {
8419 		return (0);
8420 	}
8421 	if (tiwin && tiwin != tp->snd_wnd) {
8422 		return (0);
8423 	}
8424 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8425 		return (0);
8426 	}
8427 	if (__predict_false((to->to_flags & TOF_TS) &&
8428 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8429 		return (0);
8430 	}
8431 	if (__predict_false((th->th_ack != tp->snd_una))) {
8432 		return (0);
8433 	}
8434 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8435 		return (0);
8436 	}
8437 	if ((to->to_flags & TOF_TS) != 0 &&
8438 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8439 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8440 		tp->ts_recent = to->to_tsval;
8441 	}
8442 	/*
8443 	 * This is a pure, in-sequence data packet with nothing on the
8444 	 * reassembly queue and we have enough buffer space to take it.
8445 	 */
8446 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8447 
8448 #ifdef NETFLIX_SB_LIMITS
8449 	if (so->so_rcv.sb_shlim) {
8450 		mcnt = m_memcnt(m);
8451 		appended = 0;
8452 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8453 		    CFO_NOSLEEP, NULL) == false) {
8454 			counter_u64_add(tcp_sb_shlim_fails, 1);
8455 			m_freem(m);
8456 			return (1);
8457 		}
8458 	}
8459 #endif
8460 	/* Clean receiver SACK report if present */
8461 	if (tp->rcv_numsacks)
8462 		tcp_clean_sackreport(tp);
8463 	KMOD_TCPSTAT_INC(tcps_preddat);
8464 	tp->rcv_nxt += tlen;
8465 	if (tlen &&
8466 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8467 	    (tp->t_fbyte_in == 0)) {
8468 		tp->t_fbyte_in = ticks;
8469 		if (tp->t_fbyte_in == 0)
8470 			tp->t_fbyte_in = 1;
8471 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8472 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8473 	}
8474 	/*
8475 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8476 	 */
8477 	tp->snd_wl1 = th->th_seq;
8478 	/*
8479 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8480 	 */
8481 	tp->rcv_up = tp->rcv_nxt;
8482 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8483 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8484 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8485 
8486 	/* Add data to socket buffer. */
8487 	SOCKBUF_LOCK(&so->so_rcv);
8488 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8489 		m_freem(m);
8490 	} else {
8491 		/*
8492 		 * Set new socket buffer size. Give up when limit is
8493 		 * reached.
8494 		 */
8495 		if (newsize)
8496 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8497 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8498 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8499 
8500 #ifdef NETFLIX_SB_LIMITS
8501 		appended =
8502 #endif
8503 			sbappendstream_locked(&so->so_rcv, m, 0);
8504 		ctf_calc_rwin(so, tp);
8505 	}
8506 	/* NB: sorwakeup_locked() does an implicit unlock. */
8507 	sorwakeup_locked(so);
8508 #ifdef NETFLIX_SB_LIMITS
8509 	if (so->so_rcv.sb_shlim && mcnt != appended)
8510 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8511 #endif
8512 	if (DELAY_ACK(tp, bbr, nsegs)) {
8513 		bbr->bbr_segs_rcvd += max(1, nsegs);
8514 		tp->t_flags |= TF_DELACK;
8515 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8516 	} else {
8517 		bbr->r_wanted_output = 1;
8518 		tp->t_flags |= TF_ACKNOW;
8519 	}
8520 	return (1);
8521 }
8522 
8523 /*
8524  * This subfunction is used to try to highly optimize the
8525  * fast path. We again allow window updates that are
8526  * in sequence to remain in the fast-path. We also add
8527  * in the __predict's to attempt to help the compiler.
8528  * Note that if we return a 0, then we can *not* process
8529  * it and the caller should push the packet into the
8530  * slow-path. If we return 1, then all is well and
8531  * the packet is fully processed.
8532  */
8533 static int
8534 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8535     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8536     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8537 {
8538 	int32_t acked;
8539 	uint16_t nsegs;
8540 	uint32_t sack_changed;
8541 	uint32_t prev_acked = 0;
8542 	struct tcp_bbr *bbr;
8543 
8544 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8545 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8546 		return (0);
8547 	}
8548 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8549 		/* Above what we have sent? */
8550 		return (0);
8551 	}
8552 	if (__predict_false(tiwin == 0)) {
8553 		/* zero window */
8554 		return (0);
8555 	}
8556 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8557 		/* We need a SYN or a FIN, unlikely.. */
8558 		return (0);
8559 	}
8560 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8561 		/* Timestamp is behind .. old ack with seq wrap? */
8562 		return (0);
8563 	}
8564 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8565 		/* Still recovering */
8566 		return (0);
8567 	}
8568 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8569 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8570 		/* We are retransmitting */
8571 		return (0);
8572 	}
8573 	if (__predict_false(bbr->rc_in_persist != 0)) {
8574 		/* In persist mode */
8575 		return (0);
8576 	}
8577 	if (bbr->r_ctl.rc_sacked) {
8578 		/* We have sack holes on our scoreboard */
8579 		return (0);
8580 	}
8581 	/* Ok if we reach here, we can process a fast-ack */
8582 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8583 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8584 	/*
8585 	 * We never detect loss in fast ack [we can't
8586 	 * have a sack and can't be in recovery so
8587 	 * we always pass 0 (nothing detected)].
8588 	 */
8589 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8590 	/* Did the window get updated? */
8591 	if (tiwin != tp->snd_wnd) {
8592 		tp->snd_wnd = tiwin;
8593 		tp->snd_wl1 = th->th_seq;
8594 		if (tp->snd_wnd > tp->max_sndwnd)
8595 			tp->max_sndwnd = tp->snd_wnd;
8596 	}
8597 	/* Do we need to exit persists? */
8598 	if ((bbr->rc_in_persist != 0) &&
8599 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8600 			       bbr_minseg(bbr)))) {
8601 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8602 		bbr->r_wanted_output = 1;
8603 	}
8604 	/* Do we need to enter persists? */
8605 	if ((bbr->rc_in_persist == 0) &&
8606 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8607 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8608 	    (tp->snd_max == tp->snd_una) &&
8609 	    sbavail(&so->so_snd) &&
8610 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8611 		/* No send window.. we must enter persist */
8612 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8613 	}
8614 	/*
8615 	 * If last ACK falls within this segment's sequence numbers, record
8616 	 * the timestamp. NOTE that the test is modified according to the
8617 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8618 	 */
8619 	if ((to->to_flags & TOF_TS) != 0 &&
8620 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8621 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8622 		tp->ts_recent = to->to_tsval;
8623 	}
8624 	/*
8625 	 * This is a pure ack for outstanding data.
8626 	 */
8627 	KMOD_TCPSTAT_INC(tcps_predack);
8628 
8629 	/*
8630 	 * "bad retransmit" recovery.
8631 	 */
8632 	if (tp->t_flags & TF_PREVVALID) {
8633 		tp->t_flags &= ~TF_PREVVALID;
8634 		if (tp->t_rxtshift == 1 &&
8635 		    (int)(ticks - tp->t_badrxtwin) < 0)
8636 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8637 	}
8638 	/*
8639 	 * Recalculate the transmit timer / rtt.
8640 	 *
8641 	 * Some boxes send broken timestamp replies during the SYN+ACK
8642 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8643 	 * and blow up the retransmit timer.
8644 	 */
8645 	acked = BYTES_THIS_ACK(tp, th);
8646 
8647 #ifdef TCP_HHOOK
8648 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8649 	hhook_run_tcp_est_in(tp, th, to);
8650 #endif
8651 
8652 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8653 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8654 	sbdrop(&so->so_snd, acked);
8655 
8656 	if (SEQ_GT(th->th_ack, tp->snd_una))
8657 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8658 	tp->snd_una = th->th_ack;
8659 	if (tp->snd_wnd < ctf_outstanding(tp))
8660 		/* The peer collapsed its window on us */
8661 		bbr_collapsed_window(bbr);
8662 	else if (bbr->rc_has_collapsed)
8663 		bbr_un_collapse_window(bbr);
8664 
8665 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8666 		tp->snd_recover = tp->snd_una;
8667 	}
8668 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8669 	/*
8670 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8671 	 */
8672 	tp->snd_wl2 = th->th_ack;
8673 	m_freem(m);
8674 	/*
8675 	 * If all outstanding data are acked, stop retransmit timer,
8676 	 * otherwise restart timer using current (possibly backed-off)
8677 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8678 	 * If data are ready to send, let tcp_output decide between more
8679 	 * output or persist.
8680 	 * Wake up the socket if we have room to write more.
8681 	 */
8682 	sowwakeup(so);
8683 	if (tp->snd_una == tp->snd_max) {
8684 		/* Nothing left outstanding */
8685 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8686 		if (sbavail(&so->so_snd) == 0)
8687 			bbr->rc_tp->t_acktime = 0;
8688 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8689 		if (bbr->rc_in_persist == 0) {
8690 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8691 		}
8692 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8693 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8694 		/*
8695 		 * We invalidate the last ack here since we
8696 		 * don't want to transfer forward the time
8697 		 * for our sum's calculations.
8698 		 */
8699 		bbr->r_wanted_output = 1;
8700 	}
8701 	if (sbavail(&so->so_snd)) {
8702 		bbr->r_wanted_output = 1;
8703 	}
8704 	return (1);
8705 }
8706 
8707 /*
8708  * Return value of 1, the TCB is unlocked and most
8709  * likely gone, return value of 0, the TCB is still
8710  * locked.
8711  */
8712 static int
8713 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8714     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8715     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8716 {
8717 	int32_t todrop;
8718 	int32_t ourfinisacked = 0;
8719 	struct tcp_bbr *bbr;
8720 	int32_t ret_val = 0;
8721 
8722 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8723 
8724 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8725 	ctf_calc_rwin(so, tp);
8726 	/*
8727 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8728 	 * SYN, drop the input. if seg contains a RST, then drop the
8729 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8730 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8731 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8732 	 * not support ECN so we will not say we are capable. if SYN has
8733 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8734 	 * segment to be acked (eventually) continue processing rest of
8735 	 * data/controls, beginning with URG
8736 	 */
8737 	if ((thflags & TH_ACK) &&
8738 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8739 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8740 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8741 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8742 		return (1);
8743 	}
8744 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8745 		TCP_PROBE5(connect__refused, NULL, tp,
8746 		    mtod(m, const char *), tp, th);
8747 		tp = tcp_drop(tp, ECONNREFUSED);
8748 		ctf_do_drop(m, tp);
8749 		return (1);
8750 	}
8751 	if (thflags & TH_RST) {
8752 		ctf_do_drop(m, tp);
8753 		return (1);
8754 	}
8755 	if (!(thflags & TH_SYN)) {
8756 		ctf_do_drop(m, tp);
8757 		return (1);
8758 	}
8759 	tp->irs = th->th_seq;
8760 	tcp_rcvseqinit(tp);
8761 	if (thflags & TH_ACK) {
8762 		int tfo_partial = 0;
8763 
8764 		KMOD_TCPSTAT_INC(tcps_connects);
8765 		soisconnected(so);
8766 #ifdef MAC
8767 		mac_socketpeer_set_from_mbuf(m, so);
8768 #endif
8769 		/* Do window scaling on this connection? */
8770 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8771 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8772 			tp->rcv_scale = tp->request_r_scale;
8773 		}
8774 		tp->rcv_adv += min(tp->rcv_wnd,
8775 		    TCP_MAXWIN << tp->rcv_scale);
8776 		/*
8777 		 * If not all the data that was sent in the TFO SYN
8778 		 * has been acked, resend the remainder right away.
8779 		 */
8780 		if (IS_FASTOPEN(tp->t_flags) &&
8781 		    (tp->snd_una != tp->snd_max)) {
8782 			tp->snd_nxt = th->th_ack;
8783 			tfo_partial = 1;
8784 		}
8785 		/*
8786 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8787 		 * will be turned on later.
8788 		 */
8789 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8790 			bbr->bbr_segs_rcvd += 1;
8791 			tp->t_flags |= TF_DELACK;
8792 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8793 		} else {
8794 			bbr->r_wanted_output = 1;
8795 			tp->t_flags |= TF_ACKNOW;
8796 		}
8797 		if (SEQ_GT(th->th_ack, tp->iss)) {
8798 			/*
8799 			 * The SYN is acked
8800 			 * handle it specially.
8801 			 */
8802 			bbr_log_syn(tp, to);
8803 		}
8804 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8805 			/*
8806 			 * We advance snd_una for the
8807 			 * fast open case. If th_ack is
8808 			 * acknowledging data beyond
8809 			 * snd_una we can't just call
8810 			 * ack-processing since the
8811 			 * data stream in our send-map
8812 			 * will start at snd_una + 1 (one
8813 			 * beyond the SYN). If its just
8814 			 * equal we don't need to do that
8815 			 * and there is no send_map.
8816 			 */
8817 			tp->snd_una++;
8818 		}
8819 		/*
8820 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8821 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8822 		 */
8823 		tp->t_starttime = ticks;
8824 		if (tp->t_flags & TF_NEEDFIN) {
8825 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8826 			tp->t_flags &= ~TF_NEEDFIN;
8827 			thflags &= ~TH_SYN;
8828 		} else {
8829 			tcp_state_change(tp, TCPS_ESTABLISHED);
8830 			TCP_PROBE5(connect__established, NULL, tp,
8831 			    mtod(m, const char *), tp, th);
8832 			cc_conn_init(tp);
8833 		}
8834 	} else {
8835 		/*
8836 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8837 		 * open.  If segment contains CC option and there is a
8838 		 * cached CC, apply TAO test. If it succeeds, connection is *
8839 		 * half-synchronized. Otherwise, do 3-way handshake:
8840 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8841 		 * there was no CC option, clear cached CC value.
8842 		 */
8843 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
8844 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8845 	}
8846 	/*
8847 	 * Advance th->th_seq to correspond to first data byte. If data,
8848 	 * trim to stay within window, dropping FIN if necessary.
8849 	 */
8850 	th->th_seq++;
8851 	if (tlen > tp->rcv_wnd) {
8852 		todrop = tlen - tp->rcv_wnd;
8853 		m_adj(m, -todrop);
8854 		tlen = tp->rcv_wnd;
8855 		thflags &= ~TH_FIN;
8856 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8857 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8858 	}
8859 	tp->snd_wl1 = th->th_seq - 1;
8860 	tp->rcv_up = th->th_seq;
8861 	/*
8862 	 * Client side of transaction: already sent SYN and data. If the
8863 	 * remote host used T/TCP to validate the SYN, our data will be
8864 	 * ACK'd; if so, enter normal data segment processing in the middle
8865 	 * of step 5, ack processing. Otherwise, goto step 6.
8866 	 */
8867 	if (thflags & TH_ACK) {
8868 		if ((to->to_flags & TOF_TS) != 0) {
8869 			uint32_t t, rtt;
8870 
8871 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8872 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8873 				rtt = t - to->to_tsecr;
8874 				if (rtt == 0) {
8875 					rtt = 1;
8876 				}
8877 				rtt *= MS_IN_USEC;
8878 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8879 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8880 						       rtt, bbr->r_ctl.rc_rcvtime);
8881 			}
8882 		}
8883 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8884 			return (ret_val);
8885 		/* We may have changed to FIN_WAIT_1 above */
8886 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8887 			/*
8888 			 * In FIN_WAIT_1 STATE in addition to the processing
8889 			 * for the ESTABLISHED state if our FIN is now
8890 			 * acknowledged then enter FIN_WAIT_2.
8891 			 */
8892 			if (ourfinisacked) {
8893 				/*
8894 				 * If we can't receive any more data, then
8895 				 * closing user can proceed. Starting the
8896 				 * timer is contrary to the specification,
8897 				 * but if we don't get a FIN we'll hang
8898 				 * forever.
8899 				 *
8900 				 * XXXjl: we should release the tp also, and
8901 				 * use a compressed state.
8902 				 */
8903 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8904 					soisdisconnected(so);
8905 					tcp_timer_activate(tp, TT_2MSL,
8906 					    (tcp_fast_finwait2_recycle ?
8907 					    tcp_finwait2_timeout :
8908 					    TP_MAXIDLE(tp)));
8909 				}
8910 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8911 			}
8912 		}
8913 	}
8914 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8915 	    tiwin, thflags, nxt_pkt));
8916 }
8917 
8918 /*
8919  * Return value of 1, the TCB is unlocked and most
8920  * likely gone, return value of 0, the TCB is still
8921  * locked.
8922  */
8923 static int
8924 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8925 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8926 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8927 {
8928 	int32_t ourfinisacked = 0;
8929 	int32_t ret_val;
8930 	struct tcp_bbr *bbr;
8931 
8932 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8933 
8934 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8935 	ctf_calc_rwin(so, tp);
8936 	if ((thflags & TH_ACK) &&
8937 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8938 	     SEQ_GT(th->th_ack, tp->snd_max))) {
8939 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8940 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8941 		return (1);
8942 	}
8943 	if (IS_FASTOPEN(tp->t_flags)) {
8944 		/*
8945 		 * When a TFO connection is in SYN_RECEIVED, the only valid
8946 		 * packets are the initial SYN, a retransmit/copy of the
8947 		 * initial SYN (possibly with a subset of the original
8948 		 * data), a valid ACK, a FIN, or a RST.
8949 		 */
8950 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
8951 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8952 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8953 			return (1);
8954 		} else if (thflags & TH_SYN) {
8955 			/* non-initial SYN is ignored */
8956 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
8957 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
8958 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
8959 				ctf_do_drop(m, NULL);
8960 				return (0);
8961 			}
8962 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
8963 			ctf_do_drop(m, NULL);
8964 			return (0);
8965 		}
8966 	}
8967 	if ((thflags & TH_RST) ||
8968 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
8969 		return (ctf_process_rst(m, th, so, tp));
8970 	/*
8971 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
8972 	 * it's less than ts_recent, drop it.
8973 	 */
8974 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
8975 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
8976 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
8977 			return (ret_val);
8978 	}
8979 	/*
8980 	 * In the SYN-RECEIVED state, validate that the packet belongs to
8981 	 * this connection before trimming the data to fit the receive
8982 	 * window.  Check the sequence number versus IRS since we know the
8983 	 * sequence numbers haven't wrapped.  This is a partial fix for the
8984 	 * "LAND" DoS attack.
8985 	 */
8986 	if (SEQ_LT(th->th_seq, tp->irs)) {
8987 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8988 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8989 		return (1);
8990 	}
8991 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
8992 		return (ret_val);
8993 	}
8994 	/*
8995 	 * If last ACK falls within this segment's sequence numbers, record
8996 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
8997 	 * from the latest proposal of the tcplw@cray.com list (Braden
8998 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
8999 	 * with our earlier PAWS tests, so this check should be solely
9000 	 * predicated on the sequence space of this segment. 3) That we
9001 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9002 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9003 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9004 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9005 	 * p.869. In such cases, we can still calculate the RTT correctly
9006 	 * when RCV.NXT == Last.ACK.Sent.
9007 	 */
9008 	if ((to->to_flags & TOF_TS) != 0 &&
9009 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9010 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9011 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9012 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9013 		tp->ts_recent = to->to_tsval;
9014 	}
9015 	tp->snd_wnd = tiwin;
9016 	/*
9017 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9018 	 * is on (half-synchronized state), then queue data for later
9019 	 * processing; else drop segment and return.
9020 	 */
9021 	if ((thflags & TH_ACK) == 0) {
9022 		if (IS_FASTOPEN(tp->t_flags)) {
9023 			cc_conn_init(tp);
9024 		}
9025 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9026 					 tiwin, thflags, nxt_pkt));
9027 	}
9028 	KMOD_TCPSTAT_INC(tcps_connects);
9029 	if (tp->t_flags & TF_SONOTCONN) {
9030 		tp->t_flags &= ~TF_SONOTCONN;
9031 		soisconnected(so);
9032 	}
9033 	/* Do window scaling? */
9034 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9035 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9036 		tp->rcv_scale = tp->request_r_scale;
9037 	}
9038 	/*
9039 	 * ok for the first time in lets see if we can use the ts to figure
9040 	 * out what the initial RTT was.
9041 	 */
9042 	if ((to->to_flags & TOF_TS) != 0) {
9043 		uint32_t t, rtt;
9044 
9045 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9046 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9047 			rtt = t - to->to_tsecr;
9048 			if (rtt == 0) {
9049 				rtt = 1;
9050 			}
9051 			rtt *= MS_IN_USEC;
9052 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9053 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9054 		}
9055 	}
9056 	/* Drop off any SYN in the send map (probably not there)  */
9057 	if (thflags & TH_ACK)
9058 		bbr_log_syn(tp, to);
9059 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9060 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9061 		tp->t_tfo_pending = NULL;
9062 	}
9063 	/*
9064 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9065 	 * FIN-WAIT-1
9066 	 */
9067 	tp->t_starttime = ticks;
9068 	if (tp->t_flags & TF_NEEDFIN) {
9069 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9070 		tp->t_flags &= ~TF_NEEDFIN;
9071 	} else {
9072 		tcp_state_change(tp, TCPS_ESTABLISHED);
9073 		TCP_PROBE5(accept__established, NULL, tp,
9074 			   mtod(m, const char *), tp, th);
9075 		/*
9076 		 * TFO connections call cc_conn_init() during SYN
9077 		 * processing.  Calling it again here for such connections
9078 		 * is not harmless as it would undo the snd_cwnd reduction
9079 		 * that occurs when a TFO SYN|ACK is retransmitted.
9080 		 */
9081 		if (!IS_FASTOPEN(tp->t_flags))
9082 			cc_conn_init(tp);
9083 	}
9084 	/*
9085 	 * Account for the ACK of our SYN prior to
9086 	 * regular ACK processing below, except for
9087 	 * simultaneous SYN, which is handled later.
9088 	 */
9089 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9090 		tp->snd_una++;
9091 	/*
9092 	 * If segment contains data or ACK, will call tcp_reass() later; if
9093 	 * not, do so now to pass queued data to user.
9094 	 */
9095 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9096 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9097 			(struct mbuf *)0);
9098 		if (tp->t_flags & TF_WAKESOR) {
9099 			tp->t_flags &= ~TF_WAKESOR;
9100 			/* NB: sorwakeup_locked() does an implicit unlock. */
9101 			sorwakeup_locked(so);
9102 		}
9103 	}
9104 	tp->snd_wl1 = th->th_seq - 1;
9105 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9106 		return (ret_val);
9107 	}
9108 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9109 		/* We could have went to FIN_WAIT_1 (or EST) above */
9110 		/*
9111 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9112 		 * ESTABLISHED state if our FIN is now acknowledged then
9113 		 * enter FIN_WAIT_2.
9114 		 */
9115 		if (ourfinisacked) {
9116 			/*
9117 			 * If we can't receive any more data, then closing
9118 			 * user can proceed. Starting the timer is contrary
9119 			 * to the specification, but if we don't get a FIN
9120 			 * we'll hang forever.
9121 			 *
9122 			 * XXXjl: we should release the tp also, and use a
9123 			 * compressed state.
9124 			 */
9125 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9126 				soisdisconnected(so);
9127 				tcp_timer_activate(tp, TT_2MSL,
9128 						   (tcp_fast_finwait2_recycle ?
9129 						    tcp_finwait2_timeout :
9130 						    TP_MAXIDLE(tp)));
9131 			}
9132 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9133 		}
9134 	}
9135 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9136 				 tiwin, thflags, nxt_pkt));
9137 }
9138 
9139 /*
9140  * Return value of 1, the TCB is unlocked and most
9141  * likely gone, return value of 0, the TCB is still
9142  * locked.
9143  */
9144 static int
9145 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9146     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9147     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9148 {
9149 	struct tcp_bbr *bbr;
9150 	int32_t ret_val;
9151 
9152 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9153 
9154 	/*
9155 	 * Header prediction: check for the two common cases of a
9156 	 * uni-directional data xfer.  If the packet has no control flags,
9157 	 * is in-sequence, the window didn't change and we're not
9158 	 * retransmitting, it's a candidate.  If the length is zero and the
9159 	 * ack moved forward, we're the sender side of the xfer.  Just free
9160 	 * the data acked & wake any higher level process that was blocked
9161 	 * waiting for space.  If the length is non-zero and the ack didn't
9162 	 * move, we're the receiver side.  If we're getting packets in-order
9163 	 * (the reassembly queue is empty), add the data toc The socket
9164 	 * buffer and note that we need a delayed ack. Make sure that the
9165 	 * hidden state-flags are also off. Since we check for
9166 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9167 	 */
9168 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9169 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9170 		/*
9171 		 * If we have delived under 4 segments increase the initial
9172 		 * window if raised by the peer. We use this to determine
9173 		 * dynamic and static rwnd's at the end of a connection.
9174 		 */
9175 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9176 	}
9177 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9178 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9179 	    __predict_true(SEGQ_EMPTY(tp)) &&
9180 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9181 		if (tlen == 0) {
9182 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9183 			    tiwin, nxt_pkt, iptos)) {
9184 				return (0);
9185 			}
9186 		} else {
9187 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9188 			    tiwin, nxt_pkt)) {
9189 				return (0);
9190 			}
9191 		}
9192 	}
9193 	ctf_calc_rwin(so, tp);
9194 
9195 	if ((thflags & TH_RST) ||
9196 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9197 		return (ctf_process_rst(m, th, so, tp));
9198 	/*
9199 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9200 	 * synchronized state.
9201 	 */
9202 	if (thflags & TH_SYN) {
9203 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9204 		return (ret_val);
9205 	}
9206 	/*
9207 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9208 	 * it's less than ts_recent, drop it.
9209 	 */
9210 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9211 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9212 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9213 			return (ret_val);
9214 	}
9215 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9216 		return (ret_val);
9217 	}
9218 	/*
9219 	 * If last ACK falls within this segment's sequence numbers, record
9220 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9221 	 * from the latest proposal of the tcplw@cray.com list (Braden
9222 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9223 	 * with our earlier PAWS tests, so this check should be solely
9224 	 * predicated on the sequence space of this segment. 3) That we
9225 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9226 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9227 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9228 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9229 	 * p.869. In such cases, we can still calculate the RTT correctly
9230 	 * when RCV.NXT == Last.ACK.Sent.
9231 	 */
9232 	if ((to->to_flags & TOF_TS) != 0 &&
9233 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9234 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9235 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9236 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9237 		tp->ts_recent = to->to_tsval;
9238 	}
9239 	/*
9240 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9241 	 * is on (half-synchronized state), then queue data for later
9242 	 * processing; else drop segment and return.
9243 	 */
9244 	if ((thflags & TH_ACK) == 0) {
9245 		if (tp->t_flags & TF_NEEDSYN) {
9246 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9247 			    tiwin, thflags, nxt_pkt));
9248 		} else if (tp->t_flags & TF_ACKNOW) {
9249 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9250 			bbr->r_wanted_output = 1;
9251 			return (ret_val);
9252 		} else {
9253 			ctf_do_drop(m, NULL);
9254 			return (0);
9255 		}
9256 	}
9257 	/*
9258 	 * Ack processing.
9259 	 */
9260 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9261 		return (ret_val);
9262 	}
9263 	if (sbavail(&so->so_snd)) {
9264 		if (ctf_progress_timeout_check(tp, true)) {
9265 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9266 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9267 			return (1);
9268 		}
9269 	}
9270 	/* State changes only happen in bbr_process_data() */
9271 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9272 	    tiwin, thflags, nxt_pkt));
9273 }
9274 
9275 /*
9276  * Return value of 1, the TCB is unlocked and most
9277  * likely gone, return value of 0, the TCB is still
9278  * locked.
9279  */
9280 static int
9281 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9282     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9283     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9284 {
9285 	struct tcp_bbr *bbr;
9286 	int32_t ret_val;
9287 
9288 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9289 
9290 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9291 	ctf_calc_rwin(so, tp);
9292 	if ((thflags & TH_RST) ||
9293 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9294 		return (ctf_process_rst(m, th, so, tp));
9295 	/*
9296 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9297 	 * synchronized state.
9298 	 */
9299 	if (thflags & TH_SYN) {
9300 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9301 		return (ret_val);
9302 	}
9303 	/*
9304 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9305 	 * it's less than ts_recent, drop it.
9306 	 */
9307 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9308 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9309 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9310 			return (ret_val);
9311 	}
9312 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9313 		return (ret_val);
9314 	}
9315 	/*
9316 	 * If last ACK falls within this segment's sequence numbers, record
9317 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9318 	 * from the latest proposal of the tcplw@cray.com list (Braden
9319 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9320 	 * with our earlier PAWS tests, so this check should be solely
9321 	 * predicated on the sequence space of this segment. 3) That we
9322 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9323 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9324 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9325 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9326 	 * p.869. In such cases, we can still calculate the RTT correctly
9327 	 * when RCV.NXT == Last.ACK.Sent.
9328 	 */
9329 	if ((to->to_flags & TOF_TS) != 0 &&
9330 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9331 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9332 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9333 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9334 		tp->ts_recent = to->to_tsval;
9335 	}
9336 	/*
9337 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9338 	 * is on (half-synchronized state), then queue data for later
9339 	 * processing; else drop segment and return.
9340 	 */
9341 	if ((thflags & TH_ACK) == 0) {
9342 		if (tp->t_flags & TF_NEEDSYN) {
9343 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9344 			    tiwin, thflags, nxt_pkt));
9345 		} else if (tp->t_flags & TF_ACKNOW) {
9346 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9347 			bbr->r_wanted_output = 1;
9348 			return (ret_val);
9349 		} else {
9350 			ctf_do_drop(m, NULL);
9351 			return (0);
9352 		}
9353 	}
9354 	/*
9355 	 * Ack processing.
9356 	 */
9357 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9358 		return (ret_val);
9359 	}
9360 	if (sbavail(&so->so_snd)) {
9361 		if (ctf_progress_timeout_check(tp, true)) {
9362 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9363 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9364 			return (1);
9365 		}
9366 	}
9367 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9368 	    tiwin, thflags, nxt_pkt));
9369 }
9370 
9371 static int
9372 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9373     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9374 {
9375 
9376 	if (bbr->rc_allow_data_af_clo == 0) {
9377 close_now:
9378 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9379 		/* tcp_close will kill the inp pre-log the Reset */
9380 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9381 		tp = tcp_close(tp);
9382 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9383 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9384 		return (1);
9385 	}
9386 	if (sbavail(&so->so_snd) == 0)
9387 		goto close_now;
9388 	/* Ok we allow data that is ignored and a followup reset */
9389 	tp->rcv_nxt = th->th_seq + *tlen;
9390 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9391 	bbr->r_wanted_output = 1;
9392 	*tlen = 0;
9393 	return (0);
9394 }
9395 
9396 /*
9397  * Return value of 1, the TCB is unlocked and most
9398  * likely gone, return value of 0, the TCB is still
9399  * locked.
9400  */
9401 static int
9402 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9403     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9404     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9405 {
9406 	int32_t ourfinisacked = 0;
9407 	int32_t ret_val;
9408 	struct tcp_bbr *bbr;
9409 
9410 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9411 
9412 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9413 	ctf_calc_rwin(so, tp);
9414 	if ((thflags & TH_RST) ||
9415 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9416 		return (ctf_process_rst(m, th, so, tp));
9417 	/*
9418 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9419 	 * synchronized state.
9420 	 */
9421 	if (thflags & TH_SYN) {
9422 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9423 		return (ret_val);
9424 	}
9425 	/*
9426 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9427 	 * it's less than ts_recent, drop it.
9428 	 */
9429 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9430 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9431 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9432 			return (ret_val);
9433 	}
9434 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9435 		return (ret_val);
9436 	}
9437 	/*
9438 	 * If new data are received on a connection after the user processes
9439 	 * are gone, then RST the other end.
9440 	 * We call a new function now so we might continue and setup
9441 	 * to reset at all data being ack'd.
9442 	 */
9443 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9444 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9445 		return (1);
9446 	/*
9447 	 * If last ACK falls within this segment's sequence numbers, record
9448 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9449 	 * from the latest proposal of the tcplw@cray.com list (Braden
9450 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9451 	 * with our earlier PAWS tests, so this check should be solely
9452 	 * predicated on the sequence space of this segment. 3) That we
9453 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9454 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9455 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9456 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9457 	 * p.869. In such cases, we can still calculate the RTT correctly
9458 	 * when RCV.NXT == Last.ACK.Sent.
9459 	 */
9460 	if ((to->to_flags & TOF_TS) != 0 &&
9461 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9462 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9463 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9464 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9465 		tp->ts_recent = to->to_tsval;
9466 	}
9467 	/*
9468 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9469 	 * is on (half-synchronized state), then queue data for later
9470 	 * processing; else drop segment and return.
9471 	 */
9472 	if ((thflags & TH_ACK) == 0) {
9473 		if (tp->t_flags & TF_NEEDSYN) {
9474 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9475 			    tiwin, thflags, nxt_pkt));
9476 		} else if (tp->t_flags & TF_ACKNOW) {
9477 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9478 			bbr->r_wanted_output = 1;
9479 			return (ret_val);
9480 		} else {
9481 			ctf_do_drop(m, NULL);
9482 			return (0);
9483 		}
9484 	}
9485 	/*
9486 	 * Ack processing.
9487 	 */
9488 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9489 		return (ret_val);
9490 	}
9491 	if (ourfinisacked) {
9492 		/*
9493 		 * If we can't receive any more data, then closing user can
9494 		 * proceed. Starting the timer is contrary to the
9495 		 * specification, but if we don't get a FIN we'll hang
9496 		 * forever.
9497 		 *
9498 		 * XXXjl: we should release the tp also, and use a
9499 		 * compressed state.
9500 		 */
9501 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9502 			soisdisconnected(so);
9503 			tcp_timer_activate(tp, TT_2MSL,
9504 			    (tcp_fast_finwait2_recycle ?
9505 			    tcp_finwait2_timeout :
9506 			    TP_MAXIDLE(tp)));
9507 		}
9508 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9509 	}
9510 	if (sbavail(&so->so_snd)) {
9511 		if (ctf_progress_timeout_check(tp, true)) {
9512 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9513 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9514 			return (1);
9515 		}
9516 	}
9517 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9518 	    tiwin, thflags, nxt_pkt));
9519 }
9520 
9521 /*
9522  * Return value of 1, the TCB is unlocked and most
9523  * likely gone, return value of 0, the TCB is still
9524  * locked.
9525  */
9526 static int
9527 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9528     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9529     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9530 {
9531 	int32_t ourfinisacked = 0;
9532 	int32_t ret_val;
9533 	struct tcp_bbr *bbr;
9534 
9535 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9536 
9537 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9538 	ctf_calc_rwin(so, tp);
9539 	if ((thflags & TH_RST) ||
9540 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9541 		return (ctf_process_rst(m, th, so, tp));
9542 	/*
9543 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9544 	 * synchronized state.
9545 	 */
9546 	if (thflags & TH_SYN) {
9547 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9548 		return (ret_val);
9549 	}
9550 	/*
9551 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9552 	 * it's less than ts_recent, drop it.
9553 	 */
9554 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9555 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9556 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9557 			return (ret_val);
9558 	}
9559 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9560 		return (ret_val);
9561 	}
9562 	/*
9563 	 * If new data are received on a connection after the user processes
9564 	 * are gone, then RST the other end.
9565 	 * We call a new function now so we might continue and setup
9566 	 * to reset at all data being ack'd.
9567 	 */
9568 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9569 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9570 		return (1);
9571 	/*
9572 	 * If last ACK falls within this segment's sequence numbers, record
9573 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9574 	 * from the latest proposal of the tcplw@cray.com list (Braden
9575 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9576 	 * with our earlier PAWS tests, so this check should be solely
9577 	 * predicated on the sequence space of this segment. 3) That we
9578 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9579 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9580 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9581 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9582 	 * p.869. In such cases, we can still calculate the RTT correctly
9583 	 * when RCV.NXT == Last.ACK.Sent.
9584 	 */
9585 	if ((to->to_flags & TOF_TS) != 0 &&
9586 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9587 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9588 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9589 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9590 		tp->ts_recent = to->to_tsval;
9591 	}
9592 	/*
9593 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9594 	 * is on (half-synchronized state), then queue data for later
9595 	 * processing; else drop segment and return.
9596 	 */
9597 	if ((thflags & TH_ACK) == 0) {
9598 		if (tp->t_flags & TF_NEEDSYN) {
9599 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9600 			    tiwin, thflags, nxt_pkt));
9601 		} else if (tp->t_flags & TF_ACKNOW) {
9602 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9603 			bbr->r_wanted_output = 1;
9604 			return (ret_val);
9605 		} else {
9606 			ctf_do_drop(m, NULL);
9607 			return (0);
9608 		}
9609 	}
9610 	/*
9611 	 * Ack processing.
9612 	 */
9613 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9614 		return (ret_val);
9615 	}
9616 	if (ourfinisacked) {
9617 		tcp_twstart(tp);
9618 		m_freem(m);
9619 		return (1);
9620 	}
9621 	if (sbavail(&so->so_snd)) {
9622 		if (ctf_progress_timeout_check(tp, true)) {
9623 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9624 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9625 			return (1);
9626 		}
9627 	}
9628 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9629 	    tiwin, thflags, nxt_pkt));
9630 }
9631 
9632 /*
9633  * Return value of 1, the TCB is unlocked and most
9634  * likely gone, return value of 0, the TCB is still
9635  * locked.
9636  */
9637 static int
9638 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9639     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9640     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9641 {
9642 	int32_t ourfinisacked = 0;
9643 	int32_t ret_val;
9644 	struct tcp_bbr *bbr;
9645 
9646 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9647 
9648 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9649 	ctf_calc_rwin(so, tp);
9650 	if ((thflags & TH_RST) ||
9651 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9652 		return (ctf_process_rst(m, th, so, tp));
9653 	/*
9654 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9655 	 * synchronized state.
9656 	 */
9657 	if (thflags & TH_SYN) {
9658 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9659 		return (ret_val);
9660 	}
9661 	/*
9662 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9663 	 * it's less than ts_recent, drop it.
9664 	 */
9665 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9666 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9667 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9668 			return (ret_val);
9669 	}
9670 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9671 		return (ret_val);
9672 	}
9673 	/*
9674 	 * If new data are received on a connection after the user processes
9675 	 * are gone, then RST the other end.
9676 	 * We call a new function now so we might continue and setup
9677 	 * to reset at all data being ack'd.
9678 	 */
9679 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9680 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9681 		return (1);
9682 	/*
9683 	 * If last ACK falls within this segment's sequence numbers, record
9684 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9685 	 * from the latest proposal of the tcplw@cray.com list (Braden
9686 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9687 	 * with our earlier PAWS tests, so this check should be solely
9688 	 * predicated on the sequence space of this segment. 3) That we
9689 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9690 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9691 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9692 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9693 	 * p.869. In such cases, we can still calculate the RTT correctly
9694 	 * when RCV.NXT == Last.ACK.Sent.
9695 	 */
9696 	if ((to->to_flags & TOF_TS) != 0 &&
9697 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9698 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9699 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9700 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9701 		tp->ts_recent = to->to_tsval;
9702 	}
9703 	/*
9704 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9705 	 * is on (half-synchronized state), then queue data for later
9706 	 * processing; else drop segment and return.
9707 	 */
9708 	if ((thflags & TH_ACK) == 0) {
9709 		if (tp->t_flags & TF_NEEDSYN) {
9710 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9711 			    tiwin, thflags, nxt_pkt));
9712 		} else if (tp->t_flags & TF_ACKNOW) {
9713 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9714 			bbr->r_wanted_output = 1;
9715 			return (ret_val);
9716 		} else {
9717 			ctf_do_drop(m, NULL);
9718 			return (0);
9719 		}
9720 	}
9721 	/*
9722 	 * case TCPS_LAST_ACK: Ack processing.
9723 	 */
9724 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9725 		return (ret_val);
9726 	}
9727 	if (ourfinisacked) {
9728 		tp = tcp_close(tp);
9729 		ctf_do_drop(m, tp);
9730 		return (1);
9731 	}
9732 	if (sbavail(&so->so_snd)) {
9733 		if (ctf_progress_timeout_check(tp, true)) {
9734 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9735 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9736 			return (1);
9737 		}
9738 	}
9739 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9740 	    tiwin, thflags, nxt_pkt));
9741 }
9742 
9743 /*
9744  * Return value of 1, the TCB is unlocked and most
9745  * likely gone, return value of 0, the TCB is still
9746  * locked.
9747  */
9748 static int
9749 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9750     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9751     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9752 {
9753 	int32_t ourfinisacked = 0;
9754 	int32_t ret_val;
9755 	struct tcp_bbr *bbr;
9756 
9757 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9758 
9759 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9760 	ctf_calc_rwin(so, tp);
9761 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9762 	if ((thflags & TH_RST) ||
9763 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9764 		return (ctf_process_rst(m, th, so, tp));
9765 
9766 	/*
9767 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9768 	 * synchronized state.
9769 	 */
9770 	if (thflags & TH_SYN) {
9771 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9772 		return (ret_val);
9773 	}
9774 	/*
9775 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9776 	 * it's less than ts_recent, drop it.
9777 	 */
9778 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9779 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9780 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9781 			return (ret_val);
9782 	}
9783 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9784 		return (ret_val);
9785 	}
9786 	/*
9787 	 * If new data are received on a connection after the user processes
9788 	 * are gone, then we may RST the other end depending on the outcome
9789 	 * of bbr_check_data_after_close.
9790 	 * We call a new function now so we might continue and setup
9791 	 * to reset at all data being ack'd.
9792 	 */
9793 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9794 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9795 		return (1);
9796 	/*
9797 	 * If last ACK falls within this segment's sequence numbers, record
9798 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9799 	 * from the latest proposal of the tcplw@cray.com list (Braden
9800 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9801 	 * with our earlier PAWS tests, so this check should be solely
9802 	 * predicated on the sequence space of this segment. 3) That we
9803 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9804 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9805 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9806 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9807 	 * p.869. In such cases, we can still calculate the RTT correctly
9808 	 * when RCV.NXT == Last.ACK.Sent.
9809 	 */
9810 	if ((to->to_flags & TOF_TS) != 0 &&
9811 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9812 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9813 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9814 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9815 		tp->ts_recent = to->to_tsval;
9816 	}
9817 	/*
9818 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9819 	 * is on (half-synchronized state), then queue data for later
9820 	 * processing; else drop segment and return.
9821 	 */
9822 	if ((thflags & TH_ACK) == 0) {
9823 		if (tp->t_flags & TF_NEEDSYN) {
9824 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9825 			    tiwin, thflags, nxt_pkt));
9826 		} else if (tp->t_flags & TF_ACKNOW) {
9827 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9828 			bbr->r_wanted_output = 1;
9829 			return (ret_val);
9830 		} else {
9831 			ctf_do_drop(m, NULL);
9832 			return (0);
9833 		}
9834 	}
9835 	/*
9836 	 * Ack processing.
9837 	 */
9838 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9839 		return (ret_val);
9840 	}
9841 	if (sbavail(&so->so_snd)) {
9842 		if (ctf_progress_timeout_check(tp, true)) {
9843 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9844 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9845 			return (1);
9846 		}
9847 	}
9848 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9849 	    tiwin, thflags, nxt_pkt));
9850 }
9851 
9852 static void
9853 bbr_stop_all_timers(struct tcpcb *tp)
9854 {
9855 	struct tcp_bbr *bbr;
9856 
9857 	/*
9858 	 * Assure no timers are running.
9859 	 */
9860 	if (tcp_timer_active(tp, TT_PERSIST)) {
9861 		/* We enter in persists, set the flag appropriately */
9862 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9863 		bbr->rc_in_persist = 1;
9864 	}
9865 }
9866 
9867 static void
9868 bbr_google_mode_on(struct tcp_bbr *bbr)
9869 {
9870 	bbr->rc_use_google = 1;
9871 	bbr->rc_no_pacing = 0;
9872 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9873 	bbr->r_use_policer = bbr_policer_detection_enabled;
9874 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9875 	bbr->bbr_use_rack_cheat = 0;
9876 	bbr->r_ctl.rc_incr_tmrs = 0;
9877 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9878 	bbr->r_ctl.rc_inc_ip_oh = 0;
9879 	bbr->r_ctl.rc_inc_enet_oh = 0;
9880 	reset_time(&bbr->r_ctl.rc_delrate,
9881 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9882 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9883 			 (11 * USECS_IN_SECOND));
9884 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9885 }
9886 
9887 static void
9888 bbr_google_mode_off(struct tcp_bbr *bbr)
9889 {
9890 	bbr->rc_use_google = 0;
9891 	bbr->r_ctl.bbr_google_discount = 0;
9892 	bbr->no_pacing_until = bbr_no_pacing_until;
9893 	bbr->r_use_policer = 0;
9894 	if (bbr->no_pacing_until)
9895 		bbr->rc_no_pacing = 1;
9896 	else
9897 		bbr->rc_no_pacing = 0;
9898 	if (bbr_use_rack_resend_cheat)
9899 		bbr->bbr_use_rack_cheat = 1;
9900 	else
9901 		bbr->bbr_use_rack_cheat = 0;
9902 	if (bbr_incr_timers)
9903 		bbr->r_ctl.rc_incr_tmrs = 1;
9904 	else
9905 		bbr->r_ctl.rc_incr_tmrs = 0;
9906 	if (bbr_include_tcp_oh)
9907 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9908 	else
9909 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9910 	if (bbr_include_ip_oh)
9911 		bbr->r_ctl.rc_inc_ip_oh = 1;
9912 	else
9913 		bbr->r_ctl.rc_inc_ip_oh = 0;
9914 	if (bbr_include_enet_oh)
9915 		bbr->r_ctl.rc_inc_enet_oh = 1;
9916 	else
9917 		bbr->r_ctl.rc_inc_enet_oh = 0;
9918 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9919 	reset_time(&bbr->r_ctl.rc_delrate,
9920 		   bbr_num_pktepo_for_del_limit);
9921 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9922 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9923 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9924 }
9925 /*
9926  * Return 0 on success, non-zero on failure
9927  * which indicates the error (usually no memory).
9928  */
9929 static int
9930 bbr_init(struct tcpcb *tp)
9931 {
9932 	struct inpcb *inp = tptoinpcb(tp);
9933 	struct tcp_bbr *bbr = NULL;
9934 	uint32_t cts;
9935 
9936 	tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
9937 	if (tp->t_fb_ptr == NULL) {
9938 		/*
9939 		 * We need to allocate memory but cant. The INP and INP_INFO
9940 		 * locks and they are recursive (happens during setup. So a
9941 		 * scheme to drop the locks fails :(
9942 		 *
9943 		 */
9944 		return (ENOMEM);
9945 	}
9946 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9947 	bbr->rtt_valid = 0;
9948 	inp->inp_flags2 |= INP_CANNOT_DO_ECN;
9949 	inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
9950 	TAILQ_INIT(&bbr->r_ctl.rc_map);
9951 	TAILQ_INIT(&bbr->r_ctl.rc_free);
9952 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
9953 	bbr->rc_tp = tp;
9954 	bbr->rc_inp = inp;
9955 	cts = tcp_get_usecs(&bbr->rc_tv);
9956 	tp->t_acktime = 0;
9957 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
9958 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
9959 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
9960 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
9961 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
9962 	bbr->r_ctl.rc_min_to = bbr_min_to;
9963 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
9964 	bbr->r_ctl.bbr_lost_at_state = 0;
9965 	bbr->r_ctl.rc_lost_at_startup = 0;
9966 	bbr->rc_all_timers_stopped = 0;
9967 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
9968 	bbr->r_ctl.rc_pkt_epoch_del = 0;
9969 	bbr->r_ctl.rc_pkt_epoch = 0;
9970 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
9971 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
9972 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
9973 	bbr->r_ctl.rc_went_idle_time = cts;
9974 	bbr->rc_pacer_started = cts;
9975 	bbr->r_ctl.rc_pkt_epoch_time = cts;
9976 	bbr->r_ctl.rc_rcvtime = cts;
9977 	bbr->r_ctl.rc_bbr_state_time = cts;
9978 	bbr->r_ctl.rc_del_time = cts;
9979 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
9980 	bbr->r_ctl.last_in_probertt = cts;
9981 	bbr->skip_gain = 0;
9982 	bbr->gain_is_limited = 0;
9983 	bbr->no_pacing_until = bbr_no_pacing_until;
9984 	if (bbr->no_pacing_until)
9985 		bbr->rc_no_pacing = 1;
9986 	if (bbr_use_google_algo) {
9987 		bbr->rc_no_pacing = 0;
9988 		bbr->rc_use_google = 1;
9989 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9990 		bbr->r_use_policer = bbr_policer_detection_enabled;
9991 	} else {
9992 		bbr->rc_use_google = 0;
9993 		bbr->r_ctl.bbr_google_discount = 0;
9994 		bbr->r_use_policer = 0;
9995 	}
9996 	if (bbr_ts_limiting)
9997 		bbr->rc_use_ts_limit = 1;
9998 	else
9999 		bbr->rc_use_ts_limit = 0;
10000 	if (bbr_ts_can_raise)
10001 		bbr->ts_can_raise = 1;
10002 	else
10003 		bbr->ts_can_raise = 0;
10004 	if (V_tcp_delack_enabled == 1)
10005 		tp->t_delayed_ack = 2;
10006 	else if (V_tcp_delack_enabled == 0)
10007 		tp->t_delayed_ack = 0;
10008 	else if (V_tcp_delack_enabled < 100)
10009 		tp->t_delayed_ack = V_tcp_delack_enabled;
10010 	else
10011 		tp->t_delayed_ack = 2;
10012 	if (bbr->rc_use_google == 0)
10013 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10014 	else
10015 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10016 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10017 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10018 	bbr->rc_init_win = bbr_def_init_win;
10019 	if (tp->t_flags & TF_REQ_TSTMP)
10020 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10021 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10022 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10023 	bbr->r_init_rtt = 1;
10024 
10025 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10026 	if (bbr_allow_hdwr_pacing)
10027 		bbr->bbr_hdw_pace_ena = 1;
10028 	else
10029 		bbr->bbr_hdw_pace_ena = 0;
10030 	if (bbr_sends_full_iwnd)
10031 		bbr->bbr_init_win_cheat = 1;
10032 	else
10033 		bbr->bbr_init_win_cheat = 0;
10034 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10035 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10036 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10037 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10038 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10039 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10040 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10041 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10042 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10043 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10044 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10045 	bbr->r_ctl.rc_rtt_shrinks = cts;
10046 	if (bbr->rc_use_google) {
10047 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10048 				  FILTER_TYPE_MAX,
10049 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10050 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10051 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10052 	} else {
10053 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10054 				  FILTER_TYPE_MAX,
10055 				  bbr_num_pktepo_for_del_limit);
10056 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10057 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10058 	}
10059 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10060 	if (bbr_uses_idle_restart)
10061 		bbr->rc_use_idle_restart = 1;
10062 	else
10063 		bbr->rc_use_idle_restart = 0;
10064 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10065 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10066 	if (bbr_resends_use_tso)
10067 		bbr->rc_resends_use_tso = 1;
10068 #ifdef NETFLIX_PEAKRATE
10069 	tp->t_peakrate_thr = tp->t_maxpeakrate;
10070 #endif
10071 	if (tp->snd_una != tp->snd_max) {
10072 		/* Create a send map for the current outstanding data */
10073 		struct bbr_sendmap *rsm;
10074 
10075 		rsm = bbr_alloc(bbr);
10076 		if (rsm == NULL) {
10077 			uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10078 			tp->t_fb_ptr = NULL;
10079 			return (ENOMEM);
10080 		}
10081 		rsm->r_rtt_not_allowed = 1;
10082 		rsm->r_tim_lastsent[0] = cts;
10083 		rsm->r_rtr_cnt = 1;
10084 		rsm->r_rtr_bytes = 0;
10085 		rsm->r_start = tp->snd_una;
10086 		rsm->r_end = tp->snd_max;
10087 		rsm->r_dupack = 0;
10088 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10089 		rsm->r_ts_valid = 0;
10090 		rsm->r_del_ack_ts = tp->ts_recent;
10091 		rsm->r_del_time = cts;
10092 		if (bbr->r_ctl.r_app_limited_until)
10093 			rsm->r_app_limited = 1;
10094 		else
10095 			rsm->r_app_limited = 0;
10096 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10097 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10098 		rsm->r_in_tmap = 1;
10099 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10100 			rsm->r_bbr_state = bbr_state_val(bbr);
10101 		else
10102 			rsm->r_bbr_state = 8;
10103 	}
10104 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10105 		bbr->bbr_use_rack_cheat = 1;
10106 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10107 		bbr->r_ctl.rc_incr_tmrs = 1;
10108 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10109 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10110 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10111 		bbr->r_ctl.rc_inc_ip_oh = 1;
10112 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10113 		bbr->r_ctl.rc_inc_enet_oh = 1;
10114 
10115 	bbr_log_type_statechange(bbr, cts, __LINE__);
10116 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10117 	    (tp->t_srtt)) {
10118 		uint32_t rtt;
10119 
10120 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10121 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10122 	}
10123 	/* announce the settings and state */
10124 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10125 	tcp_bbr_tso_size_check(bbr, cts);
10126 	/*
10127 	 * Now call the generic function to start a timer. This will place
10128 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10129 	 * flags.
10130 	 */
10131 	bbr_stop_all_timers(tp);
10132 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10133 	return (0);
10134 }
10135 
10136 /*
10137  * Return 0 if we can accept the connection. Return
10138  * non-zero if we can't handle the connection. A EAGAIN
10139  * means you need to wait until the connection is up.
10140  * a EADDRNOTAVAIL means we can never handle the connection
10141  * (no SACK).
10142  */
10143 static int
10144 bbr_handoff_ok(struct tcpcb *tp)
10145 {
10146 	if ((tp->t_state == TCPS_CLOSED) ||
10147 	    (tp->t_state == TCPS_LISTEN)) {
10148 		/* Sure no problem though it may not stick */
10149 		return (0);
10150 	}
10151 	if ((tp->t_state == TCPS_SYN_SENT) ||
10152 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10153 		/*
10154 		 * We really don't know you have to get to ESTAB or beyond
10155 		 * to tell.
10156 		 */
10157 		return (EAGAIN);
10158 	}
10159 	if (tp->t_flags & TF_SENTFIN)
10160 		return (EINVAL);
10161 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10162 		return (0);
10163 	}
10164 	/*
10165 	 * If we reach here we don't do SACK on this connection so we can
10166 	 * never do rack.
10167 	 */
10168 	return (EINVAL);
10169 }
10170 
10171 static void
10172 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10173 {
10174 	if (tp->t_fb_ptr) {
10175 		struct inpcb *inp = tptoinpcb(tp);
10176 		uint32_t calc;
10177 		struct tcp_bbr *bbr;
10178 		struct bbr_sendmap *rsm;
10179 
10180 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10181 		if (bbr->r_ctl.crte)
10182 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10183 		bbr_log_flowend(bbr);
10184 		bbr->rc_tp = NULL;
10185 		/* Backout any flags2 we applied */
10186 		inp->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10187 		inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10188 		inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10189 		if (bbr->bbr_hdrw_pacing)
10190 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10191 		else
10192 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10193 		if (bbr->r_ctl.crte != NULL) {
10194 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10195 			bbr->r_ctl.crte = NULL;
10196 		}
10197 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10198 		while (rsm) {
10199 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10200 			uma_zfree(bbr_zone, rsm);
10201 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10202 		}
10203 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10204 		while (rsm) {
10205 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10206 			uma_zfree(bbr_zone, rsm);
10207 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10208 		}
10209 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10210 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10211 			BBR_STAT_INC(bbr_dynamic_rwnd);
10212 		else
10213 			BBR_STAT_INC(bbr_static_rwnd);
10214 		bbr->r_ctl.rc_free_cnt = 0;
10215 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10216 		tp->t_fb_ptr = NULL;
10217 	}
10218 	/* Make sure snd_nxt is correctly set */
10219 	tp->snd_nxt = tp->snd_max;
10220 }
10221 
10222 static void
10223 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10224 {
10225 	switch (tp->t_state) {
10226 	case TCPS_SYN_SENT:
10227 		bbr->r_state = TCPS_SYN_SENT;
10228 		bbr->r_substate = bbr_do_syn_sent;
10229 		break;
10230 	case TCPS_SYN_RECEIVED:
10231 		bbr->r_state = TCPS_SYN_RECEIVED;
10232 		bbr->r_substate = bbr_do_syn_recv;
10233 		break;
10234 	case TCPS_ESTABLISHED:
10235 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10236 		bbr->r_state = TCPS_ESTABLISHED;
10237 		bbr->r_substate = bbr_do_established;
10238 		break;
10239 	case TCPS_CLOSE_WAIT:
10240 		bbr->r_state = TCPS_CLOSE_WAIT;
10241 		bbr->r_substate = bbr_do_close_wait;
10242 		break;
10243 	case TCPS_FIN_WAIT_1:
10244 		bbr->r_state = TCPS_FIN_WAIT_1;
10245 		bbr->r_substate = bbr_do_fin_wait_1;
10246 		break;
10247 	case TCPS_CLOSING:
10248 		bbr->r_state = TCPS_CLOSING;
10249 		bbr->r_substate = bbr_do_closing;
10250 		break;
10251 	case TCPS_LAST_ACK:
10252 		bbr->r_state = TCPS_LAST_ACK;
10253 		bbr->r_substate = bbr_do_lastack;
10254 		break;
10255 	case TCPS_FIN_WAIT_2:
10256 		bbr->r_state = TCPS_FIN_WAIT_2;
10257 		bbr->r_substate = bbr_do_fin_wait_2;
10258 		break;
10259 	case TCPS_LISTEN:
10260 	case TCPS_CLOSED:
10261 	case TCPS_TIME_WAIT:
10262 	default:
10263 		break;
10264 	};
10265 }
10266 
10267 static void
10268 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10269 {
10270 	/*
10271 	 * Now what state are we going into now? Is there adjustments
10272 	 * needed?
10273 	 */
10274 	int32_t old_state;
10275 
10276 	old_state = bbr_state_val(bbr);
10277 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10278 		/* Save the lowest srtt we saw in our end of the sub-state */
10279 		bbr->rc_hit_state_1 = 0;
10280 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10281 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10282 	}
10283 	bbr->rc_bbr_substate++;
10284 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10285 		/* Cycle back to first state-> gain */
10286 		bbr->rc_bbr_substate = 0;
10287 	}
10288 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10289 		/*
10290 		 * We enter the gain(5/4) cycle (possibly less if
10291 		 * shallow buffer detection is enabled)
10292 		 */
10293 		if (bbr->skip_gain) {
10294 			/*
10295 			 * Hardware pacing has set our rate to
10296 			 * the max and limited our b/w just
10297 			 * do level i.e. no gain.
10298 			 */
10299 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10300 		} else if (bbr->gain_is_limited &&
10301 			   bbr->bbr_hdrw_pacing &&
10302 			   bbr->r_ctl.crte) {
10303 			/*
10304 			 * We can't gain above the hardware pacing
10305 			 * rate which is less than our rate + the gain
10306 			 * calculate the gain needed to reach the hardware
10307 			 * pacing rate..
10308 			 */
10309 			uint64_t bw, rate, gain_calc;
10310 
10311 			bw = bbr_get_bw(bbr);
10312 			rate = bbr->r_ctl.crte->rate;
10313 			if ((rate > bw) &&
10314 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10315 				gain_calc = (rate * BBR_UNIT) / bw;
10316 				if (gain_calc < BBR_UNIT)
10317 					gain_calc = BBR_UNIT;
10318 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10319 			} else {
10320 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10321 			}
10322 		} else
10323 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10324 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10325 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10326 		} else
10327 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10328 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10329 		bbr->rc_hit_state_1 = 1;
10330 		bbr->r_ctl.rc_exta_time_gd = 0;
10331 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10332 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10333 		if (bbr_state_drain_2_tar) {
10334 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10335 		} else
10336 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10337 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10338 	} else {
10339 		/* All other cycles hit here 2-7 */
10340 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10341 			if (bbr_sub_drain_slam_cwnd &&
10342 			    (bbr->rc_use_google == 0) &&
10343 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10344 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10345 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10346 			}
10347 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10348 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10349 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10350 			else
10351 				bbr->r_ctl.rc_exta_time_gd = 0;
10352 			if (bbr->r_ctl.rc_exta_time_gd) {
10353 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10354 				/* Now chop up the time for each state (div by 7) */
10355 				bbr->r_ctl.rc_level_state_extra /= 7;
10356 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10357 					/* Add a randomization */
10358 					bbr_randomize_extra_state_time(bbr);
10359 				}
10360 			}
10361 		}
10362 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10363 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10364 	}
10365 	if (bbr->rc_use_google) {
10366 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10367 	}
10368 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10369 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10370 	if (dolog)
10371 		bbr_log_type_statechange(bbr, cts, line);
10372 
10373 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10374 		uint32_t time_in;
10375 
10376 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10377 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10378 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10379 		} else {
10380 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10381 		}
10382 	}
10383 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10384 	bbr_set_state_target(bbr, __LINE__);
10385 	if (bbr_sub_drain_slam_cwnd &&
10386 	    (bbr->rc_use_google == 0) &&
10387 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10388 		/* Slam down the cwnd */
10389 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10390 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10391 		if (bbr_sub_drain_app_limit) {
10392 			/* Go app limited if we are on a long drain */
10393 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10394 							  ctf_flight_size(bbr->rc_tp,
10395 							      (bbr->r_ctl.rc_sacked +
10396 							       bbr->r_ctl.rc_lost_bytes)));
10397 		}
10398 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10399 	}
10400 	if (bbr->rc_lt_use_bw) {
10401 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10402 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10403 	}
10404 	/* Google changes TSO size every cycle */
10405 	if (bbr->rc_use_google)
10406 		tcp_bbr_tso_size_check(bbr, cts);
10407 	bbr->r_ctl.gain_epoch = cts;
10408 	bbr->r_ctl.rc_bbr_state_time = cts;
10409 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10410 }
10411 
10412 static void
10413 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10414 {
10415 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10416 	    (google_allow_early_out == 1) &&
10417 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10418 		/* We have reached out target flight size possibly early */
10419 		goto change_state;
10420 	}
10421 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10422 		return;
10423 	}
10424 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10425 		/*
10426 		 * Must be a rttProp movement forward before
10427 		 * we can change states.
10428 		 */
10429 		return;
10430 	}
10431 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10432 		/*
10433 		 * The needed time has passed but for
10434 		 * the gain cycle extra rules apply:
10435 		 * 1) If we have seen loss, we exit
10436 		 * 2) If we have not reached the target
10437 		 *    we stay in GAIN (gain-to-target).
10438 		 */
10439 		if (google_consider_lost && losses)
10440 			goto change_state;
10441 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10442 			return;
10443 		}
10444 	}
10445 change_state:
10446 	/* For gain we must reach our target, all others last 1 rttProp */
10447 	bbr_substate_change(bbr, cts, __LINE__, 1);
10448 }
10449 
10450 static void
10451 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10452 {
10453 	uint32_t flight, bbr_cur_cycle_time;
10454 
10455 	if (bbr->rc_use_google) {
10456 		bbr_set_probebw_google_gains(bbr, cts, losses);
10457 		return;
10458 	}
10459 	if (cts == 0) {
10460 		/*
10461 		 * Never alow cts to be 0 we
10462 		 * do this so we can judge if
10463 		 * we have set a timestamp.
10464 		 */
10465 		cts = 1;
10466 	}
10467 	if (bbr_state_is_pkt_epoch)
10468 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10469 	else
10470 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10471 
10472 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10473 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10474 			flight = ctf_flight_size(bbr->rc_tp,
10475 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10476 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10477 				/* Keep it slam down */
10478 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10479 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10480 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10481 				}
10482 				if (bbr_sub_drain_app_limit) {
10483 					/* Go app limited if we are on a long drain */
10484 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10485 				}
10486 			}
10487 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10488 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10489 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10490 				/*
10491 				 * Still here after the same time as
10492 				 * the gain. We need to drain harder
10493 				 * for the next srtt. Reduce by a set amount
10494 				 * the gain drop is capped at DRAIN states
10495 				 * value (88).
10496 				 */
10497 				bbr->r_ctl.flightsize_at_drain = flight;
10498 				if (bbr_drain_drop_mul &&
10499 				    bbr_drain_drop_div &&
10500 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10501 					/* Use your specific drop value (def 4/5 = 20%) */
10502 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10503 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10504 				} else {
10505 					/* You get drop of 20% */
10506 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10507 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10508 				}
10509 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10510 					/* Reduce our gain again to the bottom  */
10511 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10512 				}
10513 				bbr_log_exit_gain(bbr, cts, 4);
10514 				/*
10515 				 * Extend out so we wait another
10516 				 * epoch before dropping again.
10517 				 */
10518 				bbr->r_ctl.gain_epoch = cts;
10519 			}
10520 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10521 				if (bbr_sub_drain_slam_cwnd &&
10522 				    (bbr->rc_use_google == 0) &&
10523 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10524 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10525 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10526 				}
10527 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10528 				bbr_log_exit_gain(bbr, cts, 3);
10529 			}
10530 		} else {
10531 			/* Its a gain  */
10532 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10533 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10534 				goto change_state;
10535 			}
10536 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10537 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10538 			     bbr->rc_tp->snd_wnd)) {
10539 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10540 				bbr_log_exit_gain(bbr, cts, 2);
10541 			}
10542 		}
10543 		/**
10544 		 * We fall through and return always one of two things has
10545 		 * occurred.
10546 		 * 1) We are still not at target
10547 		 *    <or>
10548 		 * 2) We reached the target and set rc_bbr_state_atflight
10549 		 *    which means we no longer hit this block
10550 		 *    next time we are called.
10551 		 */
10552 		return;
10553 	}
10554 change_state:
10555 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10556 		return;
10557 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10558 		/* Less than a full time-period has passed */
10559 		return;
10560 	}
10561 	if (bbr->r_ctl.rc_level_state_extra &&
10562 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10563 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10564 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10565 		/* Less than a full time-period + extra has passed */
10566 		return;
10567 	}
10568 	if (bbr_gain_gets_extra_too &&
10569 	    bbr->r_ctl.rc_level_state_extra &&
10570 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10571 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10572 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10573 		/* Less than a full time-period + extra has passed */
10574 		return;
10575 	}
10576 	bbr_substate_change(bbr, cts, __LINE__, 1);
10577 }
10578 
10579 static uint32_t
10580 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10581 {
10582 	uint32_t mss, tar;
10583 
10584 	if (bbr->rc_use_google) {
10585 		/* Google just uses the cwnd target */
10586 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10587 	} else {
10588 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10589 			  bbr->r_ctl.rc_pace_max_segs);
10590 		/* Get the base cwnd with gain rounded to a mss */
10591 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10592 						      gain), mss);
10593 		/* Make sure it is within our min */
10594 		if (tar < get_min_cwnd(bbr))
10595 			return (get_min_cwnd(bbr));
10596 	}
10597 	return (tar);
10598 }
10599 
10600 static void
10601 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10602 {
10603 	uint32_t tar, meth;
10604 
10605 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10606 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10607 		/* Special case using old probe-rtt method */
10608 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10609 		meth = 1;
10610 	} else {
10611 		/* Non-probe-rtt case and reduced probe-rtt  */
10612 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10613 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10614 			/* For gain cycle we use the hptsi gain */
10615 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10616 			meth = 2;
10617 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10618 			/*
10619 			 * If configured, or for google all other states
10620 			 * get BBR_UNIT.
10621 			 */
10622 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10623 			meth = 3;
10624 		} else {
10625 			/*
10626 			 * Or we set a target based on the pacing gain
10627 			 * for non-google mode and default (non-configured).
10628 			 * Note we don't set a target goal below drain (192).
10629 			 */
10630 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10631 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10632 				meth = 4;
10633 			} else {
10634 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10635 				meth = 5;
10636 			}
10637 		}
10638 	}
10639 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10640 	bbr->r_ctl.rc_target_at_state = tar;
10641 }
10642 
10643 static void
10644 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10645 {
10646 	/* Change to probe_rtt */
10647 	uint32_t time_in;
10648 
10649 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10650 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10651 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10652 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10653 					  + bbr->r_ctl.rc_delivered);
10654 	/* Setup so we force feed the filter */
10655 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10656 		bbr->rc_prtt_set_ts = 1;
10657 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10658 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10659 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10660 	}
10661 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10662 	bbr->r_ctl.rc_rtt_shrinks = cts;
10663 	bbr->r_ctl.last_in_probertt = cts;
10664 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10665 	bbr->r_ctl.rc_bbr_state_time = cts;
10666 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10667 	/* We need to force the filter to update */
10668 
10669 	if ((bbr_sub_drain_slam_cwnd) &&
10670 	    bbr->rc_hit_state_1 &&
10671 	    (bbr->rc_use_google == 0) &&
10672 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10673 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10674 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10675 	} else
10676 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10677 	/* Update the lost */
10678 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10679 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10680 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10681 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10682 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10683 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10684 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10685 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10686 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10687 	} else {
10688 		/*
10689 		 * We bring it down slowly by using a hptsi gain that is
10690 		 * probably 75%. This will slowly float down our outstanding
10691 		 * without tampering with the cwnd.
10692 		 */
10693 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10694 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10695 		bbr_set_state_target(bbr, __LINE__);
10696 		if (bbr_prtt_slam_cwnd &&
10697 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10698 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10699 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10700 		}
10701 	}
10702 	if (ctf_flight_size(bbr->rc_tp,
10703 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10704 	    bbr->r_ctl.rc_target_at_state) {
10705 		/* We are at target */
10706 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10707 	} else {
10708 		/* We need to come down to reach target before our time begins */
10709 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10710 	}
10711 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10712 	BBR_STAT_INC(bbr_enter_probertt);
10713 	bbr_log_exit_gain(bbr, cts, 0);
10714 	bbr_log_type_statechange(bbr, cts, line);
10715 }
10716 
10717 static void
10718 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10719 {
10720 	/*
10721 	 * Sanity check on probe-rtt intervals.
10722 	 * In crazy situations where we are competing
10723 	 * against new-reno flows with huge buffers
10724 	 * our rtt-prop interval could come to dominate
10725 	 * things if we can't get through a full set
10726 	 * of cycles, we need to adjust it.
10727 	 */
10728 	if (bbr_can_adjust_probertt &&
10729 	    (bbr->rc_use_google == 0)) {
10730 		uint16_t val = 0;
10731 		uint32_t cur_rttp, fval, newval, baseval;
10732 
10733 		/* Are we to small and go into probe-rtt to often? */
10734 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10735 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10736 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10737 		if (bbr_is_ratio == 0) {
10738 			if (fval > bbr_rtt_probe_limit)
10739 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10740 			else
10741 				newval = cur_rttp;
10742 		} else {
10743 			int mul;
10744 
10745 			mul = fval / bbr_rtt_probe_limit;
10746 			newval = cur_rttp * mul;
10747 		}
10748 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10749 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10750 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10751 			val = 1;
10752 		} else {
10753 			/*
10754 			 * No adjustments were made
10755 			 * do we need to shrink it?
10756 			 */
10757 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10758 				if (cur_rttp <= bbr_rtt_probe_limit) {
10759 					/*
10760 					 * Things have calmed down lets
10761 					 * shrink all the way to default
10762 					 */
10763 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10764 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10765 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10766 					cur_rttp = bbr_rtt_probe_limit;
10767 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10768 					val = 2;
10769 				} else {
10770 					/*
10771 					 * Well does some adjustment make sense?
10772 					 */
10773 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10774 						/* We can reduce interval time some */
10775 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10776 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10777 						val = 3;
10778 					}
10779 				}
10780 			}
10781 		}
10782 		if (val)
10783 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10784 	}
10785 }
10786 
10787 static void
10788 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10789 {
10790 	/* Exit probe-rtt */
10791 
10792 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10793 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10794 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10795 	}
10796 	bbr_log_exit_gain(bbr, cts, 1);
10797 	bbr->rc_hit_state_1 = 0;
10798 	bbr->r_ctl.rc_rtt_shrinks = cts;
10799 	bbr->r_ctl.last_in_probertt = cts;
10800 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10801 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10802 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10803 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10804 					  bbr->r_ctl.rc_delivered);
10805 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10806 		uint32_t time_in;
10807 
10808 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10809 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10810 	}
10811 	if (bbr->rc_filled_pipe) {
10812 		/* Switch to probe_bw */
10813 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10814 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10815 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10816 		bbr_substate_change(bbr, cts, __LINE__, 0);
10817 		bbr_log_type_statechange(bbr, cts, __LINE__);
10818 	} else {
10819 		/* Back to startup */
10820 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10821 		bbr->r_ctl.rc_bbr_state_time = cts;
10822 		/*
10823 		 * We don't want to give a complete free 3
10824 		 * measurements until we exit, so we use
10825 		 * the number of pe's we were in probe-rtt
10826 		 * to add to the startup_epoch. That way
10827 		 * we will still retain the old state.
10828 		 */
10829 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10830 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10831 		/* Make sure to use the lower pg when shifting back in */
10832 		if (bbr->r_ctl.rc_lost &&
10833 		    bbr_use_lower_gain_in_startup &&
10834 		    (bbr->rc_use_google == 0))
10835 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10836 		else
10837 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10838 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10839 		/* Probably not needed but set it anyway */
10840 		bbr_set_state_target(bbr, __LINE__);
10841 		bbr_log_type_statechange(bbr, cts, __LINE__);
10842 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10843 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10844 	}
10845 	bbr_check_probe_rtt_limits(bbr, cts);
10846 }
10847 
10848 static int32_t inline
10849 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10850 {
10851 	if ((bbr->rc_past_init_win == 1) &&
10852 	    (bbr->rc_in_persist == 0) &&
10853 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10854 		return (1);
10855 	}
10856 	if (bbr_can_force_probertt &&
10857 	    (bbr->rc_in_persist == 0) &&
10858 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10859 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10860 		return (1);
10861 	}
10862 	return (0);
10863 }
10864 
10865 static int32_t
10866 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10867 {
10868 	uint64_t btlbw, gain;
10869 	if (pkt_epoch == 0) {
10870 		/*
10871 		 * Need to be on a pkt-epoch to continue.
10872 		 */
10873 		return (0);
10874 	}
10875 	btlbw = bbr_get_full_bw(bbr);
10876 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10877 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10878 	if (btlbw >= gain) {
10879 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10880 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10881 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10882 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10883 	}
10884 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10885 		return (1);
10886 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10887 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10888 	return(0);
10889 }
10890 
10891 static int32_t inline
10892 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10893 {
10894 	/* Have we gained 25% in the last 3 packet based epoch's? */
10895 	uint64_t btlbw, gain;
10896 	int do_exit;
10897 	int delta, rtt_gain;
10898 
10899 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10900 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10901 		/*
10902 		 * This qualifies as a RTT_PROBE session since we drop the
10903 		 * data outstanding to nothing and waited more than
10904 		 * bbr_rtt_probe_time.
10905 		 */
10906 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10907 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10908 	}
10909 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10910 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10911 		return (0);
10912 	}
10913 	if (bbr->rc_use_google)
10914 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10915 
10916 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10917 	    (bbr_use_lower_gain_in_startup)) {
10918 		/* Drop to a lower gain 1.5 x since we saw loss */
10919 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10920 	}
10921 	if (pkt_epoch == 0) {
10922 		/*
10923 		 * Need to be on a pkt-epoch to continue.
10924 		 */
10925 		return (0);
10926 	}
10927 	if (bbr_rtt_gain_thresh) {
10928 		/*
10929 		 * Do we allow a flow to stay
10930 		 * in startup with no loss and no
10931 		 * gain in rtt over a set threshold?
10932 		 */
10933 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
10934 		    bbr->r_ctl.startup_last_srtt &&
10935 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
10936 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
10937 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
10938 		} else
10939 			rtt_gain = 0;
10940 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
10941 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
10942 			/* First time or new lower value */
10943 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
10944 
10945 		if ((bbr->r_ctl.rc_lost == 0) &&
10946 		    (rtt_gain < bbr_rtt_gain_thresh)) {
10947 			/*
10948 			 * No loss, and we are under
10949 			 * our gain threhold for
10950 			 * increasing RTT.
10951 			 */
10952 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10953 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
10954 			bbr_log_startup_event(bbr, cts, rtt_gain,
10955 					      delta, bbr->r_ctl.startup_last_srtt, 10);
10956 			return (0);
10957 		}
10958 	}
10959 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
10960 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
10961 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
10962 		/*
10963 		 * We only assess if we have a new measurement when
10964 		 * we have no loss and are not in recovery.
10965 		 * Drag up by one our last_startup epoch so we will hold
10966 		 * the number of non-gain we have already accumulated.
10967 		 */
10968 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10969 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
10970 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10971 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
10972 		return (0);
10973 	}
10974 	/* Case where we reduced the lost (bad retransmit) */
10975 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
10976 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10977 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
10978 	btlbw = bbr_get_full_bw(bbr);
10979 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
10980 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10981 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10982 	else
10983 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10984 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10985 	do_exit = 0;
10986 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
10987 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10988 	if (btlbw >= gain) {
10989 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10990 		/* Update the lost so we won't exit in next set of tests */
10991 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10992 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10993 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10994 	}
10995 	if ((bbr->rc_loss_exit &&
10996 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10997 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
10998 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
10999 		/*
11000 		 * If we had no gain,  we had loss and that loss was above
11001 		 * our threshould, the rwnd is not constrained, and we have
11002 		 * had at least 3 packet epochs exit. Note that this is
11003 		 * switched off by sysctl. Google does not do this by the
11004 		 * way.
11005 		 */
11006 		if ((ctf_flight_size(bbr->rc_tp,
11007 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11008 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11009 			do_exit = 1;
11010 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11011 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11012 		} else {
11013 			/* Just record an updated loss value */
11014 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11015 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11016 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11017 		}
11018 	} else
11019 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11020 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11021 	    do_exit) {
11022 		/* Return 1 to exit the startup state. */
11023 		return (1);
11024 	}
11025 	/* Stay in startup */
11026 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11027 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11028 	return (0);
11029 }
11030 
11031 static void
11032 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11033 {
11034 	/*
11035 	 * A tick occurred in the rtt epoch do we need to do anything?
11036 	 */
11037 #ifdef BBR_INVARIANTS
11038 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11039 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11040 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11041 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11042 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11043 		/* Debug code? */
11044 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11045 	}
11046 #endif
11047 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11048 		/* Do we exit the startup state? */
11049 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11050 			uint32_t time_in;
11051 
11052 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11053 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11054 			bbr->rc_filled_pipe = 1;
11055 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11056 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11057 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11058 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11059 			} else
11060 				time_in = 0;
11061 			if (bbr->rc_no_pacing)
11062 				bbr->rc_no_pacing = 0;
11063 			bbr->r_ctl.rc_bbr_state_time = cts;
11064 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11065 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11066 			bbr_set_state_target(bbr, __LINE__);
11067 			if ((bbr->rc_use_google == 0) &&
11068 			    bbr_slam_cwnd_in_main_drain) {
11069 				/* Here we don't have to worry about probe-rtt */
11070 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11071 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11072 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11073 			}
11074 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11075 			bbr_log_type_statechange(bbr, cts, __LINE__);
11076 			if (ctf_flight_size(bbr->rc_tp,
11077 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11078 			    bbr->r_ctl.rc_target_at_state) {
11079 				/*
11080 				 * Switch to probe_bw if we are already
11081 				 * there
11082 				 */
11083 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11084 				bbr_substate_change(bbr, cts, __LINE__, 0);
11085 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11086 				bbr_log_type_statechange(bbr, cts, __LINE__);
11087 			}
11088 		}
11089 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11090 		uint32_t inflight;
11091 		struct tcpcb *tp;
11092 
11093 		tp = bbr->rc_tp;
11094 		inflight = ctf_flight_size(tp,
11095 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11096 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11097 			/* We have reached a flight of the cwnd target */
11098 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11099 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11100 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11101 			bbr_set_state_target(bbr, __LINE__);
11102 			/*
11103 			 * Rig it so we don't do anything crazy and
11104 			 * start fresh with a new randomization.
11105 			 */
11106 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11107 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11108 			bbr_substate_change(bbr, cts, __LINE__, 1);
11109 		}
11110 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11111 		/* Has in-flight reached the bdp (or less)? */
11112 		uint32_t inflight;
11113 		struct tcpcb *tp;
11114 
11115 		tp = bbr->rc_tp;
11116 		inflight = ctf_flight_size(tp,
11117 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11118 		if ((bbr->rc_use_google == 0) &&
11119 		    bbr_slam_cwnd_in_main_drain &&
11120 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11121 			/*
11122 			 * Here we don't have to worry about probe-rtt
11123 			 * re-slam it, but keep it slammed down.
11124 			 */
11125 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11126 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11127 		}
11128 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11129 			/* We have drained */
11130 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11131 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11132 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11133 				uint32_t time_in;
11134 
11135 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11136 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11137 			}
11138 			if ((bbr->rc_use_google == 0) &&
11139 			    bbr_slam_cwnd_in_main_drain &&
11140 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11141 				/* Restore the cwnd */
11142 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11143 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11144 			}
11145 			/* Setup probe-rtt has being done now RRS-HERE */
11146 			bbr->r_ctl.rc_rtt_shrinks = cts;
11147 			bbr->r_ctl.last_in_probertt = cts;
11148 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11149 			/* Randomly pick a sub-state */
11150 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11151 			bbr_substate_change(bbr, cts, __LINE__, 0);
11152 			bbr_log_type_statechange(bbr, cts, __LINE__);
11153 		}
11154 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11155 		uint32_t flight;
11156 
11157 		flight = ctf_flight_size(bbr->rc_tp,
11158 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11159 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11160 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11161 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11162 			/*
11163 			 * We must keep cwnd at the desired MSS.
11164 			 */
11165 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11166 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11167 		} else if ((bbr_prtt_slam_cwnd) &&
11168 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11169 			/* Re-slam it */
11170 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11171 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11172 		}
11173 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11174 			/* Has outstanding reached our target? */
11175 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11176 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11177 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11178 				/* If time is exactly 0, be 1usec off */
11179 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11180 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11181 				if (bbr->rc_use_google == 0) {
11182 					/*
11183 					 * Restore any lowering that as occurred to
11184 					 * reach here
11185 					 */
11186 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11187 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11188 					else
11189 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11190 				}
11191 			}
11192 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11193 			    (bbr->rc_use_google == 0) &&
11194 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11195 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11196 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11197 				/*
11198 				 * We have doddled with our current hptsi
11199 				 * gain an srtt and have still not made it
11200 				 * to target, or we have increased our flight.
11201 				 * Lets reduce the gain by xx%
11202 				 * flooring the reduce at DRAIN (based on
11203 				 * mul/div)
11204 				 */
11205 				int red;
11206 
11207 				bbr->r_ctl.flightsize_at_drain = flight;
11208 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11209 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11210 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11211 					/* Reduce our gain again */
11212 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11213 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11214 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11215 					/* one more chance before we give up */
11216 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11217 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11218 				} else {
11219 					/* At the very bottom */
11220 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11221 				}
11222 			}
11223 		}
11224 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11225 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11226 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11227 			/* Time to exit probe RTT normally */
11228 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11229 		}
11230 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11231 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11232 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11233 			/*
11234 			 * This qualifies as a RTT_PROBE session since we
11235 			 * drop the data outstanding to nothing and waited
11236 			 * more than bbr_rtt_probe_time.
11237 			 */
11238 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11239 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11240 		}
11241 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11242 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11243 		} else {
11244 			bbr_set_probebw_gains(bbr, cts, losses);
11245 		}
11246 	}
11247 }
11248 
11249 static void
11250 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11251 {
11252 	int32_t epoch = 0;
11253 
11254 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11255 		bbr_set_epoch(bbr, cts, line);
11256 		/* At each epoch doe lt bw sampling */
11257 		epoch = 1;
11258 	}
11259 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11260 }
11261 
11262 static int
11263 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11264     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11265     int32_t nxt_pkt, struct timeval *tv)
11266 {
11267 	struct inpcb *inp = tptoinpcb(tp);
11268 	int32_t thflags, retval;
11269 	uint32_t cts, lcts;
11270 	uint32_t tiwin;
11271 	struct tcpopt to;
11272 	struct tcp_bbr *bbr;
11273 	struct bbr_sendmap *rsm;
11274 	struct timeval ltv;
11275 	int32_t did_out = 0;
11276 	uint16_t nsegs;
11277 	int32_t prev_state;
11278 	uint32_t lost;
11279 
11280 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11281 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11282 	/* add in our stats */
11283 	kern_prefetch(bbr, &prev_state);
11284 	prev_state = 0;
11285 	thflags = tcp_get_flags(th);
11286 	/*
11287 	 * If this is either a state-changing packet or current state isn't
11288 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11289 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11290 	 * caller may have unnecessarily acquired a write lock due to a
11291 	 * race.
11292 	 */
11293 	INP_WLOCK_ASSERT(tptoinpcb(tp));
11294 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11295 	    __func__));
11296 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11297 	    __func__));
11298 
11299 	tp->t_rcvtime = ticks;
11300 	/*
11301 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11302 	 * the scale is zero.
11303 	 */
11304 	tiwin = th->th_win << tp->snd_scale;
11305 #ifdef STATS
11306 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11307 #endif
11308 
11309 	if (m->m_flags & M_TSTMP) {
11310 		/* Prefer the hardware timestamp if present */
11311 		struct timespec ts;
11312 
11313 		mbuf_tstmp2timespec(m, &ts);
11314 		bbr->rc_tv.tv_sec = ts.tv_sec;
11315 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11316 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11317 	} else if (m->m_flags & M_TSTMP_LRO) {
11318 		/* Next the arrival timestamp */
11319 		struct timespec ts;
11320 
11321 		mbuf_tstmp2timespec(m, &ts);
11322 		bbr->rc_tv.tv_sec = ts.tv_sec;
11323 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11324 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11325 	} else {
11326 		/*
11327 		 * Ok just get the current time.
11328 		 */
11329 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11330 	}
11331 	/*
11332 	 * Parse options on any incoming segment.
11333 	 */
11334 	tcp_dooptions(&to, (u_char *)(th + 1),
11335 	    (th->th_off << 2) - sizeof(struct tcphdr),
11336 	    (thflags & TH_SYN) ? TO_SYN : 0);
11337 
11338 	/*
11339 	 * If timestamps were negotiated during SYN/ACK and a
11340 	 * segment without a timestamp is received, silently drop
11341 	 * the segment, unless it is a RST segment or missing timestamps are
11342 	 * tolerated.
11343 	 * See section 3.2 of RFC 7323.
11344 	 */
11345 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11346 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11347 		retval = 0;
11348 		m_freem(m);
11349 		goto done_with_input;
11350 	}
11351 	/*
11352 	 * If echoed timestamp is later than the current time, fall back to
11353 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11354 	 * were used when this connection was established.
11355 	 */
11356 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11357 		to.to_tsecr -= tp->ts_offset;
11358 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11359 			to.to_tsecr = 0;
11360 	}
11361 	/*
11362 	 * If its the first time in we need to take care of options and
11363 	 * verify we can do SACK for rack!
11364 	 */
11365 	if (bbr->r_state == 0) {
11366 		/*
11367 		 * Process options only when we get SYN/ACK back. The SYN
11368 		 * case for incoming connections is handled in tcp_syncache.
11369 		 * According to RFC1323 the window field in a SYN (i.e., a
11370 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11371 		 * this is traditional behavior, may need to be cleaned up.
11372 		 */
11373 		if (bbr->rc_inp == NULL) {
11374 			bbr->rc_inp = inp;
11375 		}
11376 		/*
11377 		 * We need to init rc_inp here since its not init'd when
11378 		 * bbr_init is called
11379 		 */
11380 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11381 			if ((to.to_flags & TOF_SCALE) &&
11382 			    (tp->t_flags & TF_REQ_SCALE)) {
11383 				tp->t_flags |= TF_RCVD_SCALE;
11384 				tp->snd_scale = to.to_wscale;
11385 			} else
11386 				tp->t_flags &= ~TF_REQ_SCALE;
11387 			/*
11388 			 * Initial send window.  It will be updated with the
11389 			 * next incoming segment to the scaled value.
11390 			 */
11391 			tp->snd_wnd = th->th_win;
11392 			if ((to.to_flags & TOF_TS) &&
11393 			    (tp->t_flags & TF_REQ_TSTMP)) {
11394 				tp->t_flags |= TF_RCVD_TSTMP;
11395 				tp->ts_recent = to.to_tsval;
11396 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11397 			} else
11398 			    tp->t_flags &= ~TF_REQ_TSTMP;
11399 			if (to.to_flags & TOF_MSS)
11400 				tcp_mss(tp, to.to_mss);
11401 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11402 			    (to.to_flags & TOF_SACKPERM) == 0)
11403 				tp->t_flags &= ~TF_SACK_PERMIT;
11404 			if (IS_FASTOPEN(tp->t_flags)) {
11405 				if (to.to_flags & TOF_FASTOPEN) {
11406 					uint16_t mss;
11407 
11408 					if (to.to_flags & TOF_MSS)
11409 						mss = to.to_mss;
11410 					else
11411 						if ((inp->inp_vflag & INP_IPV6) != 0)
11412 							mss = TCP6_MSS;
11413 						else
11414 							mss = TCP_MSS;
11415 					tcp_fastopen_update_cache(tp, mss,
11416 					    to.to_tfo_len, to.to_tfo_cookie);
11417 				} else
11418 					tcp_fastopen_disable_path(tp);
11419 			}
11420 		}
11421 		/*
11422 		 * At this point we are at the initial call. Here we decide
11423 		 * if we are doing RACK or not. We do this by seeing if
11424 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11425 		 * we switch to the default code.
11426 		 */
11427 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11428 			/* Bail */
11429 			tcp_switch_back_to_default(tp);
11430 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11431 			    tlen, iptos);
11432 			return (1);
11433 		}
11434 		/* Set the flag */
11435 		bbr->r_is_v6 = (inp->inp_vflag & INP_IPV6) != 0;
11436 		tcp_set_hpts(inp);
11437 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11438 	}
11439 	if (thflags & TH_ACK) {
11440 		/* Track ack types */
11441 		if (to.to_flags & TOF_SACK)
11442 			BBR_STAT_INC(bbr_acks_with_sacks);
11443 		else
11444 			BBR_STAT_INC(bbr_plain_acks);
11445 	}
11446 	/*
11447 	 * This is the one exception case where we set the rack state
11448 	 * always. All other times (timers etc) we must have a rack-state
11449 	 * set (so we assure we have done the checks above for SACK).
11450 	 */
11451 	if (thflags & TH_FIN)
11452 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11453 	if (bbr->r_state != tp->t_state)
11454 		bbr_set_state(tp, bbr, tiwin);
11455 
11456 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11457 		kern_prefetch(rsm, &prev_state);
11458 	prev_state = bbr->r_state;
11459 	bbr->rc_ack_was_delayed = 0;
11460 	lost = bbr->r_ctl.rc_lost;
11461 	bbr->rc_is_pkt_epoch_now = 0;
11462 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11463 		/* Get the real time into lcts and figure the real delay */
11464 		lcts = tcp_get_usecs(&ltv);
11465 		if (TSTMP_GT(lcts, cts)) {
11466 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11467 			bbr->rc_ack_was_delayed = 1;
11468 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11469 				     bbr->r_ctl.highest_hdwr_delay))
11470 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11471 		} else {
11472 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11473 			bbr->rc_ack_was_delayed = 0;
11474 		}
11475 	} else {
11476 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11477 		bbr->rc_ack_was_delayed = 0;
11478 	}
11479 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11480 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11481 		retval = 0;
11482 		m_freem(m);
11483 		goto done_with_input;
11484 	}
11485 	/*
11486 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11487 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11488 	 */
11489 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11490 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11491 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11492 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11493 		return (1);
11494 	}
11495 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11496 		bbr->r_ctl.rc_high_rwnd = tiwin;
11497 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11498 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11499 	bbr->rtt_valid = 0;
11500 	if (to.to_flags & TOF_TS) {
11501 		bbr->rc_ts_valid = 1;
11502 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11503 	} else {
11504 		bbr->rc_ts_valid = 0;
11505 		bbr->r_ctl.last_inbound_ts = 0;
11506 	}
11507 	retval = (*bbr->r_substate) (m, th, so,
11508 	    tp, &to, drop_hdrlen,
11509 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11510 	if (nxt_pkt == 0)
11511 		BBR_STAT_INC(bbr_rlock_left_ret0);
11512 	else
11513 		BBR_STAT_INC(bbr_rlock_left_ret1);
11514 	if (retval == 0) {
11515 		/*
11516 		 * If retval is 1 the tcb is unlocked and most likely the tp
11517 		 * is gone.
11518 		 */
11519 		INP_WLOCK_ASSERT(inp);
11520 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11521 		if (bbr->rc_is_pkt_epoch_now)
11522 			bbr_set_pktepoch(bbr, cts, __LINE__);
11523 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11524 		if (nxt_pkt == 0) {
11525 			if (bbr->r_wanted_output != 0) {
11526 				bbr->rc_output_starts_timer = 0;
11527 				did_out = 1;
11528 				if (tcp_output(tp) < 0)
11529 					return (1);
11530 			} else
11531 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11532 		}
11533 		if ((nxt_pkt == 0) &&
11534 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11535 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11536 		     (tp->t_flags & TF_DELACK) ||
11537 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11538 		      (tp->t_state <= TCPS_CLOSING)))) {
11539 			/*
11540 			 * We could not send (probably in the hpts but
11541 			 * stopped the timer)?
11542 			 */
11543 			if ((tp->snd_max == tp->snd_una) &&
11544 			    ((tp->t_flags & TF_DELACK) == 0) &&
11545 			    (tcp_in_hpts(bbr->rc_inp)) &&
11546 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11547 				/*
11548 				 * keep alive not needed if we are hptsi
11549 				 * output yet
11550 				 */
11551 				;
11552 			} else {
11553 				if (tcp_in_hpts(bbr->rc_inp)) {
11554 					tcp_hpts_remove(bbr->rc_inp);
11555 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11556 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11557 						uint32_t del;
11558 
11559 						del = lcts - bbr->rc_pacer_started;
11560 						if (bbr->r_ctl.rc_last_delay_val > del) {
11561 							BBR_STAT_INC(bbr_force_timer_start);
11562 							bbr->r_ctl.rc_last_delay_val -= del;
11563 							bbr->rc_pacer_started = lcts;
11564 						} else {
11565 							/* We are late */
11566 							bbr->r_ctl.rc_last_delay_val = 0;
11567 							BBR_STAT_INC(bbr_force_output);
11568 							if (tcp_output(tp) < 0)
11569 								return (1);
11570 						}
11571 					}
11572 				}
11573 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11574 				    0);
11575 			}
11576 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11577 			/* Do we have the correct timer running? */
11578 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11579 		}
11580 		/* Do we have a new state */
11581 		if (bbr->r_state != tp->t_state)
11582 			bbr_set_state(tp, bbr, tiwin);
11583 done_with_input:
11584 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11585 		if (did_out)
11586 			bbr->r_wanted_output = 0;
11587 	}
11588 	return (retval);
11589 }
11590 
11591 static void
11592 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11593     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11594 {
11595 	struct timeval tv;
11596 	int retval;
11597 
11598 	/* First lets see if we have old packets */
11599 	if (tp->t_in_pkt) {
11600 		if (ctf_do_queued_segments(so, tp, 1)) {
11601 			m_freem(m);
11602 			return;
11603 		}
11604 	}
11605 	if (m->m_flags & M_TSTMP_LRO) {
11606 		mbuf_tstmp2timeval(m, &tv);
11607 	} else {
11608 		/* Should not be should we kassert instead? */
11609 		tcp_get_usecs(&tv);
11610 	}
11611 	retval = bbr_do_segment_nounlock(m, th, so, tp,
11612 					 drop_hdrlen, tlen, iptos, 0, &tv);
11613 	if (retval == 0) {
11614 		INP_WUNLOCK(tptoinpcb(tp));
11615 	}
11616 }
11617 
11618 /*
11619  * Return how much data can be sent without violating the
11620  * cwnd or rwnd.
11621  */
11622 
11623 static inline uint32_t
11624 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11625     uint32_t avail, int32_t sb_offset, uint32_t cts)
11626 {
11627 	uint32_t len;
11628 
11629 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11630 		/* We never want to go over our peers rcv-window */
11631 		len = 0;
11632 	} else {
11633 		uint32_t flight;
11634 
11635 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11636 		if (flight >= sendwin) {
11637 			/*
11638 			 * We have in flight what we are allowed by cwnd (if
11639 			 * it was rwnd blocking it would have hit above out
11640 			 * >= tp->snd_wnd).
11641 			 */
11642 			return (0);
11643 		}
11644 		len = sendwin - flight;
11645 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11646 			/* We would send too much (beyond the rwnd) */
11647 			len = tp->snd_wnd - ctf_outstanding(tp);
11648 		}
11649 		if ((len + sb_offset) > avail) {
11650 			/*
11651 			 * We don't have that much in the SB, how much is
11652 			 * there?
11653 			 */
11654 			len = avail - sb_offset;
11655 		}
11656 	}
11657 	return (len);
11658 }
11659 
11660 static inline void
11661 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11662 {
11663 #ifdef NETFLIX_STATS
11664 	KMOD_TCPSTAT_INC(tcps_sndpack_error);
11665 	KMOD_TCPSTAT_ADD(tcps_sndbyte_error, len);
11666 #endif
11667 }
11668 
11669 static inline void
11670 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11671 {
11672 	if (error) {
11673 		bbr_do_error_accounting(tp, bbr, rsm, len, error);
11674 		return;
11675 	}
11676 	if (rsm) {
11677 		if (rsm->r_flags & BBR_TLP) {
11678 			/*
11679 			 * TLP should not count in retran count, but in its
11680 			 * own bin
11681 			 */
11682 #ifdef NETFLIX_STATS
11683 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11684 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11685 #endif
11686 		} else {
11687 			/* Retransmit */
11688 			tp->t_sndrexmitpack++;
11689 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11690 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11691 #ifdef STATS
11692 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11693 			    len);
11694 #endif
11695 		}
11696 		/*
11697 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11698 		 * sub-state
11699 		 */
11700 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11701 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11702 			/* Non probe_bw log in 1, 2, or 4. */
11703 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11704 		} else {
11705 			/*
11706 			 * Log our probe state 3, and log also 5-13 to show
11707 			 * us the recovery sub-state for the send. This
11708 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11709 			 */
11710 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11711 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11712 		}
11713 		/* Place in both 16's the totals of retransmitted */
11714 		counter_u64_add(bbr_state_lost[16], len);
11715 		counter_u64_add(bbr_state_resend[16], len);
11716 		/* Place in 17's the total sent */
11717 		counter_u64_add(bbr_state_resend[17], len);
11718 		counter_u64_add(bbr_state_lost[17], len);
11719 
11720 	} else {
11721 		/* New sends */
11722 		KMOD_TCPSTAT_INC(tcps_sndpack);
11723 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11724 		/* Place in 17's the total sent */
11725 		counter_u64_add(bbr_state_resend[17], len);
11726 		counter_u64_add(bbr_state_lost[17], len);
11727 #ifdef STATS
11728 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11729 		    len);
11730 #endif
11731 	}
11732 }
11733 
11734 static void
11735 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11736 {
11737 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11738 		/*
11739 		 * Limit the cwnd to not be above N x the target plus whats
11740 		 * is outstanding. The target is based on the current b/w
11741 		 * estimate.
11742 		 */
11743 		uint32_t target;
11744 
11745 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11746 		target += ctf_outstanding(tp);
11747 		target *= bbr_target_cwnd_mult_limit;
11748 		if (tp->snd_cwnd > target)
11749 			tp->snd_cwnd = target;
11750 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11751 	}
11752 }
11753 
11754 static int
11755 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11756 {
11757 	/*
11758 	 * "adv" is the amount we could increase the window, taking into
11759 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11760 	 */
11761 	int32_t adv;
11762 	int32_t oldwin;
11763 
11764 	adv = recwin;
11765 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11766 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11767 		if (adv > oldwin)
11768 			adv -= oldwin;
11769 		else {
11770 			/* We can't increase the window */
11771 			adv = 0;
11772 		}
11773 	} else
11774 		oldwin = 0;
11775 
11776 	/*
11777 	 * If the new window size ends up being the same as or less
11778 	 * than the old size when it is scaled, then don't force
11779 	 * a window update.
11780 	 */
11781 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11782 		return (0);
11783 
11784 	if (adv >= (2 * maxseg) &&
11785 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11786 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11787 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11788 		return (1);
11789 	}
11790 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11791 		return (1);
11792 	return (0);
11793 }
11794 
11795 /*
11796  * Return 0 on success and a errno on failure to send.
11797  * Note that a 0 return may not mean we sent anything
11798  * if the TCB was on the hpts. A non-zero return
11799  * does indicate the error we got from ip[6]_output.
11800  */
11801 static int
11802 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11803 {
11804 	struct socket *so;
11805 	int32_t len;
11806 	uint32_t cts;
11807 	uint32_t recwin, sendwin;
11808 	int32_t sb_offset;
11809 	int32_t flags, abandon, error = 0;
11810 	struct tcp_log_buffer *lgb = NULL;
11811 	struct mbuf *m;
11812 	struct mbuf *mb;
11813 	uint32_t if_hw_tsomaxsegcount = 0;
11814 	uint32_t if_hw_tsomaxsegsize = 0;
11815 	uint32_t if_hw_tsomax = 0;
11816 	struct ip *ip = NULL;
11817 	struct tcp_bbr *bbr;
11818 	struct tcphdr *th;
11819 	struct udphdr *udp = NULL;
11820 	u_char opt[TCP_MAXOLEN];
11821 	unsigned ipoptlen, optlen, hdrlen;
11822 	unsigned ulen;
11823 	uint32_t bbr_seq;
11824 	uint32_t delay_calc=0;
11825 	uint8_t doing_tlp = 0;
11826 	uint8_t local_options;
11827 #ifdef BBR_INVARIANTS
11828 	uint8_t doing_retran_from = 0;
11829 	uint8_t picked_up_retran = 0;
11830 #endif
11831 	uint8_t wanted_cookie = 0;
11832 	uint8_t more_to_rxt=0;
11833 	int32_t prefetch_so_done = 0;
11834 	int32_t prefetch_rsm = 0;
11835 	uint32_t tot_len = 0;
11836 	uint32_t maxseg, pace_max_segs, p_maxseg;
11837 	int32_t csum_flags = 0;
11838  	int32_t hw_tls;
11839 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11840 	unsigned ipsec_optlen = 0;
11841 
11842 #endif
11843 	volatile int32_t sack_rxmit;
11844 	struct bbr_sendmap *rsm = NULL;
11845 	int32_t tso, mtu;
11846 	struct tcpopt to;
11847 	int32_t slot = 0;
11848 	struct inpcb *inp;
11849 	struct sockbuf *sb;
11850 	uint32_t hpts_calling;
11851 #ifdef INET6
11852 	struct ip6_hdr *ip6 = NULL;
11853 	int32_t isipv6;
11854 #endif
11855 	uint8_t app_limited = BBR_JR_SENT_DATA;
11856 	uint8_t filled_all = 0;
11857 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11858 	/* We take a cache hit here */
11859 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11860 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11861 	inp = bbr->rc_inp;
11862 	so = inp->inp_socket;
11863 	sb = &so->so_snd;
11864 	if (tp->t_nic_ktls_xmit)
11865  		hw_tls = 1;
11866  	else
11867  		hw_tls = 0;
11868 	kern_prefetch(sb, &maxseg);
11869 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11870 	if (bbr_minseg(bbr) < maxseg) {
11871 		tcp_bbr_tso_size_check(bbr, cts);
11872 	}
11873 	/* Remove any flags that indicate we are pacing on the inp  */
11874 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11875 	p_maxseg = min(maxseg, pace_max_segs);
11876 	INP_WLOCK_ASSERT(inp);
11877 #ifdef TCP_OFFLOAD
11878 	if (tp->t_flags & TF_TOE)
11879 		return (tcp_offload_output(tp));
11880 #endif
11881 
11882 #ifdef INET6
11883 	if (bbr->r_state) {
11884 		/* Use the cache line loaded if possible */
11885 		isipv6 = bbr->r_is_v6;
11886 	} else {
11887 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11888 	}
11889 #endif
11890 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11891 	    tcp_in_hpts(inp)) {
11892 		/*
11893 		 * We are on the hpts for some timer but not hptsi output.
11894 		 * Possibly remove from the hpts so we can send/recv etc.
11895 		 */
11896 		if ((tp->t_flags & TF_ACKNOW) == 0) {
11897 			/*
11898 			 * No immediate demand right now to send an ack, but
11899 			 * the user may have read, making room for new data
11900 			 * (a window update). If so we may want to cancel
11901 			 * whatever timer is running (KEEP/DEL-ACK?) and
11902 			 * continue to send out a window update. Or we may
11903 			 * have gotten more data into the socket buffer to
11904 			 * send.
11905 			 */
11906 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
11907 				      (long)TCP_MAXWIN << tp->rcv_scale);
11908 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
11909 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
11910 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
11911 			    (tp->snd_max - tp->snd_una))) {
11912 				/*
11913 				 * Nothing new to send and no window update
11914 				 * is needed to send. Lets just return and
11915 				 * let the timer-run off.
11916 				 */
11917 				return (0);
11918 			}
11919 		}
11920 		tcp_hpts_remove(inp);
11921 		bbr_timer_cancel(bbr, __LINE__, cts);
11922 	}
11923 	if (bbr->r_ctl.rc_last_delay_val) {
11924 		/* Calculate a rough delay for early escape to sending  */
11925 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11926 			delay_calc = cts - bbr->rc_pacer_started;
11927 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11928 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11929 		else
11930 			delay_calc = 0;
11931 	}
11932 	/* Mark that we have called bbr_output(). */
11933 	if ((bbr->r_timer_override) ||
11934 	    (tp->t_state < TCPS_ESTABLISHED)) {
11935 		/* Timeouts or early states are exempt */
11936 		if (tcp_in_hpts(inp))
11937 			tcp_hpts_remove(inp);
11938 	} else if (tcp_in_hpts(inp)) {
11939 		if ((bbr->r_ctl.rc_last_delay_val) &&
11940 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11941 		    delay_calc) {
11942 			/*
11943 			 * We were being paced for output and the delay has
11944 			 * already exceeded when we were supposed to be
11945 			 * called, lets go ahead and pull out of the hpts
11946 			 * and call output.
11947 			 */
11948 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
11949 			bbr->r_ctl.rc_last_delay_val = 0;
11950 			tcp_hpts_remove(inp);
11951 		} else if (tp->t_state == TCPS_CLOSED) {
11952 			bbr->r_ctl.rc_last_delay_val = 0;
11953 			tcp_hpts_remove(inp);
11954 		} else {
11955 			/*
11956 			 * On the hpts, you shall not pass! even if ACKNOW
11957 			 * is on, we will when the hpts fires, unless of
11958 			 * course we are overdue.
11959 			 */
11960 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
11961 			return (0);
11962 		}
11963 	}
11964 	bbr->rc_cwnd_limited = 0;
11965 	if (bbr->r_ctl.rc_last_delay_val) {
11966 		/* recalculate the real delay and deal with over/under  */
11967 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11968 			delay_calc = cts - bbr->rc_pacer_started;
11969 		else
11970 			delay_calc = 0;
11971 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11972 			/* Setup the delay which will be added in */
11973 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11974 		else {
11975 			/*
11976 			 * We are early setup to adjust
11977 			 * our slot time.
11978 			 */
11979 			uint64_t merged_val;
11980 
11981 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
11982 			bbr->r_agg_early_set = 1;
11983 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
11984 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
11985 					/* Nope our previous late cancels out the early */
11986 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
11987 					bbr->r_agg_early_set = 0;
11988 					bbr->r_ctl.rc_agg_early = 0;
11989 				} else {
11990 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
11991 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
11992 				}
11993 			}
11994 			merged_val = bbr->rc_pacer_started;
11995 			merged_val <<= 32;
11996 			merged_val |= bbr->r_ctl.rc_last_delay_val;
11997 			bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
11998 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
11999 						 bbr->r_agg_early_set, 3);
12000 			bbr->r_ctl.rc_last_delay_val = 0;
12001 			BBR_STAT_INC(bbr_early);
12002 			delay_calc = 0;
12003 		}
12004 	} else {
12005 		/* We were not delayed due to hptsi */
12006 		if (bbr->r_agg_early_set)
12007 			bbr->r_ctl.rc_agg_early = 0;
12008 		bbr->r_agg_early_set = 0;
12009 		delay_calc = 0;
12010 	}
12011 	if (delay_calc) {
12012 		/*
12013 		 * We had a hptsi delay which means we are falling behind on
12014 		 * sending at the expected rate. Calculate an extra amount
12015 		 * of data we can send, if any, to put us back on track.
12016 		 */
12017 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12018 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12019 		else
12020 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12021 	}
12022 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12023 	if ((tp->snd_una == tp->snd_max) &&
12024 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12025 	    (sbavail(sb))) {
12026 		/*
12027 		 * Ok we have been idle with nothing outstanding
12028 		 * we possibly need to start fresh with either a new
12029 		 * suite of states or a fast-ramp up.
12030 		 */
12031 		bbr_restart_after_idle(bbr,
12032 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12033 	}
12034 	/*
12035 	 * Now was there a hptsi delay where we are behind? We only count
12036 	 * being behind if: a) We are not in recovery. b) There was a delay.
12037 	 * <and> c) We had room to send something.
12038 	 *
12039 	 */
12040 	hpts_calling = inp->inp_hpts_calls;
12041 	inp->inp_hpts_calls = 0;
12042 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12043 		int retval;
12044 
12045 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12046 		if (retval != 0) {
12047 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12048 			/*
12049 			 * If timers want tcp_drop(), then pass error out,
12050 			 * otherwise suppress it.
12051 			 */
12052 			return (retval < 0 ? retval : 0);
12053 		}
12054 	}
12055 	bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12056 	if (hpts_calling &&
12057 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12058 		bbr->r_ctl.rc_last_delay_val = 0;
12059 	}
12060 	bbr->r_timer_override = 0;
12061 	bbr->r_wanted_output = 0;
12062 	/*
12063 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12064 	 * SYN|ACK and those sent by the retransmit timer.
12065 	 */
12066 	if (IS_FASTOPEN(tp->t_flags) &&
12067 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12068 	     (tp->t_state == TCPS_SYN_SENT)) &&
12069 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12070 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12071 		len = 0;
12072 		goto just_return_nolock;
12073 	}
12074 	/*
12075 	 * Before sending anything check for a state update. For hpts
12076 	 * calling without input this is important. If its input calling
12077 	 * then this was already done.
12078 	 */
12079 	if (bbr->rc_use_google == 0)
12080 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12081 again:
12082 	/*
12083 	 * If we've recently taken a timeout, snd_max will be greater than
12084 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12085 	 * for historic reasons the persist timer still uses it. This means
12086 	 * we have to look at it. All retransmissions that are not persits
12087 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12088 	 * end of this routine we pull snd_nxt always up to snd_max.
12089 	 */
12090 	doing_tlp = 0;
12091 #ifdef BBR_INVARIANTS
12092 	doing_retran_from = picked_up_retran = 0;
12093 #endif
12094 	error = 0;
12095 	tso = 0;
12096 	slot = 0;
12097 	mtu = 0;
12098 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12099 	sb_offset = tp->snd_max - tp->snd_una;
12100 	flags = tcp_outflags[tp->t_state];
12101 	sack_rxmit = 0;
12102 	len = 0;
12103 	rsm = NULL;
12104 	if (flags & TH_RST) {
12105 		SOCKBUF_LOCK(sb);
12106 		goto send;
12107 	}
12108 recheck_resend:
12109 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12110 		/* We need to always have one in reserve */
12111 		rsm = bbr_alloc(bbr);
12112 		if (rsm == NULL) {
12113 			error = ENOMEM;
12114 			/* Lie to get on the hpts */
12115 			tot_len = tp->t_maxseg;
12116 			if (hpts_calling)
12117 				/* Retry in a ms */
12118 				slot = 1001;
12119 			goto just_return_nolock;
12120 		}
12121 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12122 		bbr->r_ctl.rc_free_cnt++;
12123 		rsm = NULL;
12124 	}
12125 	/* What do we send, a resend? */
12126 	if (bbr->r_ctl.rc_resend == NULL) {
12127 		/* Check for rack timeout */
12128 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12129 		if (bbr->r_ctl.rc_resend) {
12130 #ifdef BBR_INVARIANTS
12131 			picked_up_retran = 1;
12132 #endif
12133 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12134 		}
12135 	}
12136 	if (bbr->r_ctl.rc_resend) {
12137 		rsm = bbr->r_ctl.rc_resend;
12138 #ifdef BBR_INVARIANTS
12139 		doing_retran_from = 1;
12140 #endif
12141 		/* Remove any TLP flags its a RACK or T-O */
12142 		rsm->r_flags &= ~BBR_TLP;
12143 		bbr->r_ctl.rc_resend = NULL;
12144 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12145 #ifdef BBR_INVARIANTS
12146 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12147 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12148 			goto recheck_resend;
12149 #else
12150 			/* TSNH */
12151 			rsm = NULL;
12152 			goto recheck_resend;
12153 #endif
12154 		}
12155 		if (rsm->r_flags & BBR_HAS_SYN) {
12156 			/* Only retransmit a SYN by itself */
12157 			len = 0;
12158 			if ((flags & TH_SYN) == 0) {
12159 				/* Huh something is wrong */
12160 				rsm->r_start++;
12161 				if (rsm->r_start == rsm->r_end) {
12162 					/* Clean it up, somehow we missed the ack? */
12163 					bbr_log_syn(tp, NULL);
12164 				} else {
12165 					/* TFO with data? */
12166 					rsm->r_flags &= ~BBR_HAS_SYN;
12167 					len = rsm->r_end - rsm->r_start;
12168 				}
12169 			} else {
12170 				/* Retransmitting SYN */
12171 				rsm = NULL;
12172 				SOCKBUF_LOCK(sb);
12173 				goto send;
12174 			}
12175 		} else
12176 			len = rsm->r_end - rsm->r_start;
12177 		if ((bbr->rc_resends_use_tso == 0) &&
12178 		    (len > maxseg)) {
12179 			len = maxseg;
12180 			more_to_rxt = 1;
12181 		}
12182 		sb_offset = rsm->r_start - tp->snd_una;
12183 		if (len > 0) {
12184 			sack_rxmit = 1;
12185 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12186 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12187 			    min(len, maxseg));
12188 		} else {
12189 			/* I dont think this can happen */
12190 			rsm = NULL;
12191 			goto recheck_resend;
12192 		}
12193 		BBR_STAT_INC(bbr_resends_set);
12194 	} else if (bbr->r_ctl.rc_tlp_send) {
12195 		/*
12196 		 * Tail loss probe
12197 		 */
12198 		doing_tlp = 1;
12199 		rsm = bbr->r_ctl.rc_tlp_send;
12200 		bbr->r_ctl.rc_tlp_send = NULL;
12201 		sack_rxmit = 1;
12202 		len = rsm->r_end - rsm->r_start;
12203 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12204 			len = maxseg;
12205 
12206 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12207 #ifdef BBR_INVARIANTS
12208 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12209 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12210 #else
12211 			/* TSNH */
12212 			rsm = NULL;
12213 			goto recheck_resend;
12214 #endif
12215 		}
12216 		sb_offset = rsm->r_start - tp->snd_una;
12217 		BBR_STAT_INC(bbr_tlp_set);
12218 	}
12219 	/*
12220 	 * Enforce a connection sendmap count limit if set
12221 	 * as long as we are not retransmiting.
12222 	 */
12223 	if ((rsm == NULL) &&
12224 	    (V_tcp_map_entries_limit > 0) &&
12225 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12226 		BBR_STAT_INC(bbr_alloc_limited);
12227 		if (!bbr->alloc_limit_reported) {
12228 			bbr->alloc_limit_reported = 1;
12229 			BBR_STAT_INC(bbr_alloc_limited_conns);
12230 		}
12231 		goto just_return_nolock;
12232 	}
12233 #ifdef BBR_INVARIANTS
12234 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12235 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12236 		    tp, bbr, rsm, sb_offset, len);
12237 	}
12238 #endif
12239 	/*
12240 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12241 	 * state flags.
12242 	 */
12243 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12244 		flags |= TH_FIN;
12245 	if (tp->t_flags & TF_NEEDSYN)
12246 		flags |= TH_SYN;
12247 
12248 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12249 		/* we are retransmitting the fin */
12250 		len--;
12251 		if (len) {
12252 			/*
12253 			 * When retransmitting data do *not* include the
12254 			 * FIN. This could happen from a TLP probe if we
12255 			 * allowed data with a FIN.
12256 			 */
12257 			flags &= ~TH_FIN;
12258 		}
12259 	} else if (rsm) {
12260 		if (flags & TH_FIN)
12261 			flags &= ~TH_FIN;
12262 	}
12263 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12264 		void *end_rsm;
12265 
12266 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12267 		if (end_rsm)
12268 			kern_prefetch(end_rsm, &prefetch_rsm);
12269 		prefetch_rsm = 1;
12270 	}
12271 	SOCKBUF_LOCK(sb);
12272 	/*
12273 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12274 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12275 	 * negative length.  This can also occur when TCP opens up its
12276 	 * congestion window while receiving additional duplicate acks after
12277 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12278 	 * the fast-retransmit.
12279 	 *
12280 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12281 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12282 	 * up 0.
12283 	 *
12284 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12285 	 * in which case len is already set.
12286 	 */
12287 	if (sack_rxmit == 0) {
12288 		uint32_t avail;
12289 
12290 		avail = sbavail(sb);
12291 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12292 			sb_offset = tp->snd_max - tp->snd_una;
12293 		else
12294 			sb_offset = 0;
12295 		if (bbr->rc_tlp_new_data) {
12296 			/* TLP is forcing out new data */
12297 			uint32_t tlplen;
12298 
12299 			doing_tlp = 1;
12300 			tlplen = maxseg;
12301 
12302 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12303 				tlplen = (uint32_t)(avail - sb_offset);
12304 			}
12305 			if (tlplen > tp->snd_wnd) {
12306 				len = tp->snd_wnd;
12307 			} else {
12308 				len = tlplen;
12309 			}
12310 			bbr->rc_tlp_new_data = 0;
12311 		} else {
12312 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12313 			if ((len < p_maxseg) &&
12314 			    (bbr->rc_in_persist == 0) &&
12315 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12316 			    ((avail - sb_offset) >= p_maxseg)) {
12317 				/*
12318 				 * We are not completing whats in the socket
12319 				 * buffer (i.e. there is at least a segment
12320 				 * waiting to send) and we have 2 or more
12321 				 * segments outstanding. There is no sense
12322 				 * of sending a little piece. Lets defer and
12323 				 * and wait until we can send a whole
12324 				 * segment.
12325 				 */
12326 				len = 0;
12327 			}
12328 			if (bbr->rc_in_persist) {
12329 				/*
12330 				 * We are in persists, figure out if
12331 				 * a retransmit is available (maybe the previous
12332 				 * persists we sent) or if we have to send new
12333 				 * data.
12334 				 */
12335 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12336 				if (rsm) {
12337 					len = rsm->r_end - rsm->r_start;
12338 					if (rsm->r_flags & BBR_HAS_FIN)
12339 						len--;
12340 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12341 						len = maxseg;
12342 					if (len > 1)
12343 						BBR_STAT_INC(bbr_persist_reneg);
12344 					/*
12345 					 * XXXrrs we could force the len to
12346 					 * 1 byte here to cause the chunk to
12347 					 * split apart.. but that would then
12348 					 * mean we always retransmit it as
12349 					 * one byte even after the window
12350 					 * opens.
12351 					 */
12352 					sack_rxmit = 1;
12353 					sb_offset = rsm->r_start - tp->snd_una;
12354 				} else {
12355 					/*
12356 					 * First time through in persists or peer
12357 					 * acked our one byte. Though we do have
12358 					 * to have something in the sb.
12359 					 */
12360 					len = 1;
12361 					sb_offset = 0;
12362 					if (avail == 0)
12363 					    len = 0;
12364 				}
12365 			}
12366 		}
12367 	}
12368 	if (prefetch_so_done == 0) {
12369 		kern_prefetch(so, &prefetch_so_done);
12370 		prefetch_so_done = 1;
12371 	}
12372 	/*
12373 	 * Lop off SYN bit if it has already been sent.  However, if this is
12374 	 * SYN-SENT state and if segment contains data and if we don't know
12375 	 * that foreign host supports TAO, suppress sending segment.
12376 	 */
12377 	if ((flags & TH_SYN) && (rsm == NULL) &&
12378 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12379 		if (tp->t_state != TCPS_SYN_RECEIVED)
12380 			flags &= ~TH_SYN;
12381 		/*
12382 		 * When sending additional segments following a TFO SYN|ACK,
12383 		 * do not include the SYN bit.
12384 		 */
12385 		if (IS_FASTOPEN(tp->t_flags) &&
12386 		    (tp->t_state == TCPS_SYN_RECEIVED))
12387 			flags &= ~TH_SYN;
12388 		sb_offset--, len++;
12389 		if (sbavail(sb) == 0)
12390 			len = 0;
12391 	} else if ((flags & TH_SYN) && rsm) {
12392 		/*
12393 		 * Subtract one from the len for the SYN being
12394 		 * retransmitted.
12395 		 */
12396 		len--;
12397 	}
12398 	/*
12399 	 * Be careful not to send data and/or FIN on SYN segments. This
12400 	 * measure is needed to prevent interoperability problems with not
12401 	 * fully conformant TCP implementations.
12402 	 */
12403 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12404 		len = 0;
12405 		flags &= ~TH_FIN;
12406 	}
12407 	/*
12408 	 * On TFO sockets, ensure no data is sent in the following cases:
12409 	 *
12410 	 *  - When retransmitting SYN|ACK on a passively-created socket
12411 	 *  - When retransmitting SYN on an actively created socket
12412 	 *  - When sending a zero-length cookie (cookie request) on an
12413 	 *    actively created socket
12414 	 *  - When the socket is in the CLOSED state (RST is being sent)
12415 	 */
12416 	if (IS_FASTOPEN(tp->t_flags) &&
12417 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12418 	     ((tp->t_state == TCPS_SYN_SENT) &&
12419 	      (tp->t_tfo_client_cookie_len == 0)) ||
12420 	     (flags & TH_RST))) {
12421 		len = 0;
12422 		sack_rxmit = 0;
12423 		rsm = NULL;
12424 	}
12425 	/* Without fast-open there should never be data sent on a SYN */
12426 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12427 		len = 0;
12428 	if (len <= 0) {
12429 		/*
12430 		 * If FIN has been sent but not acked, but we haven't been
12431 		 * called to retransmit, len will be < 0.  Otherwise, window
12432 		 * shrank after we sent into it.  If window shrank to 0,
12433 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12434 		 * window, and set the persist timer if it isn't already
12435 		 * going.  If the window didn't close completely, just wait
12436 		 * for an ACK.
12437 		 *
12438 		 * We also do a general check here to ensure that we will
12439 		 * set the persist timer when we have data to send, but a
12440 		 * 0-byte window. This makes sure the persist timer is set
12441 		 * even if the packet hits one of the "goto send" lines
12442 		 * below.
12443 		 */
12444 		len = 0;
12445 		if ((tp->snd_wnd == 0) &&
12446 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12447 		    (tp->snd_una == tp->snd_max) &&
12448 		    (sb_offset < (int)sbavail(sb))) {
12449 			/*
12450 			 * Not enough room in the rwnd to send
12451 			 * a paced segment out.
12452 			 */
12453 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12454 		}
12455 	} else if ((rsm == NULL) &&
12456 		   (doing_tlp == 0) &&
12457 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12458 		/*
12459 		 * We are not sending a full segment for
12460 		 * some reason. Should we not send anything (think
12461 		 * sws or persists)?
12462 		 */
12463 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12464 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12465 		    (len < (int)(sbavail(sb) - sb_offset))) {
12466 			/*
12467 			 * Here the rwnd is less than
12468 			 * the pacing size, this is not a retransmit,
12469 			 * we are established and
12470 			 * the send is not the last in the socket buffer
12471 			 * lets not send, and possibly enter persists.
12472 			 */
12473 			len = 0;
12474 			if (tp->snd_max == tp->snd_una)
12475 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12476 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12477 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12478 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12479 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12480 			   (len < bbr_minseg(bbr))) {
12481 			/*
12482 			 * Here we are not retransmitting, and
12483 			 * the cwnd is not so small that we could
12484 			 * not send at least a min size (rxt timer
12485 			 * not having gone off), We have 2 segments or
12486 			 * more already in flight, its not the tail end
12487 			 * of the socket buffer  and the cwnd is blocking
12488 			 * us from sending out minimum pacing segment size.
12489 			 * Lets not send anything.
12490 			 */
12491 			bbr->rc_cwnd_limited = 1;
12492 			len = 0;
12493 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12494 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12495 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12496 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12497 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12498 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12499 			/*
12500 			 * Here we have a send window but we have
12501 			 * filled it up and we can't send another pacing segment.
12502 			 * We also have in flight more than 2 segments
12503 			 * and we are not completing the sb i.e. we allow
12504 			 * the last bytes of the sb to go out even if
12505 			 * its not a full pacing segment.
12506 			 */
12507 			len = 0;
12508 		}
12509 	}
12510 	/* len will be >= 0 after this point. */
12511 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12512 	tcp_sndbuf_autoscale(tp, so, sendwin);
12513 	/*
12514 	 *
12515 	 */
12516 	if (bbr->rc_in_persist &&
12517 	    len &&
12518 	    (rsm == NULL) &&
12519 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12520 		/*
12521 		 * We are in persist, not doing a retransmit and don't have enough space
12522 		 * yet to send a full TSO. So is it at the end of the sb
12523 		 * if so we need to send else nuke to 0 and don't send.
12524 		 */
12525 		int sbleft;
12526 		if (sbavail(sb) > sb_offset)
12527 			sbleft = sbavail(sb) - sb_offset;
12528 		else
12529 			sbleft = 0;
12530 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12531 			/* not at end of sb lets not send */
12532 			len = 0;
12533 		}
12534 	}
12535 	/*
12536 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12537 	 * hardware).
12538 	 *
12539 	 * TSO may only be used if we are in a pure bulk sending state.  The
12540 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12541 	 * options prevent using TSO.  With TSO the TCP header is the same
12542 	 * (except for the sequence number) for all generated packets.  This
12543 	 * makes it impossible to transmit any options which vary per
12544 	 * generated segment or packet.
12545 	 *
12546 	 * IPv4 handling has a clear separation of ip options and ip header
12547 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12548 	 * does the right thing below to provide length of just ip options
12549 	 * and thus checking for ipoptlen is enough to decide if ip options
12550 	 * are present.
12551 	 */
12552 #ifdef INET6
12553 	if (isipv6)
12554 		ipoptlen = ip6_optlen(inp);
12555 	else
12556 #endif
12557 	if (inp->inp_options)
12558 		ipoptlen = inp->inp_options->m_len -
12559 		    offsetof(struct ipoption, ipopt_list);
12560 	else
12561 		ipoptlen = 0;
12562 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12563 	/*
12564 	 * Pre-calculate here as we save another lookup into the darknesses
12565 	 * of IPsec that way and can actually decide if TSO is ok.
12566 	 */
12567 #ifdef INET6
12568 	if (isipv6 && IPSEC_ENABLED(ipv6))
12569 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12570 #ifdef INET
12571 	else
12572 #endif
12573 #endif				/* INET6 */
12574 #ifdef INET
12575 	if (IPSEC_ENABLED(ipv4))
12576 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12577 #endif				/* INET */
12578 #endif				/* IPSEC */
12579 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12580 	ipoptlen += ipsec_optlen;
12581 #endif
12582 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12583 	    (len > maxseg) &&
12584 	    (tp->t_port == 0) &&
12585 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12586 	    tp->rcv_numsacks == 0 &&
12587 	    ipoptlen == 0)
12588 		tso = 1;
12589 
12590 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12591 	    (long)TCP_MAXWIN << tp->rcv_scale);
12592 	/*
12593 	 * Sender silly window avoidance.   We transmit under the following
12594 	 * conditions when len is non-zero:
12595 	 *
12596 	 * - We have a full segment (or more with TSO) - This is the last
12597 	 * buffer in a write()/send() and we are either idle or running
12598 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12599 	 * then 1/2 the maximum send window's worth of data (receiver may be
12600 	 * limited the window size) - we need to retransmit
12601 	 */
12602 	if (rsm)
12603 		goto send;
12604 	if (len) {
12605 		if (sack_rxmit)
12606 			goto send;
12607 		if (len >= p_maxseg)
12608 			goto send;
12609 		/*
12610 		 * NOTE! on localhost connections an 'ack' from the remote
12611 		 * end may occur synchronously with the output and cause us
12612 		 * to flush a buffer queued with moretocome.  XXX
12613 		 *
12614 		 */
12615 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12616 		    ((tp->t_flags & TF_NODELAY) ||
12617 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12618 		    (tp->t_flags & TF_NOPUSH) == 0) {
12619 			goto send;
12620 		}
12621 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12622 			goto send;
12623 		}
12624 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12625 			goto send;
12626 		}
12627 	}
12628 	/*
12629 	 * Sending of standalone window updates.
12630 	 *
12631 	 * Window updates are important when we close our window due to a
12632 	 * full socket buffer and are opening it again after the application
12633 	 * reads data from it.  Once the window has opened again and the
12634 	 * remote end starts to send again the ACK clock takes over and
12635 	 * provides the most current window information.
12636 	 *
12637 	 * We must avoid the silly window syndrome whereas every read from
12638 	 * the receive buffer, no matter how small, causes a window update
12639 	 * to be sent.  We also should avoid sending a flurry of window
12640 	 * updates when the socket buffer had queued a lot of data and the
12641 	 * application is doing small reads.
12642 	 *
12643 	 * Prevent a flurry of pointless window updates by only sending an
12644 	 * update when we can increase the advertized window by more than
12645 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12646 	 * full or is very small be more aggressive and send an update
12647 	 * whenever we can increase by two mss sized segments. In all other
12648 	 * situations the ACK's to new incoming data will carry further
12649 	 * window increases.
12650 	 *
12651 	 * Don't send an independent window update if a delayed ACK is
12652 	 * pending (it will get piggy-backed on it) or the remote side
12653 	 * already has done a half-close and won't send more data.  Skip
12654 	 * this if the connection is in T/TCP half-open state.
12655 	 */
12656 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12657 	    !(tp->t_flags & TF_DELACK) &&
12658 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12659 		/* Check to see if we should do a window update */
12660 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12661 			goto send;
12662 	}
12663 	/*
12664 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12665 	 * is also a catch-all for the retransmit timer timeout case.
12666 	 */
12667 	if (tp->t_flags & TF_ACKNOW) {
12668 		goto send;
12669 	}
12670 	if (flags & TH_RST) {
12671 		/* Always send a RST if one is due */
12672 		goto send;
12673 	}
12674 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12675 		goto send;
12676 	}
12677 	/*
12678 	 * If our state indicates that FIN should be sent and we have not
12679 	 * yet done so, then we need to send.
12680 	 */
12681 	if (flags & TH_FIN &&
12682 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12683 		goto send;
12684 	}
12685 	/*
12686 	 * No reason to send a segment, just return.
12687 	 */
12688 just_return:
12689 	SOCKBUF_UNLOCK(sb);
12690 just_return_nolock:
12691 	if (tot_len)
12692 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12693 	if (bbr->rc_no_pacing)
12694 		slot = 0;
12695 	if (tot_len == 0) {
12696 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12697 		    tp->snd_wnd) {
12698 			BBR_STAT_INC(bbr_rwnd_limited);
12699 			app_limited = BBR_JR_RWND_LIMITED;
12700 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12701 			if ((bbr->rc_in_persist == 0) &&
12702 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12703 			    (tp->snd_max == tp->snd_una) &&
12704 			    sbavail(&so->so_snd)) {
12705 				/* No send window.. we must enter persist */
12706 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12707 			}
12708 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12709 			BBR_STAT_INC(bbr_app_limited);
12710 			app_limited = BBR_JR_APP_LIMITED;
12711 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12712 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12713 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12714 			BBR_STAT_INC(bbr_cwnd_limited);
12715  			app_limited = BBR_JR_CWND_LIMITED;
12716 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12717 									bbr->r_ctl.rc_lost_bytes)));
12718 			bbr->rc_cwnd_limited = 1;
12719 		} else {
12720 			BBR_STAT_INC(bbr_app_limited);
12721 			app_limited = BBR_JR_APP_LIMITED;
12722 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12723 		}
12724 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12725 		bbr->r_agg_early_set = 0;
12726 		bbr->r_ctl.rc_agg_early = 0;
12727 		bbr->r_ctl.rc_last_delay_val = 0;
12728 	} else if (bbr->rc_use_google == 0)
12729 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12730 	/* Are we app limited? */
12731 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12732 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12733 		/**
12734 		 * We are application limited.
12735 		 */
12736 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12737 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12738 	}
12739 	if (tot_len == 0)
12740 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12741 	/* Dont update the time if we did not send */
12742 	bbr->r_ctl.rc_last_delay_val = 0;
12743 	bbr->rc_output_starts_timer = 1;
12744 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12745 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12746 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12747 		/* Make sure snd_nxt is drug up */
12748 		tp->snd_nxt = tp->snd_max;
12749 	}
12750 	return (error);
12751 
12752 send:
12753 	if (doing_tlp == 0) {
12754 		/*
12755 		 * Data not a TLP, and its not the rxt firing. If it is the
12756 		 * rxt firing, we want to leave the tlp_in_progress flag on
12757 		 * so we don't send another TLP. It has to be a rack timer
12758 		 * or normal send (response to acked data) to clear the tlp
12759 		 * in progress flag.
12760 		 */
12761 		bbr->rc_tlp_in_progress = 0;
12762 		bbr->rc_tlp_rtx_out = 0;
12763 	} else {
12764 		/*
12765 		 * Its a TLP.
12766 		 */
12767 		bbr->rc_tlp_in_progress = 1;
12768 	}
12769 	bbr_timer_cancel(bbr, __LINE__, cts);
12770 	if (rsm == NULL) {
12771 		if (sbused(sb) > 0) {
12772 			/*
12773 			 * This is sub-optimal. We only send a stand alone
12774 			 * FIN on its own segment.
12775 			 */
12776 			if (flags & TH_FIN) {
12777 				flags &= ~TH_FIN;
12778 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12779 					/* Lets not send this */
12780 					slot = 0;
12781 					goto just_return;
12782 				}
12783 			}
12784 		}
12785 	} else {
12786 		/*
12787 		 * We do *not* send a FIN on a retransmit if it has data.
12788 		 * The if clause here where len > 1 should never come true.
12789 		 */
12790 		if ((len > 0) &&
12791 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12792 		    (flags & TH_FIN))) {
12793 			flags &= ~TH_FIN;
12794 			len--;
12795 		}
12796 	}
12797 	SOCKBUF_LOCK_ASSERT(sb);
12798 	if (len > 0) {
12799 		if ((tp->snd_una == tp->snd_max) &&
12800 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12801 			/*
12802 			 * This qualifies as a RTT_PROBE session since we
12803 			 * drop the data outstanding to nothing and waited
12804 			 * more than bbr_rtt_probe_time.
12805 			 */
12806 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12807 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12808 		}
12809 		if (len >= maxseg)
12810 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12811 		else
12812 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12813 	}
12814 	/*
12815 	 * Before ESTABLISHED, force sending of initial options unless TCP
12816 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12817 	 * plus TCP options always fit in a single mbuf, leaving room for a
12818 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12819 	 * + optlen <= MCLBYTES
12820 	 */
12821 	optlen = 0;
12822 #ifdef INET6
12823 	if (isipv6)
12824 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12825 	else
12826 #endif
12827 		hdrlen = sizeof(struct tcpiphdr);
12828 
12829 	/*
12830 	 * Compute options for segment. We only have to care about SYN and
12831 	 * established connection segments.  Options for SYN-ACK segments
12832 	 * are handled in TCP syncache.
12833 	 */
12834 	to.to_flags = 0;
12835 	local_options = 0;
12836 	if ((tp->t_flags & TF_NOOPT) == 0) {
12837 		/* Maximum segment size. */
12838 		if (flags & TH_SYN) {
12839 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12840 			if (tp->t_port)
12841 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12842 			to.to_flags |= TOF_MSS;
12843 			/*
12844 			 * On SYN or SYN|ACK transmits on TFO connections,
12845 			 * only include the TFO option if it is not a
12846 			 * retransmit, as the presence of the TFO option may
12847 			 * have caused the original SYN or SYN|ACK to have
12848 			 * been dropped by a middlebox.
12849 			 */
12850 			if (IS_FASTOPEN(tp->t_flags) &&
12851 			    (tp->t_rxtshift == 0)) {
12852 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12853 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12854 					to.to_tfo_cookie =
12855 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12856 					to.to_flags |= TOF_FASTOPEN;
12857 					wanted_cookie = 1;
12858 				} else if (tp->t_state == TCPS_SYN_SENT) {
12859 					to.to_tfo_len =
12860 					    tp->t_tfo_client_cookie_len;
12861 					to.to_tfo_cookie =
12862 					    tp->t_tfo_cookie.client;
12863 					to.to_flags |= TOF_FASTOPEN;
12864 					wanted_cookie = 1;
12865 				}
12866 			}
12867 		}
12868 		/* Window scaling. */
12869 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12870 			to.to_wscale = tp->request_r_scale;
12871 			to.to_flags |= TOF_SCALE;
12872 		}
12873 		/* Timestamps. */
12874 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12875 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12876 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12877 			to.to_tsecr = tp->ts_recent;
12878 			to.to_flags |= TOF_TS;
12879 			local_options += TCPOLEN_TIMESTAMP + 2;
12880 		}
12881 		/* Set receive buffer autosizing timestamp. */
12882 		if (tp->rfbuf_ts == 0 &&
12883 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12884 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12885 		/* Selective ACK's. */
12886 		if (flags & TH_SYN)
12887 			to.to_flags |= TOF_SACKPERM;
12888 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12889 		    tp->rcv_numsacks > 0) {
12890 			to.to_flags |= TOF_SACK;
12891 			to.to_nsacks = tp->rcv_numsacks;
12892 			to.to_sacks = (u_char *)tp->sackblks;
12893 		}
12894 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
12895 		/* TCP-MD5 (RFC2385). */
12896 		if (tp->t_flags & TF_SIGNATURE)
12897 			to.to_flags |= TOF_SIGNATURE;
12898 #endif				/* TCP_SIGNATURE */
12899 
12900 		/* Processing the options. */
12901 		hdrlen += (optlen = tcp_addoptions(&to, opt));
12902 		/*
12903 		 * If we wanted a TFO option to be added, but it was unable
12904 		 * to fit, ensure no data is sent.
12905 		 */
12906 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
12907 		    !(to.to_flags & TOF_FASTOPEN))
12908 			len = 0;
12909 	}
12910 	if (tp->t_port) {
12911 		if (V_tcp_udp_tunneling_port == 0) {
12912 			/* The port was removed?? */
12913 			SOCKBUF_UNLOCK(&so->so_snd);
12914 			return (EHOSTUNREACH);
12915 		}
12916 		hdrlen += sizeof(struct udphdr);
12917 	}
12918 #ifdef INET6
12919 	if (isipv6)
12920 		ipoptlen = ip6_optlen(inp);
12921 	else
12922 #endif
12923 	if (inp->inp_options)
12924 		ipoptlen = inp->inp_options->m_len -
12925 		    offsetof(struct ipoption, ipopt_list);
12926 	else
12927 		ipoptlen = 0;
12928 	ipoptlen = 0;
12929 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12930 	ipoptlen += ipsec_optlen;
12931 #endif
12932 	if (bbr->rc_last_options != local_options) {
12933 		/*
12934 		 * Cache the options length this generally does not change
12935 		 * on a connection. We use this to calculate TSO.
12936 		 */
12937 		bbr->rc_last_options = local_options;
12938 	}
12939 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
12940 	p_maxseg = min(maxseg, pace_max_segs);
12941 	/*
12942 	 * Adjust data length if insertion of options will bump the packet
12943 	 * length beyond the t_maxseg length. Clear the FIN bit because we
12944 	 * cut off the tail of the segment.
12945 	 */
12946 	if (len > maxseg) {
12947 		if (len != 0 && (flags & TH_FIN)) {
12948 			flags &= ~TH_FIN;
12949 		}
12950 		if (tso) {
12951 			uint32_t moff;
12952 			int32_t max_len;
12953 
12954 			/* extract TSO information */
12955 			if_hw_tsomax = tp->t_tsomax;
12956 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
12957 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
12958 			KASSERT(ipoptlen == 0,
12959 			    ("%s: TSO can't do IP options", __func__));
12960 
12961 			/*
12962 			 * Check if we should limit by maximum payload
12963 			 * length:
12964 			 */
12965 			if (if_hw_tsomax != 0) {
12966 				/* compute maximum TSO length */
12967 				max_len = (if_hw_tsomax - hdrlen -
12968 				    max_linkhdr);
12969 				if (max_len <= 0) {
12970 					len = 0;
12971 				} else if (len > max_len) {
12972 					len = max_len;
12973 				}
12974 			}
12975 			/*
12976 			 * Prevent the last segment from being fractional
12977 			 * unless the send sockbuf can be emptied:
12978 			 */
12979 			if ((sb_offset + len) < sbavail(sb)) {
12980 				moff = len % (uint32_t)maxseg;
12981 				if (moff != 0) {
12982 					len -= moff;
12983 				}
12984 			}
12985 			/*
12986 			 * In case there are too many small fragments don't
12987 			 * use TSO:
12988 			 */
12989 			if (len <= maxseg) {
12990 				len = maxseg;
12991 				tso = 0;
12992 			}
12993 		} else {
12994 			/* Not doing TSO */
12995 			if (optlen + ipoptlen >= tp->t_maxseg) {
12996 				/*
12997 				 * Since we don't have enough space to put
12998 				 * the IP header chain and the TCP header in
12999 				 * one packet as required by RFC 7112, don't
13000 				 * send it. Also ensure that at least one
13001 				 * byte of the payload can be put into the
13002 				 * TCP segment.
13003 				 */
13004 				SOCKBUF_UNLOCK(&so->so_snd);
13005 				error = EMSGSIZE;
13006 				sack_rxmit = 0;
13007 				goto out;
13008 			}
13009 			len = maxseg;
13010 		}
13011 	} else {
13012 		/* Not doing TSO */
13013 		if_hw_tsomaxsegcount = 0;
13014 		tso = 0;
13015 	}
13016 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13017 	    ("%s: len > IP_MAXPACKET", __func__));
13018 #ifdef DIAGNOSTIC
13019 #ifdef INET6
13020 	if (max_linkhdr + hdrlen > MCLBYTES)
13021 #else
13022 	if (max_linkhdr + hdrlen > MHLEN)
13023 #endif
13024 		panic("tcphdr too big");
13025 #endif
13026 	/*
13027 	 * This KASSERT is here to catch edge cases at a well defined place.
13028 	 * Before, those had triggered (random) panic conditions further
13029 	 * down.
13030 	 */
13031 #ifdef BBR_INVARIANTS
13032 	if (sack_rxmit) {
13033 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13034 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13035 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13036 		}
13037 	}
13038 #endif
13039 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13040 	if ((len == 0) &&
13041 	    (flags & TH_FIN) &&
13042 	    (sbused(sb))) {
13043 		/*
13044 		 * We have outstanding data, don't send a fin by itself!.
13045 		 */
13046 		slot = 0;
13047 		goto just_return;
13048 	}
13049 	/*
13050 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13051 	 * and initialize the header from the template for sends on this
13052 	 * connection.
13053 	 */
13054 	if (len) {
13055 		uint32_t moff;
13056 
13057 		/*
13058 		 * We place a limit on sending with hptsi.
13059 		 */
13060 		if ((rsm == NULL) && len > pace_max_segs)
13061 			len = pace_max_segs;
13062 		if (len <= maxseg)
13063 			tso = 0;
13064 #ifdef INET6
13065 		if (MHLEN < hdrlen + max_linkhdr)
13066 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13067 		else
13068 #endif
13069 			m = m_gethdr(M_NOWAIT, MT_DATA);
13070 
13071 		if (m == NULL) {
13072 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13073 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13074 			SOCKBUF_UNLOCK(sb);
13075 			error = ENOBUFS;
13076 			sack_rxmit = 0;
13077 			goto out;
13078 		}
13079 		m->m_data += max_linkhdr;
13080 		m->m_len = hdrlen;
13081 		/*
13082 		 * Start the m_copy functions from the closest mbuf to the
13083 		 * sb_offset in the socket buffer chain.
13084 		 */
13085 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13086 #ifdef BBR_INVARIANTS
13087 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13088 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13089 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13090 				    doing_retran_from,
13091 				    picked_up_retran,
13092 				    doing_tlp);
13093 
13094 #endif
13095 			/*
13096 			 * In this messed up situation we have two choices,
13097 			 * a) pretend the send worked, and just start timers
13098 			 * and what not (not good since that may lead us
13099 			 * back here a lot). <or> b) Send the lowest segment
13100 			 * in the map. <or> c) Drop the connection. Lets do
13101 			 * <b> which if it continues to happen will lead to
13102 			 * <c> via timeouts.
13103 			 */
13104 			BBR_STAT_INC(bbr_offset_recovery);
13105 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13106 			sb_offset = 0;
13107 			if (rsm == NULL) {
13108 				sack_rxmit = 0;
13109 				len = sbavail(sb);
13110 			} else {
13111 				sack_rxmit = 1;
13112 				if (rsm->r_start != tp->snd_una) {
13113 					/*
13114 					 * Things are really messed up, <c>
13115 					 * is the only thing to do.
13116 					 */
13117 					BBR_STAT_INC(bbr_offset_drop);
13118 					SOCKBUF_UNLOCK(sb);
13119 					(void)m_free(m);
13120 					return (-EFAULT); /* tcp_drop() */
13121 				}
13122 				len = rsm->r_end - rsm->r_start;
13123 			}
13124 			if (len > sbavail(sb))
13125 				len = sbavail(sb);
13126 			if (len > maxseg)
13127 				len = maxseg;
13128 		}
13129 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13130 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13131 			m_copydata(mb, moff, (int)len,
13132 			    mtod(m, caddr_t)+hdrlen);
13133 			if (rsm == NULL)
13134 				sbsndptr_adv(sb, mb, len);
13135 			m->m_len += len;
13136 		} else {
13137 			struct sockbuf *msb;
13138 
13139 			if (rsm)
13140 				msb = NULL;
13141 			else
13142 				msb = sb;
13143 #ifdef BBR_INVARIANTS
13144 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13145 				if (rsm) {
13146 					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 ",
13147 					    tp, bbr, len, moff,
13148 					    sbavail(sb), rsm,
13149 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13150 					    doing_retran_from,
13151 					    picked_up_retran,
13152 					    doing_tlp, sack_rxmit);
13153 				} else {
13154 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13155 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13156 				}
13157 			}
13158 #endif
13159 			m->m_next = tcp_m_copym(
13160 				mb, moff, &len,
13161 				if_hw_tsomaxsegcount,
13162 				if_hw_tsomaxsegsize, msb,
13163 				((rsm == NULL) ? hw_tls : 0)
13164 #ifdef NETFLIX_COPY_ARGS
13165 				, &filled_all
13166 #endif
13167 				);
13168 			if (len <= maxseg) {
13169 				/*
13170 				 * Must have ran out of mbufs for the copy
13171 				 * shorten it to no longer need tso. Lets
13172 				 * not put on sendalot since we are low on
13173 				 * mbufs.
13174 				 */
13175 				tso = 0;
13176 			}
13177 			if (m->m_next == NULL) {
13178 				SOCKBUF_UNLOCK(sb);
13179 				(void)m_free(m);
13180 				error = ENOBUFS;
13181 				sack_rxmit = 0;
13182 				goto out;
13183 			}
13184 		}
13185 #ifdef BBR_INVARIANTS
13186 		if (tso && len < maxseg) {
13187 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13188 			    tp, len, maxseg);
13189 		}
13190 		if (tso && if_hw_tsomaxsegcount) {
13191 			int32_t seg_cnt = 0;
13192 			struct mbuf *foo;
13193 
13194 			foo = m;
13195 			while (foo) {
13196 				seg_cnt++;
13197 				foo = foo->m_next;
13198 			}
13199 			if (seg_cnt > if_hw_tsomaxsegcount) {
13200 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13201 			}
13202 		}
13203 #endif
13204 		/*
13205 		 * If we're sending everything we've got, set PUSH. (This
13206 		 * will keep happy those implementations which only give
13207 		 * data to the user when a buffer fills or a PUSH comes in.)
13208 		 */
13209 		if (sb_offset + len == sbused(sb) &&
13210 		    sbused(sb) &&
13211 		    !(flags & TH_SYN)) {
13212 			flags |= TH_PUSH;
13213 		}
13214 		SOCKBUF_UNLOCK(sb);
13215 	} else {
13216 		SOCKBUF_UNLOCK(sb);
13217 		if (tp->t_flags & TF_ACKNOW)
13218 			KMOD_TCPSTAT_INC(tcps_sndacks);
13219 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13220 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13221 		else
13222 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13223 
13224 		m = m_gethdr(M_NOWAIT, MT_DATA);
13225 		if (m == NULL) {
13226 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13227 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13228 			error = ENOBUFS;
13229 			/* Fudge the send time since we could not send */
13230 			sack_rxmit = 0;
13231 			goto out;
13232 		}
13233 #ifdef INET6
13234 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13235 		    MHLEN >= hdrlen) {
13236 			M_ALIGN(m, hdrlen);
13237 		} else
13238 #endif
13239 			m->m_data += max_linkhdr;
13240 		m->m_len = hdrlen;
13241 	}
13242 	SOCKBUF_UNLOCK_ASSERT(sb);
13243 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13244 #ifdef MAC
13245 	mac_inpcb_create_mbuf(inp, m);
13246 #endif
13247 #ifdef INET6
13248 	if (isipv6) {
13249 		ip6 = mtod(m, struct ip6_hdr *);
13250 		if (tp->t_port) {
13251 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13252 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13253 			udp->uh_dport = tp->t_port;
13254 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13255 			udp->uh_ulen = htons(ulen);
13256 			th = (struct tcphdr *)(udp + 1);
13257 		} else {
13258 			th = (struct tcphdr *)(ip6 + 1);
13259 		}
13260 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13261 	} else
13262 #endif				/* INET6 */
13263 	{
13264 		ip = mtod(m, struct ip *);
13265 		if (tp->t_port) {
13266 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13267 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13268 			udp->uh_dport = tp->t_port;
13269 			ulen = hdrlen + len - sizeof(struct ip);
13270 			udp->uh_ulen = htons(ulen);
13271 			th = (struct tcphdr *)(udp + 1);
13272 		} else {
13273 			th = (struct tcphdr *)(ip + 1);
13274 		}
13275 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13276 	}
13277 	/*
13278 	 * If we are doing retransmissions, then snd_nxt will not reflect
13279 	 * the first unsent octet.  For ACK only packets, we do not want the
13280 	 * sequence number of the retransmitted packet, we want the sequence
13281 	 * number of the next unsent octet.  So, if there is no data (and no
13282 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13283 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13284 	 * one byte beyond the right edge of the window, so use snd_nxt in
13285 	 * that case, since we know we aren't doing a retransmission.
13286 	 * (retransmit and persist are mutually exclusive...)
13287 	 */
13288 	if (sack_rxmit == 0) {
13289 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13290 			/* New data (including new persists) */
13291 			th->th_seq = htonl(tp->snd_max);
13292 			bbr_seq = tp->snd_max;
13293 		} else if (flags & TH_SYN) {
13294 			/* Syn's always send from iss */
13295 			th->th_seq = htonl(tp->iss);
13296 			bbr_seq = tp->iss;
13297 		} else if (flags & TH_FIN) {
13298 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13299 				/*
13300 				 * If we sent the fin already its 1 minus
13301 				 * snd_max
13302 				 */
13303 				th->th_seq = (htonl(tp->snd_max - 1));
13304 				bbr_seq = (tp->snd_max - 1);
13305 			} else {
13306 				/* First time FIN use snd_max */
13307 				th->th_seq = htonl(tp->snd_max);
13308 				bbr_seq = tp->snd_max;
13309 			}
13310 		} else {
13311 			/*
13312 			 * len == 0 and not persist we use snd_max, sending
13313 			 * an ack unless we have sent the fin then its 1
13314 			 * minus.
13315 			 */
13316 			/*
13317 			 * XXXRRS Question if we are in persists and we have
13318 			 * nothing outstanding to send and we have not sent
13319 			 * a FIN, we will send an ACK. In such a case it
13320 			 * might be better to send (tp->snd_una - 1) which
13321 			 * would force the peer to ack.
13322 			 */
13323 			if (tp->t_flags & TF_SENTFIN) {
13324 				th->th_seq = htonl(tp->snd_max - 1);
13325 				bbr_seq = (tp->snd_max - 1);
13326 			} else {
13327 				th->th_seq = htonl(tp->snd_max);
13328 				bbr_seq = tp->snd_max;
13329 			}
13330 		}
13331 	} else {
13332 		/* All retransmits use the rsm to guide the send */
13333 		th->th_seq = htonl(rsm->r_start);
13334 		bbr_seq = rsm->r_start;
13335 	}
13336 	th->th_ack = htonl(tp->rcv_nxt);
13337 	if (optlen) {
13338 		bcopy(opt, th + 1, optlen);
13339 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13340 	}
13341 	tcp_set_flags(th, flags);
13342 	/*
13343 	 * Calculate receive window.  Don't shrink window, but avoid silly
13344 	 * window syndrome.
13345 	 */
13346 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13347 				  recwin < maxseg)))
13348 		recwin = 0;
13349 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13350 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13351 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13352 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13353 		recwin = TCP_MAXWIN << tp->rcv_scale;
13354 
13355 	/*
13356 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13357 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13358 	 * handled in syncache.
13359 	 */
13360 	if (flags & TH_SYN)
13361 		th->th_win = htons((u_short)
13362 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13363 	else {
13364 		/* Avoid shrinking window with window scaling. */
13365 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13366 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13367 	}
13368 	/*
13369 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13370 	 * window.  This may cause the remote transmitter to stall.  This
13371 	 * flag tells soreceive() to disable delayed acknowledgements when
13372 	 * draining the buffer.  This can occur if the receiver is
13373 	 * attempting to read more data than can be buffered prior to
13374 	 * transmitting on the connection.
13375 	 */
13376 	if (th->th_win == 0) {
13377 		tp->t_sndzerowin++;
13378 		tp->t_flags |= TF_RXWIN0SENT;
13379 	} else
13380 		tp->t_flags &= ~TF_RXWIN0SENT;
13381 	/*
13382 	 * We don't support urgent data, but drag along
13383 	 * the pointer in case of a stack switch.
13384 	 */
13385 	tp->snd_up = tp->snd_una;
13386 
13387 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13388 	if (to.to_flags & TOF_SIGNATURE) {
13389 		/*
13390 		 * Calculate MD5 signature and put it into the place
13391 		 * determined before. NOTE: since TCP options buffer doesn't
13392 		 * point into mbuf's data, calculate offset and use it.
13393 		 */
13394 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13395 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13396 			/*
13397 			 * Do not send segment if the calculation of MD5
13398 			 * digest has failed.
13399 			 */
13400 			goto out;
13401 		}
13402 	}
13403 #endif
13404 
13405 	/*
13406 	 * Put TCP length in extended header, and then checksum extended
13407 	 * header and data.
13408 	 */
13409 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13410 #ifdef INET6
13411 	if (isipv6) {
13412 		/*
13413 		 * ip6_plen is not need to be filled now, and will be filled
13414 		 * in ip6_output.
13415 		 */
13416 		if (tp->t_port) {
13417 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13418 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13419 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13420 			th->th_sum = htons(0);
13421 			UDPSTAT_INC(udps_opackets);
13422 		} else {
13423 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13424 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13425 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13426 			    optlen + len, IPPROTO_TCP, 0);
13427 		}
13428 	}
13429 #endif
13430 #if defined(INET6) && defined(INET)
13431 	else
13432 #endif
13433 #ifdef INET
13434 	{
13435 		if (tp->t_port) {
13436 			m->m_pkthdr.csum_flags = CSUM_UDP;
13437 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13438 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13439 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13440 			th->th_sum = htons(0);
13441 			UDPSTAT_INC(udps_opackets);
13442 		} else {
13443 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13444 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13445 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13446 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13447 			    IPPROTO_TCP + len + optlen));
13448 		}
13449 		/* IP version must be set here for ipv4/ipv6 checking later */
13450 		KASSERT(ip->ip_v == IPVERSION,
13451 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13452 	}
13453 #endif
13454 
13455 	/*
13456 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13457 	 * header checksum is always provided. XXX: Fixme: This is currently
13458 	 * not the case for IPv6.
13459 	 */
13460 	if (tso) {
13461 		KASSERT(len > maxseg,
13462 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13463 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13464 		csum_flags |= CSUM_TSO;
13465 		m->m_pkthdr.tso_segsz = maxseg;
13466 	}
13467 	KASSERT(len + hdrlen == m_length(m, NULL),
13468 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13469 	    __func__, len, hdrlen, m_length(m, NULL)));
13470 
13471 #ifdef TCP_HHOOK
13472 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13473 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13474 #endif
13475 
13476 	/* Log to the black box */
13477 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13478 		union tcp_log_stackspecific log;
13479 
13480 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13481 		/* Record info on type of transmission */
13482 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13483 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13484 		log.u_bbr.flex3 = maxseg;
13485 		log.u_bbr.flex4 = delay_calc;
13486 		/* Encode filled_all into the upper flex5 bit */
13487 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13488 		log.u_bbr.flex5 <<= 1;
13489 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13490 		log.u_bbr.flex5 <<= 29;
13491 		if (filled_all)
13492 			log.u_bbr.flex5 |= 0x80000000;
13493 		log.u_bbr.flex5 |= tp->t_maxseg;
13494 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13495 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13496 		/* lets poke in the low and the high here for debugging */
13497 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13498 		if (rsm || sack_rxmit) {
13499 			if (doing_tlp)
13500 				log.u_bbr.flex8 = 2;
13501 			else
13502 				log.u_bbr.flex8 = 1;
13503 		} else {
13504 			log.u_bbr.flex8 = 0;
13505 		}
13506 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13507 		    len, &log, false, NULL, NULL, 0, tv);
13508 	} else {
13509 		lgb = NULL;
13510 	}
13511 	/*
13512 	 * Fill in IP length and desired time to live and send to IP level.
13513 	 * There should be a better way to handle ttl and tos; we could keep
13514 	 * them in the template, but need a way to checksum without them.
13515 	 */
13516 	/*
13517 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13518 	 * because in6_cksum() need it.
13519 	 */
13520 #ifdef INET6
13521 	if (isipv6) {
13522 		/*
13523 		 * we separately set hoplimit for every segment, since the
13524 		 * user might want to change the value via setsockopt. Also,
13525 		 * desired default hop limit might be changed via Neighbor
13526 		 * Discovery.
13527 		 */
13528 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13529 
13530 		/*
13531 		 * Set the packet size here for the benefit of DTrace
13532 		 * probes. ip6_output() will set it properly; it's supposed
13533 		 * to include the option header lengths as well.
13534 		 */
13535 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13536 
13537 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13538 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13539 		else
13540 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13541 
13542 		if (tp->t_state == TCPS_SYN_SENT)
13543 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13544 
13545 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13546 		/* TODO: IPv6 IP6TOS_ECT bit on */
13547 		error = ip6_output(m, inp->in6p_outputopts,
13548 		    &inp->inp_route6,
13549 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13550 		    NULL, NULL, inp);
13551 
13552 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13553 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13554 	}
13555 #endif				/* INET6 */
13556 #if defined(INET) && defined(INET6)
13557 	else
13558 #endif
13559 #ifdef INET
13560 	{
13561 		ip->ip_len = htons(m->m_pkthdr.len);
13562 #ifdef INET6
13563 		if (isipv6)
13564 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13565 #endif				/* INET6 */
13566 		/*
13567 		 * If we do path MTU discovery, then we set DF on every
13568 		 * packet. This might not be the best thing to do according
13569 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13570 		 * the problem so it affects only the first tcp connection
13571 		 * with a host.
13572 		 *
13573 		 * NB: Don't set DF on small MTU/MSS to have a safe
13574 		 * fallback.
13575 		 */
13576 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13577 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13578 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13579 				ip->ip_off |= htons(IP_DF);
13580 			}
13581 		} else {
13582 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13583 		}
13584 
13585 		if (tp->t_state == TCPS_SYN_SENT)
13586 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13587 
13588 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13589 
13590 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13591 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13592 		    inp);
13593 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13594 			mtu = inp->inp_route.ro_nh->nh_mtu;
13595 	}
13596 #endif				/* INET */
13597 out:
13598 
13599 	if (lgb) {
13600 		lgb->tlb_errno = error;
13601 		lgb = NULL;
13602 	}
13603 	/*
13604 	 * In transmit state, time the transmission and arrange for the
13605 	 * retransmit.  In persist state, just set snd_max.
13606 	 */
13607 	if (error == 0) {
13608 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13609 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13610 		    (tp->t_flags & TF_SACK_PERMIT) &&
13611 		    tp->rcv_numsacks > 0)
13612 			tcp_clean_dsack_blocks(tp);
13613 		/* We sent an ack clear the bbr_segs_rcvd count */
13614 		bbr->output_error_seen = 0;
13615 		bbr->oerror_cnt = 0;
13616 		bbr->bbr_segs_rcvd = 0;
13617 		if (len == 0)
13618 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13619 		/* Do accounting for new sends */
13620 		if ((len > 0) && (rsm == NULL)) {
13621 			int idx;
13622 			if (tp->snd_una == tp->snd_max) {
13623 				/*
13624 				 * Special case to match google, when
13625 				 * nothing is in flight the delivered
13626 				 * time does get updated to the current
13627 				 * time (see tcp_rate_bsd.c).
13628 				 */
13629 				bbr->r_ctl.rc_del_time = cts;
13630 			}
13631 			if (len >= maxseg) {
13632 				idx = (len / maxseg) + 3;
13633 				if (idx >= TCP_MSS_ACCT_ATIMER)
13634 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13635 				else
13636 					counter_u64_add(bbr_out_size[idx], 1);
13637 			} else {
13638 				/* smaller than a MSS */
13639 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13640 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13641 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13642 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13643 			}
13644 		}
13645 	}
13646 	abandon = 0;
13647 	/*
13648 	 * We must do the send accounting before we log the output,
13649 	 * otherwise the state of the rsm could change and we account to the
13650 	 * wrong bucket.
13651 	 */
13652 	if (len > 0) {
13653 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13654 		if (error == 0) {
13655 			if (tp->snd_una == tp->snd_max)
13656 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13657 		}
13658 	}
13659 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13660 	    cts, mb, &abandon, rsm, 0, sb);
13661 	if (abandon) {
13662 		/*
13663 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13664 		 * sent we should hit this condition.
13665 		 */
13666 		return (0);
13667 	}
13668 	if (bbr->rc_in_persist == 0) {
13669 		/*
13670 		 * Advance snd_nxt over sequence space of this segment.
13671 		 */
13672 		if (error)
13673 			/* We don't log or do anything with errors */
13674 			goto skip_upd;
13675 
13676 		if (tp->snd_una == tp->snd_max &&
13677 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13678 			/*
13679 			 * Update the time we just added data since none was
13680 			 * outstanding.
13681 			 */
13682 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13683 			bbr->rc_tp->t_acktime  = ticks;
13684 		}
13685 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13686 			if (flags & TH_SYN) {
13687 				/*
13688 				 * Smack the snd_max to iss + 1
13689 				 * if its a FO we will add len below.
13690 				 */
13691 				tp->snd_max = tp->iss + 1;
13692 			}
13693 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13694 				tp->snd_max++;
13695 				tp->t_flags |= TF_SENTFIN;
13696 			}
13697 		}
13698 		if (sack_rxmit == 0)
13699 			tp->snd_max += len;
13700 skip_upd:
13701 		if ((error == 0) && len)
13702 			tot_len += len;
13703 	} else {
13704 		/* Persists case */
13705 		int32_t xlen = len;
13706 
13707 		if (error)
13708 			goto nomore;
13709 
13710 		if (flags & TH_SYN)
13711 			++xlen;
13712 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13713 			++xlen;
13714 			tp->t_flags |= TF_SENTFIN;
13715 		}
13716 		if (xlen && (tp->snd_una == tp->snd_max)) {
13717 			/*
13718 			 * Update the time we just added data since none was
13719 			 * outstanding.
13720 			 */
13721 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13722 			bbr->rc_tp->t_acktime = ticks;
13723 		}
13724 		if (sack_rxmit == 0)
13725 			tp->snd_max += xlen;
13726 		tot_len += (len + optlen + ipoptlen);
13727 	}
13728 nomore:
13729 	if (error) {
13730 		/*
13731 		 * Failures do not advance the seq counter above. For the
13732 		 * case of ENOBUFS we will fall out and become ack-clocked.
13733 		 * capping the cwnd at the current flight.
13734 		 * Everything else will just have to retransmit with the timer
13735 		 * (no pacer).
13736 		 */
13737 		SOCKBUF_UNLOCK_ASSERT(sb);
13738 		BBR_STAT_INC(bbr_saw_oerr);
13739 		/* Clear all delay/early tracks */
13740 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13741 		bbr->r_ctl.rc_agg_early = 0;
13742 		bbr->r_agg_early_set = 0;
13743 		bbr->output_error_seen = 1;
13744 		if (bbr->oerror_cnt < 0xf)
13745 			bbr->oerror_cnt++;
13746 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13747 			/* drop the session */
13748 			return (-ENETDOWN);
13749 		}
13750 		switch (error) {
13751 		case ENOBUFS:
13752 			/*
13753 			 * Make this guy have to get ack's to send
13754 			 * more but lets make sure we don't
13755 			 * slam him below a T-O (1MSS).
13756 			 */
13757 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13758 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13759 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13760 				if (tp->snd_cwnd < maxseg)
13761 					tp->snd_cwnd = maxseg;
13762 			}
13763 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13764 			BBR_STAT_INC(bbr_saw_enobuf);
13765 			if (bbr->bbr_hdrw_pacing)
13766 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13767 			else
13768 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13769 			/*
13770 			 * Here even in the enobuf's case we want to do our
13771 			 * state update. The reason being we may have been
13772 			 * called by the input function. If so we have had
13773 			 * things change.
13774 			 */
13775 			error = 0;
13776 			goto enobufs;
13777 		case EMSGSIZE:
13778 			/*
13779 			 * For some reason the interface we used initially
13780 			 * to send segments changed to another or lowered
13781 			 * its MTU. If TSO was active we either got an
13782 			 * interface without TSO capabilits or TSO was
13783 			 * turned off. If we obtained mtu from ip_output()
13784 			 * then update it and try again.
13785 			 */
13786 			/* Turn on tracing (or try to) */
13787 			{
13788 				int old_maxseg;
13789 
13790 				old_maxseg = tp->t_maxseg;
13791 				BBR_STAT_INC(bbr_saw_emsgsiz);
13792 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13793 				if (mtu != 0)
13794 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13795 				if (old_maxseg <= tp->t_maxseg) {
13796 					/* Huh it did not shrink? */
13797 					tp->t_maxseg = old_maxseg - 40;
13798 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13799 				}
13800 				/*
13801 				 * Nuke all other things that can interfere
13802 				 * with slot
13803 				 */
13804 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13805 					slot = bbr_get_pacing_delay(bbr,
13806 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13807 					    (tot_len + len), cts, 0);
13808 					if (slot < bbr_error_base_paceout)
13809 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13810 				} else
13811 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13812 				bbr->rc_output_starts_timer = 1;
13813 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13814 				    tot_len);
13815 				return (error);
13816 			}
13817 		case EPERM:
13818 			tp->t_softerror = error;
13819 			/* Fall through */
13820 		case EHOSTDOWN:
13821 		case EHOSTUNREACH:
13822 		case ENETDOWN:
13823 		case ENETUNREACH:
13824 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13825 				tp->t_softerror = error;
13826 			}
13827 			/* FALLTHROUGH */
13828 		default:
13829 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13830 			bbr->rc_output_starts_timer = 1;
13831 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13832 			return (error);
13833 		}
13834 #ifdef STATS
13835 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13836 		    len &&
13837 		    (rsm == NULL) &&
13838 	    (bbr->rc_in_persist == 0)) {
13839 		tp->gput_seq = bbr_seq;
13840 		tp->gput_ack = bbr_seq +
13841 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13842 		tp->gput_ts = cts;
13843 		tp->t_flags |= TF_GPUTINPROG;
13844 #endif
13845 	}
13846 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13847 	if ((bbr->bbr_hdw_pace_ena) &&
13848 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13849 	    (bbr->rc_past_init_win) &&
13850 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13851 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13852 	    (inp->inp_route.ro_nh &&
13853 	     inp->inp_route.ro_nh->nh_ifp)) {
13854 		/*
13855 		 * We are past the initial window and
13856 		 * have at least one measurement so we
13857 		 * could use hardware pacing if its available.
13858 		 * We have an interface and we have not attempted
13859 		 * to setup hardware pacing, lets try to now.
13860 		 */
13861 		uint64_t rate_wanted;
13862 		int err = 0;
13863 
13864 		rate_wanted = bbr_get_hardware_rate(bbr);
13865 		bbr->bbr_attempt_hdwr_pace = 1;
13866 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13867 						      inp->inp_route.ro_nh->nh_ifp,
13868 						      rate_wanted,
13869 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
13870 						      &err, NULL);
13871 		if (bbr->r_ctl.crte) {
13872 			bbr_type_log_hdwr_pacing(bbr,
13873 						 bbr->r_ctl.crte->ptbl->rs_ifp,
13874 						 rate_wanted,
13875 						 bbr->r_ctl.crte->rate,
13876 						 __LINE__, cts, err);
13877 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
13878 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
13879 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
13880 			bbr->bbr_hdrw_pacing = 1;
13881 			/* Now what is our gain status? */
13882 			if (bbr->r_ctl.crte->rate < rate_wanted) {
13883 				/* We have a problem */
13884 				bbr_setup_less_of_rate(bbr, cts,
13885 						       bbr->r_ctl.crte->rate, rate_wanted);
13886 			} else {
13887 				/* We are good */
13888 				bbr->gain_is_limited = 0;
13889 				bbr->skip_gain = 0;
13890 			}
13891 			tcp_bbr_tso_size_check(bbr, cts);
13892 		} else {
13893 			bbr_type_log_hdwr_pacing(bbr,
13894 						 inp->inp_route.ro_nh->nh_ifp,
13895 						 rate_wanted,
13896 						 0,
13897 						 __LINE__, cts, err);
13898 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
13899 		}
13900 	}
13901 	if (bbr->bbr_hdrw_pacing) {
13902 		/*
13903 		 * Worry about cases where the route
13904 		 * changes or something happened that we
13905 		 * lost our hardware pacing possibly during
13906 		 * the last ip_output call.
13907 		 */
13908 		if (inp->inp_snd_tag == NULL) {
13909 			/* A change during ip output disabled hw pacing? */
13910 			bbr->bbr_hdrw_pacing = 0;
13911 		} else if ((inp->inp_route.ro_nh == NULL) ||
13912 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
13913 			/*
13914 			 * We had an interface or route change,
13915 			 * detach from the current hdwr pacing
13916 			 * and setup to re-attempt next go
13917 			 * round.
13918 			 */
13919 			bbr->bbr_hdrw_pacing = 0;
13920 			bbr->bbr_attempt_hdwr_pace = 0;
13921 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
13922 			tcp_bbr_tso_size_check(bbr, cts);
13923 		}
13924 	}
13925 	/*
13926 	 * Data sent (as far as we can tell). If this advertises a larger
13927 	 * window than any other segment, then remember the size of the
13928 	 * advertised window. Any pending ACK has now been sent.
13929 	 */
13930 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
13931 		tp->rcv_adv = tp->rcv_nxt + recwin;
13932 
13933 	tp->last_ack_sent = tp->rcv_nxt;
13934 	if ((error == 0) &&
13935 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
13936 	    (doing_tlp == 0) &&
13937 	    (tso == 0) &&
13938 	    (len > 0) &&
13939 	    ((flags & TH_RST) == 0) &&
13940 	    ((flags & TH_SYN) == 0) &&
13941 	    (IN_RECOVERY(tp->t_flags) == 0) &&
13942 	    (bbr->rc_in_persist == 0) &&
13943 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
13944 		/*
13945 		 * For non-tso we need to goto again until we have sent out
13946 		 * enough data to match what we are hptsi out every hptsi
13947 		 * interval.
13948 		 */
13949 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13950 			/* Make sure snd_nxt is drug up */
13951 			tp->snd_nxt = tp->snd_max;
13952 		}
13953 		if (rsm != NULL) {
13954 			rsm = NULL;
13955 			goto skip_again;
13956 		}
13957 		rsm = NULL;
13958 		sack_rxmit = 0;
13959 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13960 		goto again;
13961 	}
13962 skip_again:
13963 	if ((error == 0) && (flags & TH_FIN))
13964 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
13965 	if ((error == 0) && (flags & TH_RST))
13966 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13967 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
13968 		/*
13969 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
13970 		 * what we have sent so far
13971 		 */
13972 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
13973 		if (bbr->rc_no_pacing)
13974 			slot = 0;
13975 	}
13976 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13977 enobufs:
13978 	if (bbr->rc_use_google == 0)
13979 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
13980 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13981 							bbr->r_ctl.rc_lost_bytes)));
13982 	bbr->rc_output_starts_timer = 1;
13983 	if (bbr->bbr_use_rack_cheat &&
13984 	    (more_to_rxt ||
13985 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
13986 		/* Rack cheats and shotguns out all rxt's 1ms apart */
13987 		if (slot > 1000)
13988 			slot = 1000;
13989 	}
13990 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
13991 		/*
13992 		 * We don't change the tso size until some number of sends
13993 		 * to give the hardware commands time to get down
13994 		 * to the interface.
13995 		 */
13996 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
13997 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
13998 			bbr->hw_pacing_set = 1;
13999 			tcp_bbr_tso_size_check(bbr, cts);
14000 		}
14001 	}
14002 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14003 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14004 		/* Make sure snd_nxt is drug up */
14005 		tp->snd_nxt = tp->snd_max;
14006 	}
14007 	return (error);
14008 
14009 }
14010 
14011 /*
14012  * See bbr_output_wtime() for return values.
14013  */
14014 static int
14015 bbr_output(struct tcpcb *tp)
14016 {
14017 	int32_t ret;
14018 	struct timeval tv;
14019 
14020 	NET_EPOCH_ASSERT();
14021 
14022 	INP_WLOCK_ASSERT(tptoinpcb(tp));
14023 	(void)tcp_get_usecs(&tv);
14024 	ret = bbr_output_wtime(tp, &tv);
14025 	return (ret);
14026 }
14027 
14028 static void
14029 bbr_mtu_chg(struct tcpcb *tp)
14030 {
14031 	struct tcp_bbr *bbr;
14032 	struct bbr_sendmap *rsm, *frsm = NULL;
14033 	uint32_t maxseg;
14034 
14035 	/*
14036 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14037 	 * over the current size as SACK_PASS so a retransmit will occur.
14038 	 */
14039 
14040 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14041 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14042 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14043 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14044 		/* Don't mess with ones acked (by sack?) */
14045 		if (rsm->r_flags & BBR_ACKED)
14046 			continue;
14047 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14048 			/*
14049 			 * We mark sack-passed on all the previous large
14050 			 * sends we did. This will force them to retransmit.
14051 			 */
14052 			rsm->r_flags |= BBR_SACK_PASSED;
14053 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14054 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14055 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14056 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14057 				rsm->r_flags |= BBR_MARKED_LOST;
14058 			}
14059 			if (frsm == NULL)
14060 				frsm = rsm;
14061 		}
14062 	}
14063 	if (frsm) {
14064 		bbr->r_ctl.rc_resend = frsm;
14065 	}
14066 }
14067 
14068 static int
14069 bbr_pru_options(struct tcpcb *tp, int flags)
14070 {
14071 	if (flags & PRUS_OOB)
14072 		return (EOPNOTSUPP);
14073 	return (0);
14074 }
14075 
14076 struct tcp_function_block __tcp_bbr = {
14077 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14078 	.tfb_tcp_output = bbr_output,
14079 	.tfb_do_queued_segments = ctf_do_queued_segments,
14080 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14081 	.tfb_tcp_do_segment = bbr_do_segment,
14082 	.tfb_tcp_ctloutput = bbr_ctloutput,
14083 	.tfb_tcp_fb_init = bbr_init,
14084 	.tfb_tcp_fb_fini = bbr_fini,
14085 	.tfb_tcp_timer_stop_all = bbr_stopall,
14086 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14087 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14088 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14089 	.tfb_pru_options = bbr_pru_options,
14090 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14091 };
14092 
14093 /*
14094  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14095  * socket option arguments.  When it re-acquires the lock after the copy, it
14096  * has to revalidate that the connection is still valid for the socket
14097  * option.
14098  */
14099 static int
14100 bbr_set_sockopt(struct inpcb *inp, struct sockopt *sopt)
14101 {
14102 	struct epoch_tracker et;
14103 	struct tcpcb *tp;
14104 	struct tcp_bbr *bbr;
14105 	int32_t error = 0, optval;
14106 
14107 	switch (sopt->sopt_level) {
14108 	case IPPROTO_IPV6:
14109 	case IPPROTO_IP:
14110 		return (tcp_default_ctloutput(inp, sopt));
14111 	}
14112 
14113 	switch (sopt->sopt_name) {
14114 	case TCP_RACK_PACE_MAX_SEG:
14115 	case TCP_RACK_MIN_TO:
14116 	case TCP_RACK_REORD_THRESH:
14117 	case TCP_RACK_REORD_FADE:
14118 	case TCP_RACK_TLP_THRESH:
14119 	case TCP_RACK_PKT_DELAY:
14120 	case TCP_BBR_ALGORITHM:
14121 	case TCP_BBR_TSLIMITS:
14122 	case TCP_BBR_IWINTSO:
14123 	case TCP_BBR_RECFORCE:
14124 	case TCP_BBR_STARTUP_PG:
14125 	case TCP_BBR_DRAIN_PG:
14126 	case TCP_BBR_RWND_IS_APP:
14127 	case TCP_BBR_PROBE_RTT_INT:
14128 	case TCP_BBR_PROBE_RTT_GAIN:
14129 	case TCP_BBR_PROBE_RTT_LEN:
14130 	case TCP_BBR_STARTUP_LOSS_EXIT:
14131 	case TCP_BBR_USEDEL_RATE:
14132 	case TCP_BBR_MIN_RTO:
14133 	case TCP_BBR_MAX_RTO:
14134 	case TCP_BBR_PACE_PER_SEC:
14135 	case TCP_DELACK:
14136 	case TCP_BBR_PACE_DEL_TAR:
14137 	case TCP_BBR_SEND_IWND_IN_TSO:
14138 	case TCP_BBR_EXTRA_STATE:
14139 	case TCP_BBR_UTTER_MAX_TSO:
14140 	case TCP_BBR_MIN_TOPACEOUT:
14141 	case TCP_BBR_FLOOR_MIN_TSO:
14142 	case TCP_BBR_TSTMP_RAISES:
14143 	case TCP_BBR_POLICER_DETECT:
14144 	case TCP_BBR_USE_RACK_CHEAT:
14145 	case TCP_DATA_AFTER_CLOSE:
14146 	case TCP_BBR_HDWR_PACE:
14147 	case TCP_BBR_PACE_SEG_MAX:
14148 	case TCP_BBR_PACE_SEG_MIN:
14149 	case TCP_BBR_PACE_CROSS:
14150 	case TCP_BBR_PACE_OH:
14151 #ifdef NETFLIX_PEAKRATE
14152 	case TCP_MAXPEAKRATE:
14153 #endif
14154 	case TCP_BBR_TMR_PACE_OH:
14155 	case TCP_BBR_RACK_RTT_USE:
14156 	case TCP_BBR_RETRAN_WTSO:
14157 		break;
14158 	default:
14159 		return (tcp_default_ctloutput(inp, sopt));
14160 		break;
14161 	}
14162 	INP_WUNLOCK(inp);
14163 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14164 	if (error)
14165 		return (error);
14166 	INP_WLOCK(inp);
14167 	if (inp->inp_flags & INP_DROPPED) {
14168 		INP_WUNLOCK(inp);
14169 		return (ECONNRESET);
14170 	}
14171 	tp = intotcpcb(inp);
14172 	if (tp->t_fb != &__tcp_bbr) {
14173 		INP_WUNLOCK(inp);
14174 		return (ENOPROTOOPT);
14175 	}
14176 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14177 	switch (sopt->sopt_name) {
14178 	case TCP_BBR_PACE_PER_SEC:
14179 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14180 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14181 		break;
14182 	case TCP_BBR_PACE_DEL_TAR:
14183 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14184 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14185 		break;
14186 	case TCP_BBR_PACE_SEG_MAX:
14187 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14188 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14189 		break;
14190 	case TCP_BBR_PACE_SEG_MIN:
14191 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14192 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14193 		break;
14194 	case TCP_BBR_PACE_CROSS:
14195 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14196 		bbr->r_ctl.bbr_cross_over = optval;
14197 		break;
14198 	case TCP_BBR_ALGORITHM:
14199 		BBR_OPTS_INC(tcp_bbr_algorithm);
14200 		if (optval && (bbr->rc_use_google == 0)) {
14201 			/* Turn on the google mode */
14202 			bbr_google_mode_on(bbr);
14203 			if ((optval > 3) && (optval < 500)) {
14204 				/*
14205 				 * Must be at least greater than .3%
14206 				 * and must be less than 50.0%.
14207 				 */
14208 				bbr->r_ctl.bbr_google_discount = optval;
14209 			}
14210 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14211 			/* Turn off the google mode */
14212 			bbr_google_mode_off(bbr);
14213 		}
14214 		break;
14215 	case TCP_BBR_TSLIMITS:
14216 		BBR_OPTS_INC(tcp_bbr_tslimits);
14217 		if (optval == 1)
14218 			bbr->rc_use_ts_limit = 1;
14219 		else if (optval == 0)
14220 			bbr->rc_use_ts_limit = 0;
14221 		else
14222 			error = EINVAL;
14223 		break;
14224 
14225 	case TCP_BBR_IWINTSO:
14226 		BBR_OPTS_INC(tcp_bbr_iwintso);
14227 		if ((optval >= 0) && (optval < 128)) {
14228 			uint32_t twin;
14229 
14230 			bbr->rc_init_win = optval;
14231 			twin = bbr_initial_cwnd(bbr, tp);
14232 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14233 				tp->snd_cwnd = twin;
14234 			else
14235 				error = EBUSY;
14236 		} else
14237 			error = EINVAL;
14238 		break;
14239 	case TCP_BBR_STARTUP_PG:
14240 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14241 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14242 			bbr->r_ctl.rc_startup_pg = optval;
14243 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14244 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14245 			}
14246 		} else
14247 			error = EINVAL;
14248 		break;
14249 	case TCP_BBR_DRAIN_PG:
14250 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14251 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14252 			bbr->r_ctl.rc_drain_pg = optval;
14253 		else
14254 			error = EINVAL;
14255 		break;
14256 	case TCP_BBR_PROBE_RTT_LEN:
14257 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14258 		if (optval <= 1)
14259 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14260 		else
14261 			error = EINVAL;
14262 		break;
14263 	case TCP_BBR_PROBE_RTT_GAIN:
14264 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14265 		if (optval <= BBR_UNIT)
14266 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14267 		else
14268 			error = EINVAL;
14269 		break;
14270 	case TCP_BBR_PROBE_RTT_INT:
14271 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14272 		if (optval > 1000)
14273 			bbr->r_ctl.rc_probertt_int = optval;
14274 		else
14275 			error = EINVAL;
14276 		break;
14277 	case TCP_BBR_MIN_TOPACEOUT:
14278 		BBR_OPTS_INC(tcp_bbr_topaceout);
14279 		if (optval == 0) {
14280 			bbr->no_pacing_until = 0;
14281 			bbr->rc_no_pacing = 0;
14282 		} else if (optval <= 0x00ff) {
14283 			bbr->no_pacing_until = optval;
14284 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14285 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14286 				/* Turn on no pacing */
14287 				bbr->rc_no_pacing = 1;
14288 			}
14289 		} else
14290 			error = EINVAL;
14291 		break;
14292 	case TCP_BBR_STARTUP_LOSS_EXIT:
14293 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14294 		bbr->rc_loss_exit = optval;
14295 		break;
14296 	case TCP_BBR_USEDEL_RATE:
14297 		error = EINVAL;
14298 		break;
14299 	case TCP_BBR_MIN_RTO:
14300 		BBR_OPTS_INC(tcp_bbr_min_rto);
14301 		bbr->r_ctl.rc_min_rto_ms = optval;
14302 		break;
14303 	case TCP_BBR_MAX_RTO:
14304 		BBR_OPTS_INC(tcp_bbr_max_rto);
14305 		bbr->rc_max_rto_sec = optval;
14306 		break;
14307 	case TCP_RACK_MIN_TO:
14308 		/* Minimum time between rack t-o's in ms */
14309 		BBR_OPTS_INC(tcp_rack_min_to);
14310 		bbr->r_ctl.rc_min_to = optval;
14311 		break;
14312 	case TCP_RACK_REORD_THRESH:
14313 		/* RACK reorder threshold (shift amount) */
14314 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14315 		if ((optval > 0) && (optval < 31))
14316 			bbr->r_ctl.rc_reorder_shift = optval;
14317 		else
14318 			error = EINVAL;
14319 		break;
14320 	case TCP_RACK_REORD_FADE:
14321 		/* Does reordering fade after ms time */
14322 		BBR_OPTS_INC(tcp_rack_reord_fade);
14323 		bbr->r_ctl.rc_reorder_fade = optval;
14324 		break;
14325 	case TCP_RACK_TLP_THRESH:
14326 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14327 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14328 		if (optval)
14329 			bbr->rc_tlp_threshold = optval;
14330 		else
14331 			error = EINVAL;
14332 		break;
14333 	case TCP_BBR_USE_RACK_CHEAT:
14334 		BBR_OPTS_INC(tcp_use_rackcheat);
14335 		if (bbr->rc_use_google) {
14336 			error = EINVAL;
14337 			break;
14338 		}
14339 		BBR_OPTS_INC(tcp_rack_cheat);
14340 		if (optval)
14341 			bbr->bbr_use_rack_cheat = 1;
14342 		else
14343 			bbr->bbr_use_rack_cheat = 0;
14344 		break;
14345 	case TCP_BBR_FLOOR_MIN_TSO:
14346 		BBR_OPTS_INC(tcp_utter_max_tso);
14347 		if ((optval >= 0) && (optval < 40))
14348 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14349 		else
14350 			error = EINVAL;
14351 		break;
14352 	case TCP_BBR_UTTER_MAX_TSO:
14353 		BBR_OPTS_INC(tcp_utter_max_tso);
14354 		if ((optval >= 0) && (optval < 0xffff))
14355 			bbr->r_ctl.bbr_utter_max = optval;
14356 		else
14357 			error = EINVAL;
14358 		break;
14359 
14360 	case TCP_BBR_EXTRA_STATE:
14361 		BBR_OPTS_INC(tcp_extra_state);
14362 		if (optval)
14363 			bbr->rc_use_idle_restart = 1;
14364 		else
14365 			bbr->rc_use_idle_restart = 0;
14366 		break;
14367 	case TCP_BBR_SEND_IWND_IN_TSO:
14368 		BBR_OPTS_INC(tcp_iwnd_tso);
14369 		if (optval) {
14370 			bbr->bbr_init_win_cheat = 1;
14371 			if (bbr->rc_past_init_win == 0) {
14372 				uint32_t cts;
14373 				cts = tcp_get_usecs(&bbr->rc_tv);
14374 				tcp_bbr_tso_size_check(bbr, cts);
14375 			}
14376 		} else
14377 			bbr->bbr_init_win_cheat = 0;
14378 		break;
14379 	case TCP_BBR_HDWR_PACE:
14380 		BBR_OPTS_INC(tcp_hdwr_pacing);
14381 		if (optval){
14382 			bbr->bbr_hdw_pace_ena = 1;
14383 			bbr->bbr_attempt_hdwr_pace = 0;
14384 		} else {
14385 			bbr->bbr_hdw_pace_ena = 0;
14386 #ifdef RATELIMIT
14387 			if (bbr->r_ctl.crte != NULL) {
14388 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14389 				bbr->r_ctl.crte = NULL;
14390 			}
14391 #endif
14392 		}
14393 		break;
14394 
14395 	case TCP_DELACK:
14396 		BBR_OPTS_INC(tcp_delack);
14397 		if (optval < 100) {
14398 			if (optval == 0) /* off */
14399 				tp->t_delayed_ack = 0;
14400 			else if (optval == 1) /* on which is 2 */
14401 				tp->t_delayed_ack = 2;
14402 			else /* higher than 2 and less than 100 */
14403 				tp->t_delayed_ack = optval;
14404 			if (tp->t_flags & TF_DELACK) {
14405 				tp->t_flags &= ~TF_DELACK;
14406 				tp->t_flags |= TF_ACKNOW;
14407 				NET_EPOCH_ENTER(et);
14408 				bbr_output(tp);
14409 				NET_EPOCH_EXIT(et);
14410 			}
14411 		} else
14412 			error = EINVAL;
14413 		break;
14414 	case TCP_RACK_PKT_DELAY:
14415 		/* RACK added ms i.e. rack-rtt + reord + N */
14416 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14417 		bbr->r_ctl.rc_pkt_delay = optval;
14418 		break;
14419 #ifdef NETFLIX_PEAKRATE
14420 	case TCP_MAXPEAKRATE:
14421 		BBR_OPTS_INC(tcp_maxpeak);
14422 		error = tcp_set_maxpeakrate(tp, optval);
14423 		if (!error)
14424 			tp->t_peakrate_thr = tp->t_maxpeakrate;
14425 		break;
14426 #endif
14427 	case TCP_BBR_RETRAN_WTSO:
14428 		BBR_OPTS_INC(tcp_retran_wtso);
14429 		if (optval)
14430 			bbr->rc_resends_use_tso = 1;
14431 		else
14432 			bbr->rc_resends_use_tso = 0;
14433 		break;
14434 	case TCP_DATA_AFTER_CLOSE:
14435 		BBR_OPTS_INC(tcp_data_ac);
14436 		if (optval)
14437 			bbr->rc_allow_data_af_clo = 1;
14438 		else
14439 			bbr->rc_allow_data_af_clo = 0;
14440 		break;
14441 	case TCP_BBR_POLICER_DETECT:
14442 		BBR_OPTS_INC(tcp_policer_det);
14443 		if (bbr->rc_use_google == 0)
14444 			error = EINVAL;
14445 		else if (optval)
14446 			bbr->r_use_policer = 1;
14447 		else
14448 			bbr->r_use_policer = 0;
14449 		break;
14450 
14451 	case TCP_BBR_TSTMP_RAISES:
14452 		BBR_OPTS_INC(tcp_ts_raises);
14453 		if (optval)
14454 			bbr->ts_can_raise = 1;
14455 		else
14456 			bbr->ts_can_raise = 0;
14457 		break;
14458 	case TCP_BBR_TMR_PACE_OH:
14459 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14460 		if (bbr->rc_use_google) {
14461 			error = EINVAL;
14462 		} else {
14463 			if (optval)
14464 				bbr->r_ctl.rc_incr_tmrs = 1;
14465 			else
14466 				bbr->r_ctl.rc_incr_tmrs = 0;
14467 		}
14468 		break;
14469 	case TCP_BBR_PACE_OH:
14470 		BBR_OPTS_INC(tcp_pacing_oh);
14471 		if (bbr->rc_use_google) {
14472 			error = EINVAL;
14473 		} else {
14474 			if (optval > (BBR_INCL_TCP_OH|
14475 				      BBR_INCL_IP_OH|
14476 				      BBR_INCL_ENET_OH)) {
14477 				error = EINVAL;
14478 				break;
14479 			}
14480 			if (optval & BBR_INCL_TCP_OH)
14481 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14482 			else
14483 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14484 			if (optval & BBR_INCL_IP_OH)
14485 				bbr->r_ctl.rc_inc_ip_oh = 1;
14486 			else
14487 				bbr->r_ctl.rc_inc_ip_oh = 0;
14488 			if (optval & BBR_INCL_ENET_OH)
14489 				bbr->r_ctl.rc_inc_enet_oh = 1;
14490 			else
14491 				bbr->r_ctl.rc_inc_enet_oh = 0;
14492 		}
14493 		break;
14494 	default:
14495 		return (tcp_default_ctloutput(inp, sopt));
14496 		break;
14497 	}
14498 #ifdef NETFLIX_STATS
14499 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14500 #endif
14501 	INP_WUNLOCK(inp);
14502 	return (error);
14503 }
14504 
14505 /*
14506  * return 0 on success, error-num on failure
14507  */
14508 static int
14509 bbr_get_sockopt(struct inpcb *inp, struct sockopt *sopt)
14510 {
14511 	struct tcpcb *tp;
14512 	struct tcp_bbr *bbr;
14513 	int32_t error, optval;
14514 
14515 	tp = intotcpcb(inp);
14516 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14517 	if (bbr == NULL) {
14518 		INP_WUNLOCK(inp);
14519 		return (EINVAL);
14520 	}
14521 	/*
14522 	 * Because all our options are either boolean or an int, we can just
14523 	 * pull everything into optval and then unlock and copy. If we ever
14524 	 * add a option that is not a int, then this will have quite an
14525 	 * impact to this routine.
14526 	 */
14527 	switch (sopt->sopt_name) {
14528 	case TCP_BBR_PACE_PER_SEC:
14529 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14530 		break;
14531 	case TCP_BBR_PACE_DEL_TAR:
14532 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14533 		break;
14534 	case TCP_BBR_PACE_SEG_MAX:
14535 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14536 		break;
14537 	case TCP_BBR_MIN_TOPACEOUT:
14538 		optval = bbr->no_pacing_until;
14539 		break;
14540 	case TCP_BBR_PACE_SEG_MIN:
14541 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14542 		break;
14543 	case TCP_BBR_PACE_CROSS:
14544 		optval = bbr->r_ctl.bbr_cross_over;
14545 		break;
14546 	case TCP_BBR_ALGORITHM:
14547 		optval = bbr->rc_use_google;
14548 		break;
14549 	case TCP_BBR_TSLIMITS:
14550 		optval = bbr->rc_use_ts_limit;
14551 		break;
14552 	case TCP_BBR_IWINTSO:
14553 		optval = bbr->rc_init_win;
14554 		break;
14555 	case TCP_BBR_STARTUP_PG:
14556 		optval = bbr->r_ctl.rc_startup_pg;
14557 		break;
14558 	case TCP_BBR_DRAIN_PG:
14559 		optval = bbr->r_ctl.rc_drain_pg;
14560 		break;
14561 	case TCP_BBR_PROBE_RTT_INT:
14562 		optval = bbr->r_ctl.rc_probertt_int;
14563 		break;
14564 	case TCP_BBR_PROBE_RTT_LEN:
14565 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14566 		break;
14567 	case TCP_BBR_PROBE_RTT_GAIN:
14568 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14569 		break;
14570 	case TCP_BBR_STARTUP_LOSS_EXIT:
14571 		optval = bbr->rc_loss_exit;
14572 		break;
14573 	case TCP_BBR_USEDEL_RATE:
14574 		error = EINVAL;
14575 		break;
14576 	case TCP_BBR_MIN_RTO:
14577 		optval = bbr->r_ctl.rc_min_rto_ms;
14578 		break;
14579 	case TCP_BBR_MAX_RTO:
14580 		optval = bbr->rc_max_rto_sec;
14581 		break;
14582 	case TCP_RACK_PACE_MAX_SEG:
14583 		/* Max segments in a pace */
14584 		optval = bbr->r_ctl.rc_pace_max_segs;
14585 		break;
14586 	case TCP_RACK_MIN_TO:
14587 		/* Minimum time between rack t-o's in ms */
14588 		optval = bbr->r_ctl.rc_min_to;
14589 		break;
14590 	case TCP_RACK_REORD_THRESH:
14591 		/* RACK reorder threshold (shift amount) */
14592 		optval = bbr->r_ctl.rc_reorder_shift;
14593 		break;
14594 	case TCP_RACK_REORD_FADE:
14595 		/* Does reordering fade after ms time */
14596 		optval = bbr->r_ctl.rc_reorder_fade;
14597 		break;
14598 	case TCP_BBR_USE_RACK_CHEAT:
14599 		/* Do we use the rack cheat for rxt */
14600 		optval = bbr->bbr_use_rack_cheat;
14601 		break;
14602 	case TCP_BBR_FLOOR_MIN_TSO:
14603 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14604 		break;
14605 	case TCP_BBR_UTTER_MAX_TSO:
14606 		optval = bbr->r_ctl.bbr_utter_max;
14607 		break;
14608 	case TCP_BBR_SEND_IWND_IN_TSO:
14609 		/* Do we send TSO size segments initially */
14610 		optval = bbr->bbr_init_win_cheat;
14611 		break;
14612 	case TCP_BBR_EXTRA_STATE:
14613 		optval = bbr->rc_use_idle_restart;
14614 		break;
14615 	case TCP_RACK_TLP_THRESH:
14616 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14617 		optval = bbr->rc_tlp_threshold;
14618 		break;
14619 	case TCP_RACK_PKT_DELAY:
14620 		/* RACK added ms i.e. rack-rtt + reord + N */
14621 		optval = bbr->r_ctl.rc_pkt_delay;
14622 		break;
14623 	case TCP_BBR_RETRAN_WTSO:
14624 		optval = bbr->rc_resends_use_tso;
14625 		break;
14626 	case TCP_DATA_AFTER_CLOSE:
14627 		optval = bbr->rc_allow_data_af_clo;
14628 		break;
14629 	case TCP_DELACK:
14630 		optval = tp->t_delayed_ack;
14631 		break;
14632 	case TCP_BBR_HDWR_PACE:
14633 		optval = bbr->bbr_hdw_pace_ena;
14634 		break;
14635 	case TCP_BBR_POLICER_DETECT:
14636 		optval = bbr->r_use_policer;
14637 		break;
14638 	case TCP_BBR_TSTMP_RAISES:
14639 		optval = bbr->ts_can_raise;
14640 		break;
14641 	case TCP_BBR_TMR_PACE_OH:
14642 		optval = bbr->r_ctl.rc_incr_tmrs;
14643 		break;
14644 	case TCP_BBR_PACE_OH:
14645 		optval = 0;
14646 		if (bbr->r_ctl.rc_inc_tcp_oh)
14647 			optval |= BBR_INCL_TCP_OH;
14648 		if (bbr->r_ctl.rc_inc_ip_oh)
14649 			optval |= BBR_INCL_IP_OH;
14650 		if (bbr->r_ctl.rc_inc_enet_oh)
14651 			optval |= BBR_INCL_ENET_OH;
14652 		break;
14653 	default:
14654 		return (tcp_default_ctloutput(inp, sopt));
14655 		break;
14656 	}
14657 	INP_WUNLOCK(inp);
14658 	error = sooptcopyout(sopt, &optval, sizeof optval);
14659 	return (error);
14660 }
14661 
14662 /*
14663  * return 0 on success, error-num on failure
14664  */
14665 static int
14666 bbr_ctloutput(struct inpcb *inp, struct sockopt *sopt)
14667 {
14668 	if (sopt->sopt_dir == SOPT_SET) {
14669 		return (bbr_set_sockopt(inp, sopt));
14670 	} else if (sopt->sopt_dir == SOPT_GET) {
14671 		return (bbr_get_sockopt(inp, sopt));
14672 	} else {
14673 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14674 	}
14675 }
14676 
14677 static const char *bbr_stack_names[] = {
14678 	__XSTRING(STACKNAME),
14679 #ifdef STACKALIAS
14680 	__XSTRING(STACKALIAS),
14681 #endif
14682 };
14683 
14684 static bool bbr_mod_inited = false;
14685 
14686 static int
14687 tcp_addbbr(module_t mod, int32_t type, void *data)
14688 {
14689 	int32_t err = 0;
14690 	int num_stacks;
14691 
14692 	switch (type) {
14693 	case MOD_LOAD:
14694 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14695 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14696 		    sizeof(struct bbr_sendmap),
14697 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14698 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14699 		    sizeof(struct tcp_bbr),
14700 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14701 		sysctl_ctx_init(&bbr_sysctl_ctx);
14702 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14703 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14704 		    OID_AUTO,
14705 #ifdef STACKALIAS
14706 		    __XSTRING(STACKALIAS),
14707 #else
14708 		    __XSTRING(STACKNAME),
14709 #endif
14710 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14711 		    "");
14712 		if (bbr_sysctl_root == NULL) {
14713 			printf("Failed to add sysctl node\n");
14714 			err = EFAULT;
14715 			goto free_uma;
14716 		}
14717 		bbr_init_sysctls();
14718 		num_stacks = nitems(bbr_stack_names);
14719 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14720 		    bbr_stack_names, &num_stacks);
14721 		if (err) {
14722 			printf("Failed to register %s stack name for "
14723 			    "%s module\n", bbr_stack_names[num_stacks],
14724 			    __XSTRING(MODNAME));
14725 			sysctl_ctx_free(&bbr_sysctl_ctx);
14726 	free_uma:
14727 			uma_zdestroy(bbr_zone);
14728 			uma_zdestroy(bbr_pcb_zone);
14729 			bbr_counter_destroy();
14730 			printf("Failed to register " __XSTRING(MODNAME)
14731 			    " module err:%d\n", err);
14732 			return (err);
14733 		}
14734 		tcp_lro_reg_mbufq();
14735 		bbr_mod_inited = true;
14736 		printf(__XSTRING(MODNAME) " is now available\n");
14737 		break;
14738 	case MOD_QUIESCE:
14739 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14740 		break;
14741 	case MOD_UNLOAD:
14742 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14743 		if (err == EBUSY)
14744 			break;
14745 		if (bbr_mod_inited) {
14746 			uma_zdestroy(bbr_zone);
14747 			uma_zdestroy(bbr_pcb_zone);
14748 			sysctl_ctx_free(&bbr_sysctl_ctx);
14749 			bbr_counter_destroy();
14750 			printf(__XSTRING(MODNAME)
14751 			    " is now no longer available\n");
14752 			bbr_mod_inited = false;
14753 		}
14754 		tcp_lro_dereg_mbufq();
14755 		err = 0;
14756 		break;
14757 	default:
14758 		return (EOPNOTSUPP);
14759 	}
14760 	return (err);
14761 }
14762 
14763 static moduledata_t tcp_bbr = {
14764 	.name = __XSTRING(MODNAME),
14765 	    .evhand = tcp_addbbr,
14766 	    .priv = 0
14767 };
14768 
14769 MODULE_VERSION(MODNAME, 1);
14770 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14771 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14772