xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision 1f1e2261e341e6ca6862f82261066ef1705f0a7a)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35 
36 #include "opt_inet.h"
37 #include "opt_inet6.h"
38 #include "opt_ipsec.h"
39 #include "opt_tcpdebug.h"
40 #include "opt_ratelimit.h"
41 #include <sys/param.h>
42 #include <sys/arb.h>
43 #include <sys/module.h>
44 #include <sys/kernel.h>
45 #include <sys/libkern.h>
46 #ifdef TCP_HHOOK
47 #include <sys/hhook.h>
48 #endif
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/proc.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/sysctl.h>
55 #include <sys/systm.h>
56 #ifdef STATS
57 #include <sys/qmath.h>
58 #include <sys/tree.h>
59 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
60 #endif
61 #include <sys/refcount.h>
62 #include <sys/queue.h>
63 #include <sys/eventhandler.h>
64 #include <sys/smp.h>
65 #include <sys/kthread.h>
66 #include <sys/lock.h>
67 #include <sys/mutex.h>
68 #include <sys/tim_filter.h>
69 #include <sys/time.h>
70 #include <sys/protosw.h>
71 #include <vm/uma.h>
72 #include <sys/kern_prefetch.h>
73 
74 #include <net/route.h>
75 #include <net/route/nhop.h>
76 #include <net/vnet.h>
77 
78 #define TCPSTATES		/* for logging */
79 
80 #include <netinet/in.h>
81 #include <netinet/in_kdtrace.h>
82 #include <netinet/in_pcb.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
85 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
86 #include <netinet/ip_var.h>
87 #include <netinet/ip6.h>
88 #include <netinet6/in6_pcb.h>
89 #include <netinet6/ip6_var.h>
90 #define	TCPOUTFLAGS
91 #include <netinet/tcp.h>
92 #include <netinet/tcp_fsm.h>
93 #include <netinet/tcp_seq.h>
94 #include <netinet/tcp_timer.h>
95 #include <netinet/tcp_var.h>
96 #include <netinet/tcpip.h>
97 #include <netinet/tcp_hpts.h>
98 #include <netinet/cc/cc.h>
99 #include <netinet/tcp_log_buf.h>
100 #include <netinet/tcp_ratelimit.h>
101 #include <netinet/tcp_lro.h>
102 #ifdef TCPDEBUG
103 #include <netinet/tcp_debug.h>
104 #endif				/* TCPDEBUG */
105 #ifdef TCP_OFFLOAD
106 #include <netinet/tcp_offload.h>
107 #endif
108 #ifdef INET6
109 #include <netinet6/tcp6_var.h>
110 #endif
111 #include <netinet/tcp_fastopen.h>
112 
113 #include <netipsec/ipsec_support.h>
114 #include <net/if.h>
115 #include <net/if_var.h>
116 #include <net/ethernet.h>
117 
118 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
119 #include <netipsec/ipsec.h>
120 #include <netipsec/ipsec6.h>
121 #endif				/* IPSEC */
122 
123 #include <netinet/udp.h>
124 #include <netinet/udp_var.h>
125 #include <machine/in_cksum.h>
126 
127 #ifdef MAC
128 #include <security/mac/mac_framework.h>
129 #endif
130 
131 #include "sack_filter.h"
132 #include "tcp_bbr.h"
133 #include "rack_bbr_common.h"
134 uma_zone_t bbr_zone;
135 uma_zone_t bbr_pcb_zone;
136 
137 struct sysctl_ctx_list bbr_sysctl_ctx;
138 struct sysctl_oid *bbr_sysctl_root;
139 
140 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
141 	(tv) = (value); \
142 	if ((u_long)(tv) < (u_long)(tvmin)) \
143 		(tv) = (tvmin); \
144 	if ((u_long)(tv) > (u_long)(tvmax)) \
145 		(tv) = (tvmax); \
146 } while(0)
147 
148 /*#define BBR_INVARIANT 1*/
149 
150 /*
151  * initial window
152  */
153 static uint32_t bbr_def_init_win = 10;
154 static int32_t bbr_persist_min = 250000;	/* 250ms */
155 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
156 static int32_t bbr_cwnd_may_shrink = 0;
157 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
158 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
159 static int32_t bbr_hardware_pacing_limit = 8000;
160 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
161 static int32_t bbr_no_retran = 0;
162 
163 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
164 static int32_t bbr_max_net_error_cnt = 10;
165 /* Should the following be dynamic too -- loss wise */
166 static int32_t bbr_rtt_gain_thresh = 0;
167 /* Measurement controls */
168 static int32_t bbr_use_google_algo = 1;
169 static int32_t bbr_ts_limiting = 1;
170 static int32_t bbr_ts_can_raise = 0;
171 static int32_t bbr_do_red = 600;
172 static int32_t bbr_red_scale = 20000;
173 static int32_t bbr_red_mul = 1;
174 static int32_t bbr_red_div = 2;
175 static int32_t bbr_red_growth_restrict = 1;
176 static int32_t  bbr_target_is_bbunit = 0;
177 static int32_t bbr_drop_limit = 0;
178 /*
179  * How much gain do we need to see to
180  * stay in startup?
181  */
182 static int32_t bbr_marks_rxt_sack_passed = 0;
183 static int32_t bbr_start_exit = 25;
184 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
185 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
186 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
187 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
188 					 * if we go back ever to where the pacer
189 					 * has priority over timers.
190 					 */
191 static int32_t bbr_policer_call_from_rack_to = 0;
192 static int32_t bbr_policer_detection_enabled = 1;
193 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
194 						 * measurements before we are
195 						 * "good" note that 2 == 1.
196 						 * This is because we use a >
197 						 * comparison. This means if
198 						 * min_measure was 0, it takes
199 						 * num-measures > min(0) and
200 						 * you get 1 measurement and
201 						 * you are good. Set to 1, you
202 						 * have to have two
203 						 * measurements (this is done
204 						 * to prevent it from being ok
205 						 * to have no measurements). */
206 static int32_t bbr_no_pacing_until = 4;
207 
208 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
209 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
210 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
211 
212 static int32_t bbr_target_cwnd_mult_limit = 8;
213 /*
214  * bbr_cwnd_min_val is the number of
215  * segments we hold to in the RTT probe
216  * state typically 4.
217  */
218 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
219 
220 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
221 
222 static int32_t bbr_gain_to_target = 1;
223 static int32_t bbr_gain_gets_extra_too = 1;
224 /*
225  * bbr_high_gain is the 2/ln(2) value we need
226  * to double the sending rate in startup. This
227  * is used for both cwnd and hptsi gain's.
228  */
229 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
230 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
231 static int32_t bbr_use_lower_gain_in_startup = 1;
232 
233 /* thresholds for reduction on drain in sub-states/drain */
234 static int32_t bbr_drain_rtt = BBR_SRTT;
235 static int32_t bbr_drain_floor = 88;
236 static int32_t google_allow_early_out = 1;
237 static int32_t google_consider_lost = 1;
238 static int32_t bbr_drain_drop_mul = 4;
239 static int32_t bbr_drain_drop_div = 5;
240 static int32_t bbr_rand_ot = 50;
241 static int32_t bbr_can_force_probertt = 0;
242 static int32_t bbr_can_adjust_probertt = 1;
243 static int32_t bbr_probertt_sets_rtt = 0;
244 static int32_t bbr_can_use_ts_for_rtt = 1;
245 static int32_t bbr_is_ratio = 0;
246 static int32_t bbr_sub_drain_app_limit = 1;
247 static int32_t bbr_prtt_slam_cwnd = 1;
248 static int32_t bbr_sub_drain_slam_cwnd = 1;
249 static int32_t bbr_slam_cwnd_in_main_drain = 1;
250 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
251 					 * hold */
252 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
253 /*
254  * bbr_drain_gain is the reverse of the high_gain
255  * designed to drain back out the standing queue
256  * that is formed in startup by causing a larger
257  * hptsi gain and thus drainging the packets
258  * in flight.
259  */
260 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
261 static int32_t bbr_rttprobe_gain = 192;
262 
263 /*
264  * The cwnd_gain is the default cwnd gain applied when
265  * calculating a target cwnd. Note that the cwnd is
266  * a secondary factor in the way BBR works (see the
267  * paper and think about it, it will take some time).
268  * Basically the hptsi_gain spreads the packets out
269  * so you never get more than BDP to the peer even
270  * if the cwnd is high. In our implemenation that
271  * means in non-recovery/retransmission scenarios
272  * cwnd will never be reached by the flight-size.
273  */
274 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
275 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
276 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
277 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
278 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
279 static int32_t bbr_ignore_data_after_close = 1;
280 static int16_t bbr_hptsi_gain[] = {
281 	(BBR_UNIT *5 / 4),
282 	(BBR_UNIT * 3 / 4),
283 	BBR_UNIT,
284 	BBR_UNIT,
285 	BBR_UNIT,
286 	BBR_UNIT,
287 	BBR_UNIT,
288 	BBR_UNIT
289 };
290 int32_t bbr_use_rack_resend_cheat = 1;
291 int32_t bbr_sends_full_iwnd = 1;
292 
293 #define BBR_HPTSI_GAIN_MAX 8
294 /*
295  * The BBR module incorporates a number of
296  * TCP ideas that have been put out into the IETF
297  * over the last few years:
298  * - Yuchung Cheng's RACK TCP (for which its named) that
299  *    will stop us using the number of dup acks and instead
300  *    use time as the gage of when we retransmit.
301  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
302  *    of Dukkipati et.al.
303  * - Van Jacobson's et.al BBR.
304  *
305  * RACK depends on SACK, so if an endpoint arrives that
306  * cannot do SACK the state machine below will shuttle the
307  * connection back to using the "default" TCP stack that is
308  * in FreeBSD.
309  *
310  * To implement BBR and RACK the original TCP stack was first decomposed
311  * into a functional state machine with individual states
312  * for each of the possible TCP connection states. The do_segment
313  * functions role in life is to mandate the connection supports SACK
314  * initially and then assure that the RACK state matches the conenction
315  * state before calling the states do_segment function. Data processing
316  * of inbound segments also now happens in the hpts_do_segment in general
317  * with only one exception. This is so we can keep the connection on
318  * a single CPU.
319  *
320  * Each state is simplified due to the fact that the original do_segment
321  * has been decomposed and we *know* what state we are in (no
322  * switches on the state) and all tests for SACK are gone. This
323  * greatly simplifies what each state does.
324  *
325  * TCP output is also over-written with a new version since it
326  * must maintain the new rack scoreboard and has had hptsi
327  * integrated as a requirment. Still todo is to eliminate the
328  * use of the callout_() system and use the hpts for all
329  * timers as well.
330  */
331 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
332 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
333 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
334 						 * free list */
335 static int32_t bbr_tlp_thresh = 1;
336 static int32_t bbr_reorder_thresh = 2;
337 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
338 						 * 60,000,000 - 60 seconds */
339 static int32_t bbr_pkt_delay = 1000;
340 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
341 static int32_t bbr_incr_timers = 1;
342 
343 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
344 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
345 static int32_t bbr_exit_startup_at_loss = 1;
346 
347 /*
348  * bbr_lt_bw_ratio is 1/8th
349  * bbr_lt_bw_diff is  < 4 Kbit/sec
350  */
351 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
352 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
353 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
354 						 * the lt_bw for */
355 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
356 						 * lt_bw */
357 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
358 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
359 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
360 
361 static int32_t bbr_verbose_logging = 0;
362 /*
363  * Currently regular tcp has a rto_min of 30ms
364  * the backoff goes 12 times so that ends up
365  * being a total of 122.850 seconds before a
366  * connection is killed.
367  */
368 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
369 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
370 
371 /****************************************************/
372 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
373 /****************************************************/
374 /* What amount is our formula using to get TSO size */
375 static int32_t bbr_hptsi_per_second = 1000;
376 
377 /*
378  * For hptsi under bbr_cross_over connections what is delay
379  * target 7ms (in usec) combined with a seg_max of 2
380  * gets us close to identical google behavior in
381  * TSO size selection (possibly more 1MSS sends).
382  */
383 static int32_t bbr_hptsi_segments_delay_tar = 7000;
384 
385 /* Does pacing delay include overhead's in its time calculations? */
386 static int32_t bbr_include_enet_oh = 0;
387 static int32_t bbr_include_ip_oh = 1;
388 static int32_t bbr_include_tcp_oh = 1;
389 static int32_t bbr_google_discount = 10;
390 
391 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
392 static int32_t bbr_state_is_pkt_epoch = 0;
393 static int32_t bbr_state_drain_2_tar = 1;
394 /* What is the max the 0 - bbr_cross_over MBPS TSO target
395  * can reach using our delay target. Note that this
396  * value becomes the floor for the cross over
397  * algorithm.
398  */
399 static int32_t bbr_hptsi_segments_max = 2;
400 static int32_t bbr_hptsi_segments_floor = 1;
401 static int32_t bbr_hptsi_utter_max = 0;
402 
403 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
404 static int32_t bbr_hptsi_bytes_min = 1460;
405 static int32_t bbr_all_get_min = 0;
406 
407 /* Cross over point from algo-a to algo-b */
408 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
409 
410 /* Do we deal with our restart state? */
411 static int32_t bbr_uses_idle_restart = 0;
412 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
413 
414 /* Do we allow hardware pacing? */
415 static int32_t bbr_allow_hdwr_pacing = 0;
416 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
417 static int32_t bbr_hdwr_pace_floor = 1;
418 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
419 
420 /****************************************************/
421 static int32_t bbr_resends_use_tso = 0;
422 static int32_t bbr_tlp_max_resend = 2;
423 static int32_t bbr_sack_block_limit = 128;
424 
425 #define  BBR_MAX_STAT 19
426 counter_u64_t bbr_state_time[BBR_MAX_STAT];
427 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
428 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
429 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
430 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
431 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
432 counter_u64_t bbr_flows_whdwr_pacing;
433 counter_u64_t bbr_flows_nohdwr_pacing;
434 
435 counter_u64_t bbr_nohdwr_pacing_enobuf;
436 counter_u64_t bbr_hdwr_pacing_enobuf;
437 
438 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
439 
440 /*
441  * Static defintions we need for forward declarations.
442  */
443 static uint32_t
444 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
445 		      uint32_t useconds_time, uint64_t bw);
446 static uint32_t
447 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
448 static void
449 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
450 static void
451 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
452 static void
453 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
454 		    int dolog);
455 static uint32_t
456 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
457 static void
458 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
459 		 int32_t pkt_epoch, uint32_t losses);
460 static uint32_t
461 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts,
462 		     struct bbr_sendmap *rsm);
463 static uint32_t
464 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
465 static uint32_t
466 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
467 		    struct bbr_sendmap *rsm, uint32_t srtt, uint32_t cts);
468 static void
469 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
470 		 int32_t line);
471 static void
472 bbr_set_state_target(struct tcp_bbr *bbr, int line);
473 static void
474 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
475 static void
476 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick,
477 		       int event, int line);
478 static void
479 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
480 static void
481 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
482 static void
483 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
484 		    uint32_t rtt, uint32_t line, uint8_t is_start,
485 		    uint16_t set);
486 static struct bbr_sendmap *
487 bbr_find_lowest_rsm(struct tcp_bbr *bbr);
488 static __inline uint32_t
489 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
490 static void
491 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot,
492 		 uint8_t which);
493 static void
494 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts,
495 		  uint32_t time_since_sent, uint32_t srtt,
496 		  uint32_t thresh, uint32_t to);
497 static void
498 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
499 static void
500 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
501 		    uint32_t del_by, uint32_t cts, uint32_t sloton,
502 		    uint32_t prev_delay);
503 static void
504 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
505 		  int32_t line);
506 static void
507 bbr_stop_all_timers(struct tcpcb *tp);
508 static void
509 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
510 static void
511 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
512 static void
513 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
514 static void
515 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
516 			  uint32_t cts, uint32_t usecs, uint64_t bw,
517 			  uint32_t override, int mod);
518 static int
519 bbr_ctloutput(struct inpcb *inp, struct sockopt *sopt);
520 
521 static inline uint8_t
522 bbr_state_val(struct tcp_bbr *bbr)
523 {
524 	return(bbr->rc_bbr_substate);
525 }
526 
527 static inline uint32_t
528 get_min_cwnd(struct tcp_bbr *bbr)
529 {
530 	int mss;
531 
532 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
533 		  bbr->r_ctl.rc_pace_max_segs);
534 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
535 		return (bbr_cwnd_min_val_hs * mss);
536 	else
537 		return (bbr_cwnd_min_val * mss);
538 }
539 
540 static uint32_t
541 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
542 {
543 	uint64_t srtt, var;
544 	uint64_t ret_val;
545 
546 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
547 	if (tp->t_srtt == 0) {
548 		srtt = (uint64_t)BBR_INITIAL_RTO;
549 		var = 0;
550 	} else {
551 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
552 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
553 	}
554 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
555 	    bbr_persist_min, bbr_persist_max);
556 	return ((uint32_t)ret_val);
557 }
558 
559 static uint32_t
560 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
561 {
562 	/*
563 	 * Start the FR timer, we do this based on getting the first one in
564 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
565 	 * events we need to stop the running timer (if its running) before
566 	 * starting the new one.
567 	 */
568 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
569 	int32_t idx;
570 	int32_t is_tlp_timer = 0;
571 	struct bbr_sendmap *rsm;
572 
573 	if (bbr->rc_all_timers_stopped) {
574 		/* All timers have been stopped none are to run */
575 		return (0);
576 	}
577 	if (bbr->rc_in_persist) {
578 		/* We can't start any timer in persists */
579 		return (bbr_get_persists_timer_val(tp, bbr));
580 	}
581 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
582 	if ((rsm == NULL) ||
583 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
584 	    (tp->t_state < TCPS_ESTABLISHED)) {
585 		/* Nothing on the send map */
586 activate_rxt:
587 		if (SEQ_LT(tp->snd_una, tp->snd_max) || sbavail(&(tp->t_inpcb->inp_socket->so_snd))) {
588 			uint64_t tov;
589 
590 			time_since_sent = 0;
591 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
592 			if (rsm) {
593 				idx = rsm->r_rtr_cnt - 1;
594 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
595 					tstmp_touse = rsm->r_tim_lastsent[idx];
596 				else
597 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
598 				if (TSTMP_GT(tstmp_touse, cts))
599 				    time_since_sent = cts - tstmp_touse;
600 			}
601 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
602 			if (tp->t_srtt == 0)
603 				tov = BBR_INITIAL_RTO;
604 			else
605 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
606 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
607 			if (tp->t_rxtshift)
608 				tov *= tcp_backoff[tp->t_rxtshift];
609 			if (tov > time_since_sent)
610 				tov -= time_since_sent;
611 			else
612 				tov = bbr->r_ctl.rc_min_to;
613 			TCPT_RANGESET_NOSLOP(to, tov,
614 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
615 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
616 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
617 			return (to);
618 		}
619 		return (0);
620 	}
621 	if (rsm->r_flags & BBR_ACKED) {
622 		rsm = bbr_find_lowest_rsm(bbr);
623 		if (rsm == NULL) {
624 			/* No lowest? */
625 			goto activate_rxt;
626 		}
627 	}
628 	/* Convert from ms to usecs */
629 	if (rsm->r_flags & BBR_SACK_PASSED) {
630 		if ((tp->t_flags & TF_SENTFIN) &&
631 		    ((tp->snd_max - tp->snd_una) == 1) &&
632 		    (rsm->r_flags & BBR_HAS_FIN)) {
633 			/*
634 			 * We don't start a bbr rack timer if all we have is
635 			 * a FIN outstanding.
636 			 */
637 			goto activate_rxt;
638 		}
639 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
640 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
641 		idx = rsm->r_rtr_cnt - 1;
642 		exp = rsm->r_tim_lastsent[idx] + thresh;
643 		if (SEQ_GEQ(exp, cts)) {
644 			to = exp - cts;
645 			if (to < bbr->r_ctl.rc_min_to) {
646 				to = bbr->r_ctl.rc_min_to;
647 			}
648 		} else {
649 			to = bbr->r_ctl.rc_min_to;
650 		}
651 	} else {
652 		/* Ok we need to do a TLP not RACK */
653 		if (bbr->rc_tlp_in_progress != 0) {
654 			/*
655 			 * The previous send was a TLP.
656 			 */
657 			goto activate_rxt;
658 		}
659 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
660 		if (rsm == NULL) {
661 			/* We found no rsm to TLP with. */
662 			goto activate_rxt;
663 		}
664 		if (rsm->r_flags & BBR_HAS_FIN) {
665 			/* If its a FIN we don't do TLP */
666 			rsm = NULL;
667 			goto activate_rxt;
668 		}
669 		time_since_sent = 0;
670 		idx = rsm->r_rtr_cnt - 1;
671 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
672 			tstmp_touse = rsm->r_tim_lastsent[idx];
673 		else
674 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
675 		if (TSTMP_GT(tstmp_touse, cts))
676 		    time_since_sent = cts - tstmp_touse;
677 		is_tlp_timer = 1;
678 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
679 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
680 		if (thresh > time_since_sent)
681 			to = thresh - time_since_sent;
682 		else
683 			to = bbr->r_ctl.rc_min_to;
684 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
685 			/*
686 			 * If the TLP time works out to larger than the max
687 			 * RTO lets not do TLP.. just RTO.
688 			 */
689 			goto activate_rxt;
690 		}
691 		if ((bbr->rc_tlp_rtx_out == 1) &&
692 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
693 			/*
694 			 * Second retransmit of the same TLP
695 			 * lets not.
696 			 */
697 			bbr->rc_tlp_rtx_out = 0;
698 			goto activate_rxt;
699 		}
700 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
701 			/*
702 			 * The tail is no longer the last one I did a probe
703 			 * on
704 			 */
705 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
706 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
707 		}
708 	}
709 	if (is_tlp_timer == 0) {
710 		BBR_STAT_INC(bbr_to_arm_rack);
711 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
712 	} else {
713 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
714 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
715 			/*
716 			 * We have exceeded how many times we can retran the
717 			 * current TLP timer, switch to the RTO timer.
718 			 */
719 			goto activate_rxt;
720 		} else {
721 			BBR_STAT_INC(bbr_to_arm_tlp);
722 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
723 		}
724 	}
725 	return (to);
726 }
727 
728 static inline int32_t
729 bbr_minseg(struct tcp_bbr *bbr)
730 {
731 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
732 }
733 
734 static void
735 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
736 {
737 	struct inpcb *inp;
738 	struct hpts_diag diag;
739 	uint32_t delayed_ack = 0;
740 	uint32_t left = 0;
741 	uint32_t hpts_timeout;
742 	uint8_t stopped;
743 	int32_t delay_calc = 0;
744 	uint32_t prev_delay = 0;
745 
746 	inp = tp->t_inpcb;
747 	if (tcp_in_hpts(inp)) {
748 		/* A previous call is already set up */
749 		return;
750 	}
751 	if ((tp->t_state == TCPS_CLOSED) ||
752 	    (tp->t_state == TCPS_LISTEN)) {
753 		return;
754 	}
755 	stopped = bbr->rc_tmr_stopped;
756 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
757 		left = bbr->r_ctl.rc_timer_exp - cts;
758 	}
759 	bbr->r_ctl.rc_hpts_flags = 0;
760 	bbr->r_ctl.rc_timer_exp = 0;
761 	prev_delay = bbr->r_ctl.rc_last_delay_val;
762 	if (bbr->r_ctl.rc_last_delay_val &&
763 	    (slot == 0)) {
764 		/*
765 		 * If a previous pacer delay was in place we
766 		 * are not coming from the output side (where
767 		 * we calculate a delay, more likely a timer).
768 		 */
769 		slot = bbr->r_ctl.rc_last_delay_val;
770 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
771 			/* Compensate for time passed  */
772 			delay_calc = cts - bbr->rc_pacer_started;
773 			if (delay_calc <= slot)
774 				slot -= delay_calc;
775 		}
776 	}
777 	/* Do we have early to make up for by pushing out the pacing time? */
778 	if (bbr->r_agg_early_set) {
779 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
780 		slot += bbr->r_ctl.rc_agg_early;
781 		bbr->r_ctl.rc_agg_early = 0;
782 		bbr->r_agg_early_set = 0;
783 	}
784 	/* Are we running a total debt that needs to be compensated for? */
785 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
786 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
787 			/* We nuke the delay */
788 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
789 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
790 		} else {
791 			/* We nuke some of the delay, put in a minimal 100usecs  */
792 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
793 			bbr->r_ctl.rc_last_delay_val = slot = 100;
794 		}
795 	}
796 	bbr->r_ctl.rc_last_delay_val = slot;
797 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
798 	if (tp->t_flags & TF_DELACK) {
799 		if (bbr->rc_in_persist == 0) {
800 			delayed_ack = bbr_delack_time;
801 		} else {
802 			/*
803 			 * We are in persists and have
804 			 * gotten a new data element.
805 			 */
806 			if (hpts_timeout > bbr_delack_time) {
807 				/*
808 				 * Lets make the persists timer (which acks)
809 				 * be the smaller of hpts_timeout and bbr_delack_time.
810 				 */
811 				hpts_timeout = bbr_delack_time;
812 			}
813 		}
814 	}
815 	if (delayed_ack &&
816 	    ((hpts_timeout == 0) ||
817 	     (delayed_ack < hpts_timeout))) {
818 		/* We need a Delayed ack timer */
819 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
820 		hpts_timeout = delayed_ack;
821 	}
822 	if (slot) {
823 		/* Mark that we have a pacing timer up */
824 		BBR_STAT_INC(bbr_paced_segments);
825 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
826 	}
827 	/*
828 	 * If no timers are going to run and we will fall off thfe hptsi
829 	 * wheel, we resort to a keep-alive timer if its configured.
830 	 */
831 	if ((hpts_timeout == 0) &&
832 	    (slot == 0)) {
833 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
834 		    (tp->t_state <= TCPS_CLOSING)) {
835 			/*
836 			 * Ok we have no timer (persists, rack, tlp, rxt  or
837 			 * del-ack), we don't have segments being paced. So
838 			 * all that is left is the keepalive timer.
839 			 */
840 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
841 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
842 			} else {
843 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
844 			}
845 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
846 		}
847 	}
848 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
849 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
850 		/*
851 		 * RACK, TLP, persists and RXT timers all are restartable
852 		 * based on actions input .. i.e we received a packet (ack
853 		 * or sack) and that changes things (rw, or snd_una etc).
854 		 * Thus we can restart them with a new value. For
855 		 * keep-alive, delayed_ack we keep track of what was left
856 		 * and restart the timer with a smaller value.
857 		 */
858 		if (left < hpts_timeout)
859 			hpts_timeout = left;
860 	}
861 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
862 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
863 		/*
864 		 * If configured to do so, and the timer is either
865 		 * the TLP or RXT timer, we need to increase the timeout
866 		 * by the pacing time. Consider the bottleneck at my
867 		 * machine as an example, we are sending something
868 		 * to start a TLP on. The last packet won't be emitted
869 		 * fully until the pacing time (the bottleneck will hold
870 		 * the data in place). Once the packet is emitted that
871 		 * is when we want to start waiting for the TLP. This
872 		 * is most evident with hardware pacing (where the nic
873 		 * is holding the packet(s) before emitting). But it
874 		 * can also show up in the network so we do it for all
875 		 * cases. Technically we would take off one packet from
876 		 * this extra delay but this is easier and being more
877 		 * conservative is probably better.
878 		 */
879 		hpts_timeout += slot;
880 	}
881 	if (hpts_timeout) {
882 		/*
883 		 * Hack alert for now we can't time-out over 2147 seconds (a
884 		 * bit more than 35min)
885 		 */
886 		if (hpts_timeout > 0x7ffffffe)
887 			hpts_timeout = 0x7ffffffe;
888 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
889 	} else
890 		bbr->r_ctl.rc_timer_exp = 0;
891 	if ((slot) &&
892 	    (bbr->rc_use_google ||
893 	     bbr->output_error_seen ||
894 	     (slot <= hpts_timeout))  ) {
895 		/*
896 		 * Tell LRO that it can queue packets while
897 		 * we pace.
898 		 */
899 		bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
900 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
901 		    (bbr->rc_cwnd_limited == 0)) {
902 			/*
903 			 * If we are not cwnd limited and we
904 			 * are running a rack timer we put on
905 			 * the do not disturbe even for sack.
906 			 */
907 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
908 		} else
909 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
910 		bbr->rc_pacer_started = cts;
911 
912 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(slot),
913 					   __LINE__, &diag);
914 		bbr->rc_timer_first = 0;
915 		bbr->bbr_timer_src = frm;
916 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
917 		bbr_log_hpts_diag(bbr, cts, &diag);
918 	} else if (hpts_timeout) {
919 		(void)tcp_hpts_insert_diag(tp->t_inpcb, HPTS_USEC_TO_SLOTS(hpts_timeout),
920 					   __LINE__, &diag);
921 		/*
922 		 * We add the flag here as well if the slot is set,
923 		 * since hpts will call in to clear the queue first before
924 		 * calling the output routine (which does our timers).
925 		 * We don't want to set the flag if its just a timer
926 		 * else the arrival of data might (that causes us
927 		 * to send more) might get delayed. Imagine being
928 		 * on a keep-alive timer and a request comes in for
929 		 * more data.
930 		 */
931 		if (slot)
932 			bbr->rc_pacer_started = cts;
933 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
934 		    (bbr->rc_cwnd_limited == 0)) {
935 			/*
936 			 * For a rack timer, don't wake us even
937 			 * if a sack arrives as long as we are
938 			 * not cwnd limited.
939 			 */
940 			bbr->rc_inp->inp_flags2 |= INP_MBUF_QUEUE_READY;
941 			inp->inp_flags2 |= INP_DONT_SACK_QUEUE;
942 		} else {
943 			/* All other timers wake us up */
944 			bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
945 			inp->inp_flags2 &= ~INP_DONT_SACK_QUEUE;
946 		}
947 		bbr->bbr_timer_src = frm;
948 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
949 		bbr_log_hpts_diag(bbr, cts, &diag);
950 		bbr->rc_timer_first = 1;
951 	}
952 	bbr->rc_tmr_stopped = 0;
953 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
954 }
955 
956 static void
957 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
958 {
959 	/*
960 	 * We received an ack, and then did not call send or were bounced
961 	 * out due to the hpts was running. Now a timer is up as well, is it
962 	 * the right timer?
963 	 */
964 	struct inpcb *inp;
965 	struct bbr_sendmap *rsm;
966 	uint32_t hpts_timeout;
967 	int tmr_up;
968 
969 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
970 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
971 		return;
972 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
973 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
974 	    (tmr_up == PACE_TMR_RXT)) {
975 		/* Should be an RXT */
976 		return;
977 	}
978 	inp = bbr->rc_inp;
979 	if (rsm == NULL) {
980 		/* Nothing outstanding? */
981 		if (tp->t_flags & TF_DELACK) {
982 			if (tmr_up == PACE_TMR_DELACK)
983 				/*
984 				 * We are supposed to have delayed ack up
985 				 * and we do
986 				 */
987 				return;
988 		} else if (sbavail(&inp->inp_socket->so_snd) &&
989 		    (tmr_up == PACE_TMR_RXT)) {
990 			/*
991 			 * if we hit enobufs then we would expect the
992 			 * possibility of nothing outstanding and the RXT up
993 			 * (and the hptsi timer).
994 			 */
995 			return;
996 		} else if (((V_tcp_always_keepalive ||
997 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
998 			    (tp->t_state <= TCPS_CLOSING)) &&
999 			    (tmr_up == PACE_TMR_KEEP) &&
1000 		    (tp->snd_max == tp->snd_una)) {
1001 			/* We should have keep alive up and we do */
1002 			return;
1003 		}
1004 	}
1005 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
1006 		if ((tp->t_flags & TF_SENTFIN) &&
1007 		    ((tp->snd_max - tp->snd_una) == 1) &&
1008 		    (rsm->r_flags & BBR_HAS_FIN)) {
1009 			/* needs to be a RXT */
1010 			if (tmr_up == PACE_TMR_RXT)
1011 				return;
1012 			else
1013 				goto wrong_timer;
1014 		} else if (tmr_up == PACE_TMR_RACK)
1015 			return;
1016 		else
1017 			goto wrong_timer;
1018 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1019 		/* Rack timer has priority if we have data out */
1020 		return;
1021 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1022 		    ((tmr_up == PACE_TMR_TLP) ||
1023 	    (tmr_up == PACE_TMR_RXT))) {
1024 		/*
1025 		 * Either a TLP or RXT is fine if no sack-passed is in place
1026 		 * and data is outstanding.
1027 		 */
1028 		return;
1029 	} else if (tmr_up == PACE_TMR_DELACK) {
1030 		/*
1031 		 * If the delayed ack was going to go off before the
1032 		 * rtx/tlp/rack timer were going to expire, then that would
1033 		 * be the timer in control. Note we don't check the time
1034 		 * here trusting the code is correct.
1035 		 */
1036 		return;
1037 	}
1038 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1039 	    ((tmr_up == PACE_TMR_RXT) ||
1040 	     (tmr_up == PACE_TMR_TLP) ||
1041 	     (tmr_up == PACE_TMR_RACK))) {
1042 		/*
1043 		 * We have outstanding data and
1044 		 * we *do* have a RACK, TLP or RXT
1045 		 * timer running. We won't restart
1046 		 * anything here since thats probably ok we
1047 		 * will get called with some timer here shortly.
1048 		 */
1049 		return;
1050 	}
1051 	/*
1052 	 * Ok the timer originally started is not what we want now. We will
1053 	 * force the hpts to be stopped if any, and restart with the slot
1054 	 * set to what was in the saved slot.
1055 	 */
1056 wrong_timer:
1057 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1058 		if (tcp_in_hpts(inp))
1059 			tcp_hpts_remove(inp);
1060 		bbr_timer_cancel(bbr, __LINE__, cts);
1061 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1062 		    0);
1063 	} else {
1064 		/*
1065 		 * Output is hptsi so we just need to switch the type of
1066 		 * timer. We don't bother with keep-alive, since when we
1067 		 * jump through the output, it will start the keep-alive if
1068 		 * nothing is sent.
1069 		 *
1070 		 * We only need a delayed-ack added and or the hpts_timeout.
1071 		 */
1072 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1073 		if (tp->t_flags & TF_DELACK) {
1074 			if (hpts_timeout == 0) {
1075 				hpts_timeout = bbr_delack_time;
1076 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1077 			}
1078 			else if (hpts_timeout > bbr_delack_time) {
1079 				hpts_timeout = bbr_delack_time;
1080 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1081 			}
1082 		}
1083 		if (hpts_timeout) {
1084 			if (hpts_timeout > 0x7ffffffe)
1085 				hpts_timeout = 0x7ffffffe;
1086 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1087 		}
1088 	}
1089 }
1090 
1091 int32_t bbr_clear_lost = 0;
1092 
1093 /*
1094  * Considers the two time values now (cts) and earlier.
1095  * If cts is smaller than earlier, we could have
1096  * had a sequence wrap (our counter wraps every
1097  * 70 min or so) or it could be just clock skew
1098  * getting us two different time values. Clock skew
1099  * will show up within 10ms or so. So in such
1100  * a case (where cts is behind earlier time by
1101  * less than 10ms) we return 0. Otherwise we
1102  * return the true difference between them.
1103  */
1104 static inline uint32_t
1105 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1106 	/*
1107 	 * Given two timestamps, the current time stamp cts, and some other
1108 	 * time-stamp taken in theory earlier return the difference. The
1109 	 * trick is here sometimes locking will get the other timestamp
1110 	 * after the cts. If this occurs we need to return 0.
1111 	 */
1112 	if (TSTMP_GEQ(cts, earlier_time))
1113 		return (cts - earlier_time);
1114 	/*
1115 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1116 	 * If its more than 10ms difference then we had a time wrap. Else
1117 	 * its just the normal locking foo. I wonder if we should not go to
1118 	 * 64bit TS and get rid of this issue.
1119 	 */
1120 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1121 		return (0);
1122 	/*
1123 	 * Ok the time must have wrapped. So we need to answer a large
1124 	 * amount of time, which the normal subtraction should do.
1125 	 */
1126 	return (cts - earlier_time);
1127 }
1128 
1129 static int
1130 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1131 {
1132 	uint32_t stat;
1133 	int32_t error;
1134 
1135 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1136 	if (error || req->newptr == NULL)
1137 		return error;
1138 
1139 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1140 	if (error)
1141 		return (error);
1142 	if (stat == 1) {
1143 #ifdef BBR_INVARIANTS
1144 		printf("Clearing BBR lost counters\n");
1145 #endif
1146 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1147 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1148 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1149 	} else if (stat == 2) {
1150 #ifdef BBR_INVARIANTS
1151 		printf("Clearing BBR option counters\n");
1152 #endif
1153 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1154 	} else if (stat == 3) {
1155 #ifdef BBR_INVARIANTS
1156 		printf("Clearing BBR stats counters\n");
1157 #endif
1158 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1159 	} else if (stat == 4) {
1160 #ifdef BBR_INVARIANTS
1161 		printf("Clearing BBR out-size counters\n");
1162 #endif
1163 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1164 	}
1165 	bbr_clear_lost = 0;
1166 	return (0);
1167 }
1168 
1169 static void
1170 bbr_init_sysctls(void)
1171 {
1172 	struct sysctl_oid *bbr_probertt;
1173 	struct sysctl_oid *bbr_hptsi;
1174 	struct sysctl_oid *bbr_measure;
1175 	struct sysctl_oid *bbr_cwnd;
1176 	struct sysctl_oid *bbr_timeout;
1177 	struct sysctl_oid *bbr_states;
1178 	struct sysctl_oid *bbr_startup;
1179 	struct sysctl_oid *bbr_policer;
1180 
1181 	/* Probe rtt controls */
1182 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1183 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1184 	    OID_AUTO,
1185 	    "probertt",
1186 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1187 	    "");
1188 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1189 	    SYSCTL_CHILDREN(bbr_probertt),
1190 	    OID_AUTO, "gain", CTLFLAG_RW,
1191 	    &bbr_rttprobe_gain, 192,
1192 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1193 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1194 	    SYSCTL_CHILDREN(bbr_probertt),
1195 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1196 	    &bbr_rtt_probe_cwndtarg, 4,
1197 	    "How many mss's are outstanding during probe-rtt");
1198 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1199 	    SYSCTL_CHILDREN(bbr_probertt),
1200 	    OID_AUTO, "int", CTLFLAG_RW,
1201 	    &bbr_rtt_probe_limit, 4000000,
1202 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1203 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1204 	    SYSCTL_CHILDREN(bbr_probertt),
1205 	    OID_AUTO, "mintime", CTLFLAG_RW,
1206 	    &bbr_rtt_probe_time, 200000,
1207 	    "How many microseconds in probe-rtt");
1208 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1209 	    SYSCTL_CHILDREN(bbr_probertt),
1210 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1211 	    &bbr_filter_len_sec, 6,
1212 	    "How long in seconds does the rttProp filter run?");
1213 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1214 	    SYSCTL_CHILDREN(bbr_probertt),
1215 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1216 	    &bbr_drain_rtt, BBR_SRTT,
1217 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1218 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1219 	    SYSCTL_CHILDREN(bbr_probertt),
1220 	    OID_AUTO, "can_force", CTLFLAG_RW,
1221 	    &bbr_can_force_probertt, 0,
1222 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1223 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1224 	    SYSCTL_CHILDREN(bbr_probertt),
1225 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1226 	    &bbr_probertt_sets_rtt, 0,
1227 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1228 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1229 	    SYSCTL_CHILDREN(bbr_probertt),
1230 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1231 	    &bbr_can_adjust_probertt, 1,
1232 	    "Can we dynamically adjust the probe-rtt limits and times?");
1233 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1234 	    SYSCTL_CHILDREN(bbr_probertt),
1235 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1236 	    &bbr_is_ratio, 0,
1237 	    "is the limit to filter a ratio?");
1238 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1239 	    SYSCTL_CHILDREN(bbr_probertt),
1240 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1241 	    &bbr_prtt_slam_cwnd, 0,
1242 	    "Should we set/recover cwnd?");
1243 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1244 	    SYSCTL_CHILDREN(bbr_probertt),
1245 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1246 	    &bbr_can_use_ts_for_rtt, 1,
1247 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1248 
1249 	/* Pacing controls */
1250 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1251 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1252 	    OID_AUTO,
1253 	    "pacing",
1254 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1255 	    "");
1256 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1257 	    SYSCTL_CHILDREN(bbr_hptsi),
1258 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1259 	    &bbr_allow_hdwr_pacing, 1,
1260 	    "Do we allow hardware pacing?");
1261 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1262 	    SYSCTL_CHILDREN(bbr_hptsi),
1263 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1264 	    &bbr_hardware_pacing_limit, 4000,
1265 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1266 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1267 	    SYSCTL_CHILDREN(bbr_hptsi),
1268 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1269 	    &bbr_hdwr_pace_adjust, 2,
1270 	    "Multiplier to calculated tso size?");
1271 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1272 	    SYSCTL_CHILDREN(bbr_hptsi),
1273 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1274 	    &bbr_hdwr_pace_floor, 1,
1275 	    "Do we invoke the hardware pacing floor?");
1276 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1277 	    SYSCTL_CHILDREN(bbr_hptsi),
1278 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1279 	    &bbr_hdwr_pacing_delay_cnt, 10,
1280 	    "How many packets must be sent after hdwr pacing is enabled");
1281 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1282 	    SYSCTL_CHILDREN(bbr_hptsi),
1283 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1284 	    &bbr_cross_over, 3000000,
1285 	    "What is the point where we cross over to linux like TSO size set");
1286 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1287 	    SYSCTL_CHILDREN(bbr_hptsi),
1288 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1289 	    &bbr_hptsi_segments_delay_tar, 7000,
1290 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1291 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1292 	    SYSCTL_CHILDREN(bbr_hptsi),
1293 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1294 	    &bbr_include_enet_oh, 0,
1295 	    "Do we include the ethernet overhead in calculating pacing delay?");
1296 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1297 	    SYSCTL_CHILDREN(bbr_hptsi),
1298 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1299 	    &bbr_include_ip_oh, 1,
1300 	    "Do we include the IP overhead in calculating pacing delay?");
1301 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1302 	    SYSCTL_CHILDREN(bbr_hptsi),
1303 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1304 	    &bbr_include_tcp_oh, 0,
1305 	    "Do we include the TCP overhead in calculating pacing delay?");
1306 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1307 	    SYSCTL_CHILDREN(bbr_hptsi),
1308 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1309 	    &bbr_google_discount, 10,
1310 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1311 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1312 	    SYSCTL_CHILDREN(bbr_hptsi),
1313 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1314 	    &bbr_all_get_min, 0,
1315 	    "If you are less than a MSS do you just get the min?");
1316 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1317 	    SYSCTL_CHILDREN(bbr_hptsi),
1318 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1319 	    &bbr_hptsi_bytes_min, 1460,
1320 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1321 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1322 	    SYSCTL_CHILDREN(bbr_hptsi),
1323 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1324 	    &bbr_hptsi_segments_max, 6,
1325 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1326 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1327 	    SYSCTL_CHILDREN(bbr_hptsi),
1328 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1329 	    &bbr_hptsi_segments_floor, 1,
1330 	    "Minimum TSO size we will fall too in segments");
1331 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1332 	    SYSCTL_CHILDREN(bbr_hptsi),
1333 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1334 	    &bbr_hptsi_utter_max, 0,
1335 	    "The absolute maximum that any pacing (outside of hardware) can be");
1336 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1337 	    SYSCTL_CHILDREN(bbr_hptsi),
1338 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1339 	    &bbr_hptsi_per_second, 100,
1340 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1341 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1342 	    SYSCTL_CHILDREN(bbr_hptsi),
1343 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1344 	    &bbr_hptsi_max_mul, 1,
1345 	    "The multiplier for pace len max");
1346 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1347 	    SYSCTL_CHILDREN(bbr_hptsi),
1348 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1349 	    &bbr_hptsi_max_div, 2,
1350 	    "The divisor for pace len max");
1351 	/* Measurement controls */
1352 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1353 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1354 	    OID_AUTO,
1355 	    "measure",
1356 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1357 	    "Measurement controls");
1358 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1359 	    SYSCTL_CHILDREN(bbr_measure),
1360 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1361 	    &bbr_initial_bw_bps, 62500,
1362 	    "Minimum initial b/w in bytes per second");
1363 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1364 	    SYSCTL_CHILDREN(bbr_measure),
1365 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1366 	    &bbr_sack_not_required, 0,
1367 	    "Do we allow bbr to run on connections not supporting SACK?");
1368 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1369 	    SYSCTL_CHILDREN(bbr_measure),
1370 	    OID_AUTO, "use_google", CTLFLAG_RW,
1371 	    &bbr_use_google_algo, 0,
1372 	    "Use has close to google V1.0 has possible?");
1373 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1374 	    SYSCTL_CHILDREN(bbr_measure),
1375 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1376 	    &bbr_ts_limiting, 1,
1377 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1378 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1379 	    SYSCTL_CHILDREN(bbr_measure),
1380 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1381 	    &bbr_ts_can_raise, 0,
1382 	    "Can we raise the b/w via timestamp b/w calculation?");
1383 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1384 	    SYSCTL_CHILDREN(bbr_measure),
1385 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1386 	    &bbr_min_usec_delta, 20000,
1387 	    "How long in usec between ts of our sends in ts validation code?");
1388 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1389 	    SYSCTL_CHILDREN(bbr_measure),
1390 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1391 	    &bbr_min_peer_delta, 20,
1392 	    "What min numerical value should be between the peer deltas?");
1393 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1394 	    SYSCTL_CHILDREN(bbr_measure),
1395 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1396 	    &bbr_delta_percent, 150,
1397 	    "What percentage (150 = 15.0) do we allow variance for?");
1398 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1399 	    SYSCTL_CHILDREN(bbr_measure),
1400 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1401 	    &bbr_min_measurements_req, 1,
1402 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1403 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1404 	    SYSCTL_CHILDREN(bbr_measure),
1405 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1406 	    &bbr_no_pacing_until, 4,
1407 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1408 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1409 	    SYSCTL_CHILDREN(bbr_measure),
1410 	    OID_AUTO, "quanta", CTLFLAG_RW,
1411 	    &bbr_quanta, 2,
1412 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1413 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1414 	    SYSCTL_CHILDREN(bbr_measure),
1415 	    OID_AUTO, "noretran", CTLFLAG_RW,
1416 	    &bbr_no_retran, 0,
1417 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1418 	/* State controls */
1419 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1420 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1421 	    OID_AUTO,
1422 	    "states",
1423 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1424 	    "State controls");
1425 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1426 	    SYSCTL_CHILDREN(bbr_states),
1427 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1428 	    &bbr_uses_idle_restart, 0,
1429 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1430 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1431 	    SYSCTL_CHILDREN(bbr_states),
1432 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1433 	    &bbr_idle_restart_threshold, 100000,
1434 	    "How long must we be idle before we restart??");
1435 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1436 	    SYSCTL_CHILDREN(bbr_states),
1437 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1438 	    &bbr_state_is_pkt_epoch, 0,
1439 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1440 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1441 	    SYSCTL_CHILDREN(bbr_states),
1442 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1443 	    &bbr_rtt_gain_thresh, 0,
1444 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1445 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1446 	    SYSCTL_CHILDREN(bbr_states),
1447 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1448 	    &bbr_drain_floor, 88,
1449 	    "What is the lowest we can drain (pg) too?");
1450 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1451 	    SYSCTL_CHILDREN(bbr_states),
1452 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1453 	    &bbr_state_drain_2_tar, 1,
1454 	    "Do we drain to target in drain substate?");
1455 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1456 	    SYSCTL_CHILDREN(bbr_states),
1457 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1458 	    &bbr_gain_to_target, 1,
1459 	    "Does probe bw gain to target??");
1460 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1461 	    SYSCTL_CHILDREN(bbr_states),
1462 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1463 	    &bbr_gain_gets_extra_too, 1,
1464 	    "Does probe bw gain get the extra time too?");
1465 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1466 	    SYSCTL_CHILDREN(bbr_states),
1467 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1468 	    &bbr_drain_drop_div, 5,
1469 	    "Long drain drop divider?");
1470 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1471 	    SYSCTL_CHILDREN(bbr_states),
1472 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1473 	    &bbr_drain_drop_mul, 4,
1474 	    "Long drain drop multiplier?");
1475 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1476 	    SYSCTL_CHILDREN(bbr_states),
1477 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1478 	    &bbr_rand_ot, 50,
1479 	    "Random discount of the ot?");
1480 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1481 	    SYSCTL_CHILDREN(bbr_states),
1482 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1483 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1484 	    "How many packet-epochs does the b/w delivery rate last?");
1485 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1486 	    SYSCTL_CHILDREN(bbr_states),
1487 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1488 	    &bbr_sub_drain_app_limit, 0,
1489 	    "Does our sub-state drain invoke app limited if its long?");
1490 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1491 	    SYSCTL_CHILDREN(bbr_states),
1492 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1493 	    &bbr_sub_drain_slam_cwnd, 0,
1494 	    "Should we set/recover cwnd for sub-state drain?");
1495 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1496 	    SYSCTL_CHILDREN(bbr_states),
1497 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1498 	    &bbr_slam_cwnd_in_main_drain, 0,
1499 	    "Should we set/recover cwnd for main-state drain?");
1500 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1501 	    SYSCTL_CHILDREN(bbr_states),
1502 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1503 	    &google_allow_early_out, 1,
1504 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1505 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1506 	    SYSCTL_CHILDREN(bbr_states),
1507 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1508 	    &google_consider_lost, 1,
1509 	    "Should we have losses exit gain of probebw in google mode??");
1510 	/* Startup controls */
1511 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1512 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1513 	    OID_AUTO,
1514 	    "startup",
1515 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1516 	    "Startup controls");
1517 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1518 	    SYSCTL_CHILDREN(bbr_startup),
1519 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1520 	    &bbr_sends_full_iwnd, 1,
1521 	    "Do we not pace but burst out initial windows has our TSO size?");
1522 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1523 	    SYSCTL_CHILDREN(bbr_startup),
1524 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1525 	    &bbr_startup_loss_thresh, 2000,
1526 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1527 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1528 	    SYSCTL_CHILDREN(bbr_startup),
1529 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1530 	    &bbr_use_lower_gain_in_startup, 1,
1531 	    "Should we use a lower hptsi gain if we see loss in startup?");
1532 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1533 	    SYSCTL_CHILDREN(bbr_startup),
1534 	    OID_AUTO, "gain", CTLFLAG_RW,
1535 	    &bbr_start_exit, 25,
1536 	    "What gain percent do we need to see to stay in startup??");
1537 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1538 	    SYSCTL_CHILDREN(bbr_startup),
1539 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1540 	    &bbr_low_start_exit, 15,
1541 	    "What gain percent do we need to see to stay in the lower gain startup??");
1542 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1543 	    SYSCTL_CHILDREN(bbr_startup),
1544 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1545 	    &bbr_exit_startup_at_loss, 1,
1546 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1547 	/* CWND controls */
1548 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1549 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1550 	    OID_AUTO,
1551 	    "cwnd",
1552 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1553 	    "Cwnd controls");
1554 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1555 	    SYSCTL_CHILDREN(bbr_cwnd),
1556 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1557 	    &bbr_cwndtarget_rtt_touse, 0,
1558 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1559 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1560 	    SYSCTL_CHILDREN(bbr_cwnd),
1561 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1562 	    &bbr_cwnd_may_shrink, 0,
1563 	    "Can the cwnd shrink if it would grow to more than the target?");
1564 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1565 	    SYSCTL_CHILDREN(bbr_cwnd),
1566 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1567 	    &bbr_target_cwnd_mult_limit, 8,
1568 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1569 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1570 	    SYSCTL_CHILDREN(bbr_cwnd),
1571 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1572 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1573 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1574 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1575 	    SYSCTL_CHILDREN(bbr_cwnd),
1576 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1577 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1578 	    "What is the min cwnd (rttProp > 1ms)");
1579 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1580 	    SYSCTL_CHILDREN(bbr_cwnd),
1581 	    OID_AUTO, "initwin", CTLFLAG_RW,
1582 	    &bbr_def_init_win, 10,
1583 	    "What is the BBR initial window, if 0 use tcp version");
1584 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1585 	    SYSCTL_CHILDREN(bbr_cwnd),
1586 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1587 	    &bbr_do_red, 600,
1588 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1589 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1590 	    SYSCTL_CHILDREN(bbr_cwnd),
1591 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1592 	    &bbr_red_scale, 20000,
1593 	    "What RTT do we scale with?");
1594 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1595 	    SYSCTL_CHILDREN(bbr_cwnd),
1596 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1597 	    &bbr_red_growth_restrict, 1,
1598 	    "Do we restrict cwnd growth for whats in flight?");
1599 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1600 	    SYSCTL_CHILDREN(bbr_cwnd),
1601 	    OID_AUTO, "red_div", CTLFLAG_RW,
1602 	    &bbr_red_div, 2,
1603 	    "If we reduce whats the divisor?");
1604 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1605 	    SYSCTL_CHILDREN(bbr_cwnd),
1606 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1607 	    &bbr_red_mul, 1,
1608 	    "If we reduce whats the mulitiplier?");
1609 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1610 	    SYSCTL_CHILDREN(bbr_cwnd),
1611 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1612 	    &bbr_target_is_bbunit, 0,
1613 	    "Is the state target the pacing_gain or BBR_UNIT?");
1614 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1615 	    SYSCTL_CHILDREN(bbr_cwnd),
1616 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1617 	    &bbr_drop_limit, 0,
1618 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1619 
1620 	/* Timeout controls */
1621 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1622 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1623 	    OID_AUTO,
1624 	    "timeout",
1625 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1626 	    "Time out controls");
1627 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1628 	    SYSCTL_CHILDREN(bbr_timeout),
1629 	    OID_AUTO, "delack", CTLFLAG_RW,
1630 	    &bbr_delack_time, 100000,
1631 	    "BBR's delayed ack time");
1632 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1633 	    SYSCTL_CHILDREN(bbr_timeout),
1634 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1635 	    &bbr_tlp_type_to_use, 3,
1636 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1637 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1638 	    SYSCTL_CHILDREN(bbr_timeout),
1639 	    OID_AUTO, "persmin", CTLFLAG_RW,
1640 	    &bbr_persist_min, 250000,
1641 	    "What is the minimum time in microseconds between persists");
1642 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1643 	    SYSCTL_CHILDREN(bbr_timeout),
1644 	    OID_AUTO, "persmax", CTLFLAG_RW,
1645 	    &bbr_persist_max, 1000000,
1646 	    "What is the largest delay in microseconds between persists");
1647 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1648 	    SYSCTL_CHILDREN(bbr_timeout),
1649 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1650 	    &bbr_tlp_min, 10000,
1651 	    "TLP Min timeout in usecs");
1652 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1653 	    SYSCTL_CHILDREN(bbr_timeout),
1654 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1655 	    &bbr_delayed_ack_time, 200000,
1656 	    "TLP delayed ack compensation value");
1657 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1658 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1659 	    OID_AUTO, "minrto", CTLFLAG_RW,
1660 	    &bbr_rto_min_ms, 30,
1661 	    "Minimum RTO in ms");
1662 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1663 	    SYSCTL_CHILDREN(bbr_timeout),
1664 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1665 	    &bbr_rto_max_sec, 4,
1666 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1667 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1668 	    SYSCTL_CHILDREN(bbr_timeout),
1669 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1670 	    &bbr_tlp_max_resend, 2,
1671 	    "How many times does TLP retry a single segment or multiple with no ACK");
1672 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1673 	    SYSCTL_CHILDREN(bbr_timeout),
1674 	    OID_AUTO, "minto", CTLFLAG_RW,
1675 	    &bbr_min_to, 1000,
1676 	    "Minimum rack timeout in useconds");
1677 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1678 	    SYSCTL_CHILDREN(bbr_timeout),
1679 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1680 	    &bbr_pkt_delay, 1000,
1681 	    "Extra RACK time (in useconds) besides reordering thresh");
1682 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1683 	    SYSCTL_CHILDREN(bbr_timeout),
1684 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1685 	    &bbr_incr_timers, 1,
1686 	    "Increase the RXT/TLP timer by the pacing time used?");
1687 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1688 	    SYSCTL_CHILDREN(bbr_timeout),
1689 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1690 	    &bbr_marks_rxt_sack_passed, 0,
1691 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1692 	/* Policer controls */
1693 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1694 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1695 	    OID_AUTO,
1696 	    "policer",
1697 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1698 	    "Policer controls");
1699 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1700 	    SYSCTL_CHILDREN(bbr_policer),
1701 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1702 	    &bbr_policer_detection_enabled, 1,
1703 	    "Is policer detection enabled??");
1704 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1705 	    SYSCTL_CHILDREN(bbr_policer),
1706 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1707 	    &bbr_lt_intvl_min_rtts, 4,
1708 	    "Minimum number of PE's?");
1709 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1710 	    SYSCTL_CHILDREN(bbr_policer),
1711 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1712 	    &bbr_lt_bw_diff, (4000/8),
1713 	    "Minimal bw diff?");
1714 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1715 	    SYSCTL_CHILDREN(bbr_policer),
1716 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1717 	    &bbr_lt_bw_ratio, 8,
1718 	    "Minimal bw diff?");
1719 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1720 	    SYSCTL_CHILDREN(bbr_policer),
1721 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1722 	    &bbr_policer_call_from_rack_to, 0,
1723 	    "Do we call the policer detection code from a rack-timeout?");
1724 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1725 	    SYSCTL_CHILDREN(bbr_policer),
1726 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1727 	    &bbr_lt_intvl_fp, 0,
1728 	    "What packet epoch do we do false-positive detection at (0=no)?");
1729 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1730 	    SYSCTL_CHILDREN(bbr_policer),
1731 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1732 	    &bbr_lt_loss_thresh, 196,
1733 	    "Loss threshold 196 = 19.6%?");
1734 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1735 	    SYSCTL_CHILDREN(bbr_policer),
1736 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1737 	    &bbr_lt_fd_thresh, 100,
1738 	    "What percentage is the false detection threshold (150=15.0)?");
1739 	/* All the rest */
1740 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1741 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1742 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1743 	    &bbr_use_rack_resend_cheat, 0,
1744 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1745 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1746 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1747 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1748 	    &bbr_error_base_paceout, 10000,
1749 	    "When we hit an error what is the min to pace out in usec's?");
1750 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1751 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1752 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1753 	    &bbr_max_net_error_cnt, 10,
1754 	    "When we hit this many errors in a row, kill the session?");
1755 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1756 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1757 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1758 	    &bbr_ignore_data_after_close, 1,
1759 	    "Do we hold off sending a RST until all pending data is ack'd");
1760 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1761 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1762 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1763 	    &bbr_resends_use_tso, 0,
1764 	    "Can resends use TSO?");
1765 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1766 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1767 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1768 	    &bbr_sack_block_limit, 128,
1769 	    "When do we start ignoring small sack blocks");
1770 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1771 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1772 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1773 	    &bbr_verbose_logging, 0,
1774 	    "Should BBR black box logging be verbose");
1775 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1776 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1777 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1778 	    &bbr_reorder_thresh, 2,
1779 	    "What factor for rack will be added when seeing reordering (shift right)");
1780 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1781 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1782 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1783 	    &bbr_reorder_fade, 0,
1784 	    "Does reorder detection fade, if so how many ms (0 means never)");
1785 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1786 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1787 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1788 	    &bbr_tlp_thresh, 1,
1789 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1790 	/* Stats and counters */
1791 	/* The pacing counters for hdwr/software can't be in the array */
1792 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1793 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1794 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1795 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1796 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1797 	    &bbr_hdwr_pacing_enobuf,
1798 	    "Total number of enobufs for hardware paced flows");
1799 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1800 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1801 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1802 	    &bbr_nohdwr_pacing_enobuf,
1803 	    "Total number of enobufs for non-hardware paced flows");
1804 
1805 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1806 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1807 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1808 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1809 	    &bbr_flows_whdwr_pacing,
1810 	    "Total number of hardware paced flows");
1811 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1812 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1813 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1814 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1815 	    &bbr_flows_nohdwr_pacing,
1816 	    "Total number of software paced flows");
1817 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1818 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1819 	    OID_AUTO, "stats", CTLFLAG_RD,
1820 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1821 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1822 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1823 	    OID_AUTO, "opts", CTLFLAG_RD,
1824 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1825 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1826 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1827 	    OID_AUTO, "lost", CTLFLAG_RD,
1828 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1829 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1830 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1831 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1832 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1833 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1834 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1835 	    OID_AUTO, "statetime", CTLFLAG_RD,
1836 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1837 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1838 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1839 	    OID_AUTO, "outsize", CTLFLAG_RD,
1840 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1841 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1842 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1843 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1844 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1845 }
1846 
1847 static void
1848 bbr_counter_destroy(void)
1849 {
1850 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1851 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1852 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1853 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1854 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1855 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1856 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1857 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1858 	counter_u64_free(bbr_flows_whdwr_pacing);
1859 	counter_u64_free(bbr_flows_nohdwr_pacing);
1860 
1861 }
1862 
1863 static __inline void
1864 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1865 {
1866 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1867 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1868 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1869 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1870 	l->bw_inuse = bbr_get_bw(bbr);
1871 	l->inflight = ctf_flight_size(bbr->rc_tp,
1872 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1873 	l->applimited = bbr->r_ctl.r_app_limited_until;
1874 	l->delivered = bbr->r_ctl.rc_delivered;
1875 	l->timeStamp = cts;
1876 	l->lost = bbr->r_ctl.rc_lost;
1877 	l->bbr_state = bbr->rc_bbr_state;
1878 	l->bbr_substate = bbr_state_val(bbr);
1879 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1880 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1881 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1882 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1883 	l->inhpts = tcp_in_hpts(bbr->rc_inp);
1884 	l->use_lt_bw = bbr->rc_lt_use_bw;
1885 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1886 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1887 }
1888 
1889 static void
1890 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1891 {
1892 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1893 		union tcp_log_stackspecific log;
1894 
1895 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1896 		log.u_bbr.flex1 = 0;
1897 		log.u_bbr.flex2 = 0;
1898 		log.u_bbr.flex5 = 0;
1899 		log.u_bbr.flex3 = 0;
1900 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1901 		log.u_bbr.flex7 = reason;
1902 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1903 		log.u_bbr.flex8 = 0;
1904 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1905 		    &bbr->rc_inp->inp_socket->so_rcv,
1906 		    &bbr->rc_inp->inp_socket->so_snd,
1907 		    BBR_LOG_BW_RED_EV, 0,
1908 		    0, &log, false, &bbr->rc_tv);
1909 	}
1910 }
1911 
1912 static void
1913 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1914 {
1915 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1916 		union tcp_log_stackspecific log;
1917 
1918 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1919 		log.u_bbr.flex1 = seq;
1920 		log.u_bbr.flex2 = count;
1921 		log.u_bbr.flex8 = mode;
1922 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1923 		    &bbr->rc_inp->inp_socket->so_rcv,
1924 		    &bbr->rc_inp->inp_socket->so_snd,
1925 		    BBR_LOG_LOWGAIN, 0,
1926 		    0, &log, false, &bbr->rc_tv);
1927 	}
1928 }
1929 
1930 static void
1931 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1932     uint8_t reason, uint32_t p_maxseg, int len)
1933 {
1934 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1935 		union tcp_log_stackspecific log;
1936 
1937 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1938 		log.u_bbr.flex1 = p_maxseg;
1939 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1940 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1941 		log.u_bbr.flex4 = reason;
1942 		log.u_bbr.flex5 = bbr->rc_in_persist;
1943 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1944 		log.u_bbr.flex7 = p_maxseg;
1945 		log.u_bbr.flex8 = bbr->rc_in_persist;
1946 		log.u_bbr.pkts_out = 0;
1947 		log.u_bbr.applimited = len;
1948 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1949 		    &bbr->rc_inp->inp_socket->so_rcv,
1950 		    &bbr->rc_inp->inp_socket->so_snd,
1951 		    BBR_LOG_JUSTRET, 0,
1952 		    tlen, &log, false, &bbr->rc_tv);
1953 	}
1954 }
1955 
1956 static void
1957 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1958 {
1959 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1960 		union tcp_log_stackspecific log;
1961 
1962 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1963 		log.u_bbr.flex1 = seq;
1964 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1965 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1966 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1967 		    &bbr->rc_inp->inp_socket->so_rcv,
1968 		    &bbr->rc_inp->inp_socket->so_snd,
1969 		    BBR_LOG_ENTREC, 0,
1970 		    0, &log, false, &bbr->rc_tv);
1971 	}
1972 }
1973 
1974 static void
1975 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)
1976 {
1977 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
1978 		union tcp_log_stackspecific log;
1979 
1980 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1981 		log.u_bbr.flex1 = tso;
1982 		log.u_bbr.flex2 = maxseg;
1983 		log.u_bbr.flex3 = mtu;
1984 		log.u_bbr.flex4 = csum_flags;
1985 		TCP_LOG_EVENTP(tp, NULL,
1986 		    &bbr->rc_inp->inp_socket->so_rcv,
1987 		    &bbr->rc_inp->inp_socket->so_snd,
1988 		    BBR_LOG_MSGSIZE, 0,
1989 		    0, &log, false, &bbr->rc_tv);
1990 	}
1991 }
1992 
1993 static void
1994 bbr_log_flowend(struct tcp_bbr *bbr)
1995 {
1996 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
1997 		union tcp_log_stackspecific log;
1998 		struct sockbuf *r, *s;
1999 		struct timeval tv;
2000 
2001 		if (bbr->rc_inp->inp_socket) {
2002 			r = &bbr->rc_inp->inp_socket->so_rcv;
2003 			s = &bbr->rc_inp->inp_socket->so_snd;
2004 		} else {
2005 			r = s = NULL;
2006 		}
2007 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2008 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2009 		    r, s,
2010 		    TCP_LOG_FLOWEND, 0,
2011 		    0, &log, false, &tv);
2012 	}
2013 }
2014 
2015 static void
2016 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2017     uint32_t lost, uint32_t del)
2018 {
2019 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2020 		union tcp_log_stackspecific log;
2021 
2022 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2023 		log.u_bbr.flex1 = lost;
2024 		log.u_bbr.flex2 = del;
2025 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2026 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2027 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2028 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2029 		log.u_bbr.flex7 = line;
2030 		log.u_bbr.flex8 = 0;
2031 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2032 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2033 		    &bbr->rc_inp->inp_socket->so_rcv,
2034 		    &bbr->rc_inp->inp_socket->so_snd,
2035 		    BBR_LOG_PKT_EPOCH, 0,
2036 		    0, &log, false, &bbr->rc_tv);
2037 	}
2038 }
2039 
2040 static void
2041 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2042 {
2043 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2044 		union tcp_log_stackspecific log;
2045 
2046 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2047 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2048 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2049 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2050 		log.u_bbr.flex7 = line;
2051 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2052 		    &bbr->rc_inp->inp_socket->so_rcv,
2053 		    &bbr->rc_inp->inp_socket->so_snd,
2054 		    BBR_LOG_TIME_EPOCH, 0,
2055 		    0, &log, false, &bbr->rc_tv);
2056 	}
2057 }
2058 
2059 static void
2060 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2061 {
2062 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2063 		union tcp_log_stackspecific log;
2064 
2065 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2066 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2067 		log.u_bbr.flex2 = new_tar;
2068 		log.u_bbr.flex3 = line;
2069 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2070 		log.u_bbr.flex5 = bbr_quanta;
2071 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2072 		log.u_bbr.flex7 = bbr->rc_last_options;
2073 		log.u_bbr.flex8 = meth;
2074 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2075 		    &bbr->rc_inp->inp_socket->so_rcv,
2076 		    &bbr->rc_inp->inp_socket->so_snd,
2077 		    BBR_LOG_STATE_TARGET, 0,
2078 		    0, &log, false, &bbr->rc_tv);
2079 	}
2080 
2081 }
2082 
2083 static void
2084 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2085 {
2086 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2087 		union tcp_log_stackspecific log;
2088 
2089 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2090 		log.u_bbr.flex1 = line;
2091 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2092 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2093 		if (bbr_state_is_pkt_epoch)
2094 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2095 		else
2096 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2097 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2098 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2099 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2100 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2101 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2102 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2103 		    &bbr->rc_inp->inp_socket->so_rcv,
2104 		    &bbr->rc_inp->inp_socket->so_snd,
2105 		    BBR_LOG_STATE, 0,
2106 		    0, &log, false, &bbr->rc_tv);
2107 	}
2108 }
2109 
2110 static void
2111 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2112 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2113 {
2114 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2115 		union tcp_log_stackspecific log;
2116 
2117 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2118 		log.u_bbr.flex1 = line;
2119 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2120 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2121 		log.u_bbr.flex4 = applied;
2122 		log.u_bbr.flex5 = rtt;
2123 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2124 		log.u_bbr.flex7 = cond;
2125 		log.u_bbr.flex8 = reas;
2126 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2127 		    &bbr->rc_inp->inp_socket->so_rcv,
2128 		    &bbr->rc_inp->inp_socket->so_snd,
2129 		    BBR_LOG_RTT_SHRINKS, 0,
2130 		    0, &log, false, &bbr->rc_tv);
2131 	}
2132 }
2133 
2134 static void
2135 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2136 {
2137 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2138 		union tcp_log_stackspecific log;
2139 
2140 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2141 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2142 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2143 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2144 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2145 		    &bbr->rc_inp->inp_socket->so_rcv,
2146 		    &bbr->rc_inp->inp_socket->so_snd,
2147 		    BBR_LOG_EXITREC, 0,
2148 		    0, &log, false, &bbr->rc_tv);
2149 	}
2150 }
2151 
2152 static void
2153 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2154     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2155 {
2156 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2157 		union tcp_log_stackspecific log;
2158 
2159 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2160 		log.u_bbr.flex1 = line;
2161 		log.u_bbr.flex2 = prev_acked;
2162 		log.u_bbr.flex3 = bytes_this_ack;
2163 		log.u_bbr.flex4 = chg;
2164 		log.u_bbr.flex5 = th_ack;
2165 		log.u_bbr.flex6 = target;
2166 		log.u_bbr.flex8 = meth;
2167 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2168 		    &bbr->rc_inp->inp_socket->so_rcv,
2169 		    &bbr->rc_inp->inp_socket->so_snd,
2170 		    BBR_LOG_CWND, 0,
2171 		    0, &log, false, &bbr->rc_tv);
2172 	}
2173 }
2174 
2175 static void
2176 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2177 {
2178 	/*
2179 	 * Log the rtt sample we are applying to the srtt algorithm in
2180 	 * useconds.
2181 	 */
2182 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2183 		union tcp_log_stackspecific log;
2184 
2185 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2186 		log.u_bbr.flex1 = rtt;
2187 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2188 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2189 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2190 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2191 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2192 		log.u_bbr.flex6 = tsin;
2193 		log.u_bbr.flex7 = 0;
2194 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2195 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2196 		    &bbr->rc_inp->inp_socket->so_rcv,
2197 		    &bbr->rc_inp->inp_socket->so_snd,
2198 		    TCP_LOG_RTT, 0,
2199 		    0, &log, false, &bbr->rc_tv);
2200 	}
2201 }
2202 
2203 static void
2204 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2205 {
2206 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2207 		union tcp_log_stackspecific log;
2208 
2209 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2210 		log.u_bbr.flex1 = time_in;
2211 		log.u_bbr.flex2 = line;
2212 		log.u_bbr.flex8 = enter_exit;
2213 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2214 		    &bbr->rc_inp->inp_socket->so_rcv,
2215 		    &bbr->rc_inp->inp_socket->so_snd,
2216 		    BBR_LOG_PERSIST, 0,
2217 		    0, &log, false, &bbr->rc_tv);
2218 	}
2219 }
2220 static void
2221 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2222 {
2223 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2224 		union tcp_log_stackspecific log;
2225 
2226 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2227 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2228 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2229 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2230 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2231 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2232 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2233 		    &bbr->rc_inp->inp_socket->so_rcv,
2234 		    &bbr->rc_inp->inp_socket->so_snd,
2235 		    BBR_LOG_ACKCLEAR, 0,
2236 		    0, &log, false, &bbr->rc_tv);
2237 	}
2238 }
2239 
2240 static void
2241 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2242 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2243 {
2244 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2245 		union tcp_log_stackspecific log;
2246 		struct timeval tv;
2247 
2248 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2249 		log.u_bbr.flex1 = nsegs;
2250 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2251 		if (m) {
2252 			struct timespec ts;
2253 
2254 			log.u_bbr.flex3 = m->m_flags;
2255 			if (m->m_flags & M_TSTMP) {
2256 				mbuf_tstmp2timespec(m, &ts);
2257 				tv.tv_sec = ts.tv_sec;
2258 				tv.tv_usec = ts.tv_nsec / 1000;
2259 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2260 			} else {
2261 				log.u_bbr.lt_epoch = 0;
2262 			}
2263 			if (m->m_flags & M_TSTMP_LRO) {
2264 				tv.tv_sec = m->m_pkthdr.rcv_tstmp / 1000000000;
2265 				tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000) / 1000;
2266 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2267 			} else {
2268 				/* No arrival timestamp */
2269 				log.u_bbr.flex5 = 0;
2270 			}
2271 
2272 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2273 		} else {
2274 			log.u_bbr.flex3 = 0;
2275 			log.u_bbr.flex5 = 0;
2276 			log.u_bbr.flex6 = 0;
2277 			log.u_bbr.pkts_out = 0;
2278 		}
2279 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2280 		log.u_bbr.flex7 = bbr->r_wanted_output;
2281 		log.u_bbr.flex8 = bbr->rc_in_persist;
2282 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2283 		    &bbr->rc_inp->inp_socket->so_rcv,
2284 		    &bbr->rc_inp->inp_socket->so_snd,
2285 		    TCP_LOG_IN, 0,
2286 		    tlen, &log, true, &bbr->rc_tv);
2287 	}
2288 }
2289 
2290 static void
2291 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2292 {
2293 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2294 		union tcp_log_stackspecific log;
2295 
2296 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2297 		log.u_bbr.flex1 = did_out;
2298 		log.u_bbr.flex2 = nxt_pkt;
2299 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2300 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2301 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2302 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2303 		log.u_bbr.flex7 = bbr->r_wanted_output;
2304 		log.u_bbr.flex8 = bbr->rc_in_persist;
2305 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2306 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2307 		    &bbr->rc_inp->inp_socket->so_rcv,
2308 		    &bbr->rc_inp->inp_socket->so_snd,
2309 		    BBR_LOG_DOSEG_DONE, 0,
2310 		    0, &log, true, &bbr->rc_tv);
2311 	}
2312 }
2313 
2314 static void
2315 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2316     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2317 {
2318 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2319 		union tcp_log_stackspecific log;
2320 
2321 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2322 		log.u_bbr.flex1 = line;
2323 		log.u_bbr.flex2 = o_len;
2324 		log.u_bbr.flex3 = segcnt;
2325 		log.u_bbr.flex4 = segsiz;
2326 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2327 		    &bbr->rc_inp->inp_socket->so_rcv,
2328 		    &bbr->rc_inp->inp_socket->so_snd,
2329 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2330 		    len, &log, true, &bbr->rc_tv);
2331 	}
2332 }
2333 
2334 static void
2335 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2336 {
2337 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2338 		union tcp_log_stackspecific log;
2339 
2340 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2341 		log.u_bbr.flex1 = timers;
2342 		log.u_bbr.flex2 = ret;
2343 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2344 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2345 		log.u_bbr.flex5 = cts;
2346 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2347 		log.u_bbr.flex8 = hpts_calling;
2348 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2349 		    &bbr->rc_inp->inp_socket->so_rcv,
2350 		    &bbr->rc_inp->inp_socket->so_snd,
2351 		    BBR_LOG_TO_PROCESS, 0,
2352 		    0, &log, false, &bbr->rc_tv);
2353 	}
2354 }
2355 
2356 static void
2357 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2358 {
2359 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2360 		union tcp_log_stackspecific log;
2361 		uint64_t ar;
2362 
2363 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2364 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2365 		log.u_bbr.flex2 = 0;
2366 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2367 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2368 		ar >>= 32;
2369 		ar &= 0x00000000ffffffff;
2370 		log.u_bbr.flex4 = (uint32_t)ar;
2371 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2372 		ar &= 0x00000000ffffffff;
2373 		log.u_bbr.flex5 = (uint32_t)ar;
2374 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2375 		log.u_bbr.flex8 = to_num;
2376 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2377 		    &bbr->rc_inp->inp_socket->so_rcv,
2378 		    &bbr->rc_inp->inp_socket->so_snd,
2379 		    BBR_LOG_RTO, 0,
2380 		    0, &log, false, &bbr->rc_tv);
2381 	}
2382 }
2383 
2384 static void
2385 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2386 {
2387 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2388 		union tcp_log_stackspecific log;
2389 
2390 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2391 		log.u_bbr.flex1 = flex1;
2392 		log.u_bbr.flex2 = flex2;
2393 		log.u_bbr.flex3 = flex3;
2394 		log.u_bbr.flex4 = 0;
2395 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2396 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2397 		log.u_bbr.flex8 = reason;
2398 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2399 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2400 		    &bbr->rc_inp->inp_socket->so_rcv,
2401 		    &bbr->rc_inp->inp_socket->so_snd,
2402 		    BBR_LOG_REDUCE, 0,
2403 		    0, &log, false, &bbr->rc_tv);
2404 	}
2405 }
2406 
2407 static void
2408 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2409 {
2410 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2411 		union tcp_log_stackspecific log;
2412 
2413 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2414 		log.u_bbr.flex1 = diag->p_nxt_slot;
2415 		log.u_bbr.flex2 = diag->p_cur_slot;
2416 		log.u_bbr.flex3 = diag->slot_req;
2417 		log.u_bbr.flex4 = diag->inp_hptsslot;
2418 		log.u_bbr.flex5 = diag->slot_remaining;
2419 		log.u_bbr.flex6 = diag->need_new_to;
2420 		log.u_bbr.flex7 = diag->p_hpts_active;
2421 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2422 		/* Hijack other fields as needed  */
2423 		log.u_bbr.epoch = diag->have_slept;
2424 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2425 		log.u_bbr.pkts_out = diag->co_ret;
2426 		log.u_bbr.applimited = diag->hpts_sleep_time;
2427 		log.u_bbr.delivered = diag->p_prev_slot;
2428 		log.u_bbr.inflight = diag->p_runningslot;
2429 		log.u_bbr.bw_inuse = diag->wheel_slot;
2430 		log.u_bbr.rttProp = diag->wheel_cts;
2431 		log.u_bbr.delRate = diag->maxslots;
2432 		log.u_bbr.cur_del_rate = diag->p_curtick;
2433 		log.u_bbr.cur_del_rate <<= 32;
2434 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2435 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2436 		    &bbr->rc_inp->inp_socket->so_rcv,
2437 		    &bbr->rc_inp->inp_socket->so_snd,
2438 		    BBR_LOG_HPTSDIAG, 0,
2439 		    0, &log, false, &bbr->rc_tv);
2440 	}
2441 }
2442 
2443 static void
2444 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2445     uint32_t thresh, uint32_t to)
2446 {
2447 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2448 		union tcp_log_stackspecific log;
2449 
2450 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2451 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2452 		log.u_bbr.flex2 = time_since_sent;
2453 		log.u_bbr.flex3 = srtt;
2454 		log.u_bbr.flex4 = thresh;
2455 		log.u_bbr.flex5 = to;
2456 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2457 		log.u_bbr.flex8 = mode;
2458 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2459 		    &bbr->rc_inp->inp_socket->so_rcv,
2460 		    &bbr->rc_inp->inp_socket->so_snd,
2461 		    BBR_LOG_TIMERPREP, 0,
2462 		    0, &log, false, &bbr->rc_tv);
2463 	}
2464 }
2465 
2466 static void
2467 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2468     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2469 {
2470 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2471 		union tcp_log_stackspecific log;
2472 
2473 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2474 		log.u_bbr.flex1 = usecs;
2475 		log.u_bbr.flex2 = len;
2476 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2477 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2478 		if (override)
2479 			log.u_bbr.flex5 = (1 << 2);
2480 		else
2481 			log.u_bbr.flex5 = 0;
2482 		log.u_bbr.flex6 = override;
2483 		log.u_bbr.flex7 = gain;
2484 		log.u_bbr.flex8 = mod;
2485 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2486 		    &bbr->rc_inp->inp_socket->so_rcv,
2487 		    &bbr->rc_inp->inp_socket->so_snd,
2488 		    BBR_LOG_HPTSI_CALC, 0,
2489 		    len, &log, false, &bbr->rc_tv);
2490 	}
2491 }
2492 
2493 static void
2494 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2495 {
2496 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2497 		union tcp_log_stackspecific log;
2498 
2499 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2500 
2501 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2502 		log.u_bbr.flex2 = to;
2503 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2504 		log.u_bbr.flex4 = slot;
2505 		log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2506 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2507 		log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2508 		log.u_bbr.flex8 = which;
2509 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2510 		    &bbr->rc_inp->inp_socket->so_rcv,
2511 		    &bbr->rc_inp->inp_socket->so_snd,
2512 		    BBR_LOG_TIMERSTAR, 0,
2513 		    0, &log, false, &bbr->rc_tv);
2514 	}
2515 }
2516 
2517 static void
2518 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)
2519 {
2520 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2521 		union tcp_log_stackspecific log;
2522 
2523 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2524 		log.u_bbr.flex1 = thresh;
2525 		log.u_bbr.flex2 = lro;
2526 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2527 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2528 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2529 		log.u_bbr.flex6 = srtt;
2530 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2531 		log.u_bbr.flex8 = frm;
2532 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2533 		    &bbr->rc_inp->inp_socket->so_rcv,
2534 		    &bbr->rc_inp->inp_socket->so_snd,
2535 		    BBR_LOG_THRESH_CALC, 0,
2536 		    0, &log, false, &bbr->rc_tv);
2537 	}
2538 }
2539 
2540 static void
2541 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2542 {
2543 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2544 		union tcp_log_stackspecific log;
2545 
2546 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2547 		log.u_bbr.flex1 = line;
2548 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2549 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2550 		log.u_bbr.flex4 = bbr->rc_in_persist;
2551 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2552 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2553 		log.u_bbr.flex8 = hpts_removed;
2554 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2555 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2556 		    &bbr->rc_inp->inp_socket->so_rcv,
2557 		    &bbr->rc_inp->inp_socket->so_snd,
2558 		    BBR_LOG_TIMERCANC, 0,
2559 		    0, &log, false, &bbr->rc_tv);
2560 	}
2561 }
2562 
2563 static void
2564 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2565 {
2566 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2567 		union tcp_log_stackspecific log;
2568 
2569 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2570 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2571 		log.u_bbr.flex2 = (peer_delta >> 32);
2572 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2573 		log.u_bbr.flex4 = (delta >> 32);
2574 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2575 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2576 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2577 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2578 		    &bbr->rc_inp->inp_socket->so_rcv,
2579 		    &bbr->rc_inp->inp_socket->so_snd,
2580 		    BBR_LOG_TSTMP_VAL, 0,
2581 		    0, &log, false, &bbr->rc_tv);
2582 	}
2583 }
2584 
2585 static void
2586 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)
2587 {
2588 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2589 		union tcp_log_stackspecific log;
2590 
2591 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2592 		log.u_bbr.flex1 = tsosz;
2593 		log.u_bbr.flex2 = tls;
2594 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2595 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2596 		log.u_bbr.flex5 = old_val;
2597 		log.u_bbr.flex6 = maxseg;
2598 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2599 		log.u_bbr.flex7 <<= 1;
2600 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2601 		if (hdwr)
2602 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2603 		else
2604 			log.u_bbr.flex8 = bbr->rc_use_google;
2605 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2606 		    &bbr->rc_inp->inp_socket->so_rcv,
2607 		    &bbr->rc_inp->inp_socket->so_snd,
2608 		    BBR_LOG_BBRTSO, 0,
2609 		    0, &log, false, &bbr->rc_tv);
2610 	}
2611 }
2612 
2613 static void
2614 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2615 		      uint32_t flags, uint32_t line)
2616 {
2617 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2618 		union tcp_log_stackspecific log;
2619 
2620 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2621 		log.u_bbr.flex1 = line;
2622 		log.u_bbr.flex2 = rsm->r_start;
2623 		log.u_bbr.flex3 = rsm->r_end;
2624 		log.u_bbr.flex4 = rsm->r_delivered;
2625 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2626 		log.u_bbr.flex6 = rsm->r_dupack;
2627 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2628 		log.u_bbr.flex8 = rsm->r_flags;
2629 		/* Hijack the pkts_out fids */
2630 		log.u_bbr.applimited = flags;
2631 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2632 		    &bbr->rc_inp->inp_socket->so_rcv,
2633 		    &bbr->rc_inp->inp_socket->so_snd,
2634 		    BBR_RSM_CLEARED, 0,
2635 		    0, &log, false, &bbr->rc_tv);
2636 	}
2637 }
2638 
2639 static void
2640 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2641     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2642     uint32_t flex6, uint32_t pkts_out, int flex7,
2643     uint32_t flex4, uint32_t flex1)
2644 {
2645 
2646 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2647 		union tcp_log_stackspecific log;
2648 
2649 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2650 		log.u_bbr.flex1 = flex1;
2651 		log.u_bbr.flex2 = flex2;
2652 		log.u_bbr.flex3 = flex3;
2653 		log.u_bbr.flex4 = flex4;
2654 		log.u_bbr.flex5 = flex5;
2655 		log.u_bbr.flex6 = flex6;
2656 		log.u_bbr.flex7 = flex7;
2657 		/* Hijack the pkts_out fids */
2658 		log.u_bbr.pkts_out = pkts_out;
2659 		log.u_bbr.flex8 = flex8;
2660 		if (bbr->rc_ack_was_delayed)
2661 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2662 		else
2663 			log.u_bbr.epoch = 0;
2664 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2665 		    &bbr->rc_inp->inp_socket->so_rcv,
2666 		    &bbr->rc_inp->inp_socket->so_snd,
2667 		    BBR_LOG_BBRUPD, 0,
2668 		    flex2, &log, false, &bbr->rc_tv);
2669 	}
2670 }
2671 
2672 static void
2673 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2674 	uint32_t newbw, uint32_t obw, uint32_t diff,
2675 	uint32_t tim)
2676 {
2677 	if (/*bbr_verbose_logging && */(bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2678 		union tcp_log_stackspecific log;
2679 
2680 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2681 		log.u_bbr.flex1 = reason;
2682 		log.u_bbr.flex2 = newbw;
2683 		log.u_bbr.flex3 = obw;
2684 		log.u_bbr.flex4 = diff;
2685 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2686 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2687 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2688 		log.u_bbr.pkts_out = tim;
2689 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2690 		if (bbr->rc_lt_use_bw == 0)
2691 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2692 		else
2693 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2694 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2695 		    &bbr->rc_inp->inp_socket->so_rcv,
2696 		    &bbr->rc_inp->inp_socket->so_snd,
2697 		    BBR_LOG_BWSAMP, 0,
2698 		    0, &log, false, &bbr->rc_tv);
2699 	}
2700 }
2701 
2702 static inline void
2703 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2704 {
2705 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2706 		union tcp_log_stackspecific log;
2707 
2708 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2709 		log.u_bbr.flex1 = line;
2710 		log.u_bbr.flex2 = tick;
2711 		log.u_bbr.flex3 = tp->t_maxunacktime;
2712 		log.u_bbr.flex4 = tp->t_acktime;
2713 		log.u_bbr.flex8 = event;
2714 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2715 		    &bbr->rc_inp->inp_socket->so_rcv,
2716 		    &bbr->rc_inp->inp_socket->so_snd,
2717 		    BBR_LOG_PROGRESS, 0,
2718 		    0, &log, false, &bbr->rc_tv);
2719 	}
2720 }
2721 
2722 static void
2723 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2724 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2725 			 int error)
2726 {
2727 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2728 		union tcp_log_stackspecific log;
2729 
2730 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2731 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2732 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2733 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2734 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2735 		log.u_bbr.bw_inuse = rate;
2736 		log.u_bbr.flex5 = line;
2737 		log.u_bbr.flex6 = error;
2738 		log.u_bbr.flex8 = bbr->skip_gain;
2739 		log.u_bbr.flex8 <<= 1;
2740 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2741 		log.u_bbr.flex8 <<= 1;
2742 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2743 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2744 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2745 		    &bbr->rc_inp->inp_socket->so_rcv,
2746 		    &bbr->rc_inp->inp_socket->so_snd,
2747 		    BBR_LOG_HDWR_PACE, 0,
2748 		    0, &log, false, &bbr->rc_tv);
2749 	}
2750 }
2751 
2752 static void
2753 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)
2754 {
2755 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2756 		union tcp_log_stackspecific log;
2757 
2758 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2759 		log.u_bbr.flex1 = slot;
2760 		log.u_bbr.flex2 = del_by;
2761 		log.u_bbr.flex3 = prev_delay;
2762 		log.u_bbr.flex4 = line;
2763 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2764 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2765 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2766 		log.u_bbr.flex8 = bbr->rc_in_persist;
2767 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2768 		    &bbr->rc_inp->inp_socket->so_rcv,
2769 		    &bbr->rc_inp->inp_socket->so_snd,
2770 		    BBR_LOG_BBRSND, 0,
2771 		    len, &log, false, &bbr->rc_tv);
2772 	}
2773 }
2774 
2775 static void
2776 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)
2777 {
2778 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2779 		union tcp_log_stackspecific log;
2780 
2781 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2782 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2783 		log.u_bbr.flex2 = 0;
2784 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2785 		log.u_bbr.flex4 = end;
2786 		log.u_bbr.flex5 = seq;
2787 		log.u_bbr.flex6 = t;
2788 		log.u_bbr.flex7 = match;
2789 		log.u_bbr.flex8 = flags;
2790 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2791 		    &bbr->rc_inp->inp_socket->so_rcv,
2792 		    &bbr->rc_inp->inp_socket->so_snd,
2793 		    BBR_LOG_BBRRTT, 0,
2794 		    0, &log, false, &bbr->rc_tv);
2795 	}
2796 }
2797 
2798 static void
2799 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2800 {
2801 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2802 		union tcp_log_stackspecific log;
2803 
2804 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2805 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2806 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2807 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2808 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2809 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2810 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2811 		log.u_bbr.flex7 = 0;
2812 		log.u_bbr.flex8 = entry_method;
2813 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2814 		    &bbr->rc_inp->inp_socket->so_rcv,
2815 		    &bbr->rc_inp->inp_socket->so_snd,
2816 		    BBR_LOG_EXIT_GAIN, 0,
2817 		    0, &log, false, &bbr->rc_tv);
2818 	}
2819 }
2820 
2821 static void
2822 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2823 {
2824 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2825 		union tcp_log_stackspecific log;
2826 
2827 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2828 		/* R-HU */
2829 		log.u_bbr.flex1 = 0;
2830 		log.u_bbr.flex2 = 0;
2831 		log.u_bbr.flex3 = 0;
2832 		log.u_bbr.flex4 = 0;
2833 		log.u_bbr.flex7 = 0;
2834 		log.u_bbr.flex8 = settings_desired;
2835 
2836 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2837 		    &bbr->rc_inp->inp_socket->so_rcv,
2838 		    &bbr->rc_inp->inp_socket->so_snd,
2839 		    BBR_LOG_SETTINGS_CHG, 0,
2840 		    0, &log, false, &bbr->rc_tv);
2841 	}
2842 }
2843 
2844 /*
2845  * Returns the bw from the our filter.
2846  */
2847 static inline uint64_t
2848 bbr_get_full_bw(struct tcp_bbr *bbr)
2849 {
2850 	uint64_t bw;
2851 
2852 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2853 
2854 	return (bw);
2855 }
2856 
2857 static inline void
2858 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2859 {
2860 	uint64_t calclr;
2861 	uint32_t lost, del;
2862 
2863 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2864 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2865 	else
2866 		lost = 0;
2867 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2868 	if (lost == 0)  {
2869 		calclr = 0;
2870 	} else if (del) {
2871 		calclr = lost;
2872 		calclr *= (uint64_t)1000;
2873 		calclr /= (uint64_t)del;
2874 	} else {
2875 		/* Nothing delivered? 100.0% loss */
2876 		calclr = 1000;
2877 	}
2878 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2879 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2880 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2881 	bbr->r_ctl.rc_pkt_epoch++;
2882 	if (bbr->rc_no_pacing &&
2883 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2884 		bbr->rc_no_pacing = 0;
2885 		tcp_bbr_tso_size_check(bbr, cts);
2886 	}
2887 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2888 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2889 	/* What was our loss rate */
2890 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2891 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2892 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2893 }
2894 
2895 static inline void
2896 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2897 {
2898 	uint32_t epoch_time;
2899 
2900 	/* Tick the RTT clock */
2901 	bbr->r_ctl.rc_rtt_epoch++;
2902 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2903 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2904 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2905 }
2906 
2907 static inline void
2908 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2909 {
2910 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2911 		bbr->rc_is_pkt_epoch_now = 1;
2912 	}
2913 }
2914 
2915 /*
2916  * Returns the bw from either the b/w filter
2917  * or from the lt_bw (if the connection is being
2918  * policed).
2919  */
2920 static inline uint64_t
2921 __bbr_get_bw(struct tcp_bbr *bbr)
2922 {
2923 	uint64_t bw, min_bw;
2924 	uint64_t rtt;
2925 	int gm_measure_cnt = 1;
2926 
2927 	/*
2928 	 * For startup we make, like google, a
2929 	 * minimum b/w. This is generated from the
2930 	 * IW and the rttProp. We do fall back to srtt
2931 	 * if for some reason (initial handshake) we don't
2932 	 * have a rttProp. We, in the worst case, fall back
2933 	 * to the configured min_bw (rc_initial_hptsi_bw).
2934 	 */
2935 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2936 		/* Attempt first to use rttProp */
2937 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2938 		if (rtt && (rtt < 0xffffffff)) {
2939 measure:
2940 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2941 				((uint64_t)1000000);
2942 			min_bw /= rtt;
2943 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2944 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2945 			}
2946 
2947 		} else if (bbr->rc_tp->t_srtt != 0) {
2948 			/* No rttProp, use srtt? */
2949 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2950 			goto measure;
2951 		} else {
2952 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2953 		}
2954 	} else
2955 		min_bw = 0;
2956 
2957 	if ((bbr->rc_past_init_win == 0) &&
2958 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2959 		bbr->rc_past_init_win = 1;
2960 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2961 		gm_measure_cnt = 0;
2962 	if (gm_measure_cnt &&
2963 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2964 	     (bbr->rc_past_init_win == 0))) {
2965 		/* For google we use our guess rate until we get 1 measurement */
2966 
2967 use_initial_window:
2968 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2969 		if (rtt && (rtt < 0xffffffff)) {
2970 			/*
2971 			 * We have an RTT measurement. Use that in
2972 			 * combination with our initial window to calculate
2973 			 * a b/w.
2974 			 */
2975 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2976 				((uint64_t)1000000);
2977 			bw /= rtt;
2978 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2979 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2980 			}
2981 		} else {
2982 			/* Drop back to the 40 and punt to a default */
2983 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2984 		}
2985 		if (bw < 1)
2986 			/* Probably should panic */
2987 			bw = 1;
2988 		if (bw > min_bw)
2989 			return (bw);
2990 		else
2991 			return (min_bw);
2992 	}
2993 	if (bbr->rc_lt_use_bw)
2994 		bw = bbr->r_ctl.rc_lt_bw;
2995 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2996 		bw = bbr->r_ctl.red_bw;
2997 	else
2998 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2999 	if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
3000 		/*
3001 		 * Enforce user set rate limit, keep in mind that
3002 		 * t_peakrate_thr is in B/s already
3003 		 */
3004 		bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3005 	}
3006 	if (bw == 0) {
3007 		/* We should not be at 0, go to the initial window then  */
3008 		goto use_initial_window;
3009 	}
3010 	if (bw < 1)
3011 		/* Probably should panic */
3012 		bw = 1;
3013 	if (bw < min_bw)
3014 		bw = min_bw;
3015 	return (bw);
3016 }
3017 
3018 static inline uint64_t
3019 bbr_get_bw(struct tcp_bbr *bbr)
3020 {
3021 	uint64_t bw;
3022 
3023 	bw = __bbr_get_bw(bbr);
3024 	return (bw);
3025 }
3026 
3027 static inline void
3028 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3029 {
3030 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3031 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3032 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3033 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3034 }
3035 
3036 static inline void
3037 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3038 {
3039 	bbr->rc_lt_is_sampling = 0;
3040 	bbr->rc_lt_use_bw = 0;
3041 	bbr->r_ctl.rc_lt_bw = 0;
3042 	bbr_reset_lt_bw_interval(bbr, cts);
3043 }
3044 
3045 static inline void
3046 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3047 {
3048 	uint64_t diff;
3049 
3050 	/* Do we have a previous sample? */
3051 	if (bbr->r_ctl.rc_lt_bw) {
3052 		/* Get the diff in bytes per second */
3053 		if (bbr->r_ctl.rc_lt_bw > bw)
3054 			diff = bbr->r_ctl.rc_lt_bw - bw;
3055 		else
3056 			diff = bw - bbr->r_ctl.rc_lt_bw;
3057 		if ((diff <= bbr_lt_bw_diff) ||
3058 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3059 			/* Consider us policed */
3060 			uint32_t saved_bw;
3061 
3062 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3063 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3064 			bbr->rc_lt_use_bw = 1;
3065 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3066 			/*
3067 			 * Use pkt based epoch for measuring length of
3068 			 * policer up
3069 			 */
3070 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3071 			/*
3072 			 * reason 4 is we need to start consider being
3073 			 * policed
3074 			 */
3075 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3076 			return;
3077 		}
3078 	}
3079 	bbr->r_ctl.rc_lt_bw = bw;
3080 	bbr_reset_lt_bw_interval(bbr, cts);
3081 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3082 }
3083 
3084 static void
3085 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3086 {
3087 	uint32_t ran, deduct;
3088 
3089 	ran = arc4random_uniform(bbr_rand_ot);
3090 	if (ran) {
3091 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3092 		bbr->r_ctl.rc_level_state_extra -= deduct;
3093 	}
3094 }
3095 /*
3096  * Return randomly the starting state
3097  * to use in probebw.
3098  */
3099 static uint8_t
3100 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3101 {
3102 	uint32_t ran;
3103 	uint8_t ret_val;
3104 
3105 	/* Initialize the offset to 0 */
3106 	bbr->r_ctl.rc_exta_time_gd = 0;
3107 	bbr->rc_hit_state_1 = 0;
3108 	bbr->r_ctl.rc_level_state_extra = 0;
3109 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3110 	/*
3111 	 * The math works funny here :) the return value is used to set the
3112 	 * substate and then the state change is called which increments by
3113 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3114 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3115 	 * we return 1 - 7, so we dont return 0 and end up starting in
3116 	 * state 1 (DRAIN).
3117 	 */
3118 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3119 	/* Set an epoch */
3120 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3121 		bbr_set_epoch(bbr, cts, __LINE__);
3122 
3123 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3124 	return (ret_val);
3125 }
3126 
3127 static void
3128 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3129 {
3130 	uint32_t diff, d_time;
3131 	uint64_t del_time, bw, lost, delivered;
3132 
3133 	if (bbr->r_use_policer == 0)
3134 		return;
3135 	if (bbr->rc_lt_use_bw) {
3136 		/* We are using lt bw do we stop yet? */
3137 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3138 		if (diff > bbr_lt_bw_max_rtts) {
3139 			/* Reset it all */
3140 reset_all:
3141 			bbr_reset_lt_bw_sampling(bbr, cts);
3142 			if (bbr->rc_filled_pipe) {
3143 				bbr_set_epoch(bbr, cts, __LINE__);
3144 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3145 				bbr_substate_change(bbr, cts, __LINE__, 0);
3146 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3147 				bbr_log_type_statechange(bbr, cts, __LINE__);
3148 			} else {
3149 				/*
3150 				 * This should not happen really
3151 				 * unless we remove the startup/drain
3152 				 * restrictions above.
3153 				 */
3154 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3155 				bbr_set_epoch(bbr, cts, __LINE__);
3156 				bbr->r_ctl.rc_bbr_state_time = cts;
3157 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3158 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3159 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3160 				bbr_set_state_target(bbr, __LINE__);
3161 				bbr_log_type_statechange(bbr, cts, __LINE__);
3162 			}
3163 			/* reason 0 is to stop using lt-bw */
3164 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3165 			return;
3166 		}
3167 		if (bbr_lt_intvl_fp == 0) {
3168 			/* Not doing false-positive detection */
3169 			return;
3170 		}
3171 		/* False positive detection */
3172 		if (diff == bbr_lt_intvl_fp) {
3173 			/* At bbr_lt_intvl_fp we record the lost */
3174 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3175 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3176 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3177 			/* Now is our loss rate still high? */
3178 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3179 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3180 			if ((delivered == 0) ||
3181 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3182 				/* No still below our threshold */
3183 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3184 			} else {
3185 				/* Yikes its still high, it must be a false positive */
3186 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3187 				goto reset_all;
3188 			}
3189 		}
3190 		return;
3191 	}
3192 	/*
3193 	 * Wait for the first loss before sampling, to let the policer
3194 	 * exhaust its tokens and estimate the steady-state rate allowed by
3195 	 * the policer. Starting samples earlier includes bursts that
3196 	 * over-estimate the bw.
3197 	 */
3198 	if (bbr->rc_lt_is_sampling == 0) {
3199 		/* reason 1 is to begin doing the sampling  */
3200 		if (loss_detected == 0)
3201 			return;
3202 		bbr_reset_lt_bw_interval(bbr, cts);
3203 		bbr->rc_lt_is_sampling = 1;
3204 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3205 		return;
3206 	}
3207 	/* Now how long were we delivering long term last> */
3208 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3209 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3210 	else
3211 		d_time = 0;
3212 
3213 	/* To avoid underestimates, reset sampling if we run out of data. */
3214 	if (bbr->r_ctl.r_app_limited_until) {
3215 		/* Can not measure in app-limited state */
3216 		bbr_reset_lt_bw_sampling(bbr, cts);
3217 		/* reason 2 is to reset sampling due to app limits  */
3218 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3219 		return;
3220 	}
3221 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3222 	if (diff < bbr_lt_intvl_min_rtts) {
3223 		/*
3224 		 * need more samples (we don't
3225 		 * start on a round like linux so
3226 		 * we need 1 more).
3227 		 */
3228 		/* 6 is not_enough time or no-loss */
3229 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3230 		return;
3231 	}
3232 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3233 		/*
3234 		 * For now if we wait too long, reset all sampling. We need
3235 		 * to do some research here, its possible that we should
3236 		 * base this on how much loss as occurred.. something like
3237 		 * if its under 10% (or some thresh) reset all otherwise
3238 		 * don't.  Thats for phase II I guess.
3239 		 */
3240 		bbr_reset_lt_bw_sampling(bbr, cts);
3241  		/* reason 3 is to reset sampling due too long of sampling */
3242 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3243 		return;
3244 	}
3245 	/*
3246 	 * End sampling interval when a packet is lost, so we estimate the
3247 	 * policer tokens were exhausted. Stopping the sampling before the
3248 	 * tokens are exhausted under-estimates the policed rate.
3249 	 */
3250 	if (loss_detected == 0) {
3251 		/* 6 is not_enough time or no-loss */
3252 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3253 		return;
3254 	}
3255 	/* Calculate packets lost and delivered in sampling interval. */
3256 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3257 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3258 	if ((delivered == 0) ||
3259 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3260 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3261 		return;
3262 	}
3263 	if (d_time < 1000) {
3264 		/* Not enough time. wait */
3265 		/* 6 is not_enough time or no-loss */
3266 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3267 		return;
3268 	}
3269 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3270 		/* Too long */
3271 		bbr_reset_lt_bw_sampling(bbr, cts);
3272  		/* reason 3 is to reset sampling due too long of sampling */
3273 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3274 		return;
3275 	}
3276 	del_time = d_time;
3277 	bw = delivered;
3278 	bw *= (uint64_t)USECS_IN_SECOND;
3279 	bw /= del_time;
3280 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3281 }
3282 
3283 /*
3284  * Allocate a sendmap from our zone.
3285  */
3286 static struct bbr_sendmap *
3287 bbr_alloc(struct tcp_bbr *bbr)
3288 {
3289 	struct bbr_sendmap *rsm;
3290 
3291 	BBR_STAT_INC(bbr_to_alloc);
3292 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3293 	if (rsm) {
3294 		bbr->r_ctl.rc_num_maps_alloced++;
3295 		return (rsm);
3296 	}
3297 	if (bbr->r_ctl.rc_free_cnt) {
3298 		BBR_STAT_INC(bbr_to_alloc_emerg);
3299 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3300 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3301 		bbr->r_ctl.rc_free_cnt--;
3302 		return (rsm);
3303 	}
3304 	BBR_STAT_INC(bbr_to_alloc_failed);
3305 	return (NULL);
3306 }
3307 
3308 static struct bbr_sendmap *
3309 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3310 {
3311 	if ((V_tcp_map_entries_limit > 0) &&
3312 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3313 		BBR_STAT_INC(bbr_alloc_limited);
3314 		if (!bbr->alloc_limit_reported) {
3315 			bbr->alloc_limit_reported = 1;
3316 			BBR_STAT_INC(bbr_alloc_limited_conns);
3317 		}
3318 		return (NULL);
3319 	}
3320 	return (bbr_alloc(bbr));
3321 }
3322 
3323 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3324 static struct bbr_sendmap *
3325 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3326 {
3327 	struct bbr_sendmap *rsm;
3328 
3329 	if (limit_type) {
3330 		/* currently there is only one limit type */
3331 		if (V_tcp_map_split_limit > 0 &&
3332 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3333 			BBR_STAT_INC(bbr_split_limited);
3334 			if (!bbr->alloc_limit_reported) {
3335 				bbr->alloc_limit_reported = 1;
3336 				BBR_STAT_INC(bbr_alloc_limited_conns);
3337 			}
3338 			return (NULL);
3339 		}
3340 	}
3341 
3342 	/* allocate and mark in the limit type, if set */
3343 	rsm = bbr_alloc(bbr);
3344 	if (rsm != NULL && limit_type) {
3345 		rsm->r_limit_type = limit_type;
3346 		bbr->r_ctl.rc_num_split_allocs++;
3347 	}
3348 	return (rsm);
3349 }
3350 
3351 static void
3352 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3353 {
3354 	if (rsm->r_limit_type) {
3355 		/* currently there is only one limit type */
3356 		bbr->r_ctl.rc_num_split_allocs--;
3357 	}
3358 	if (rsm->r_is_smallmap)
3359 		bbr->r_ctl.rc_num_small_maps_alloced--;
3360 	if (bbr->r_ctl.rc_tlp_send == rsm)
3361 		bbr->r_ctl.rc_tlp_send = NULL;
3362 	if (bbr->r_ctl.rc_resend == rsm) {
3363 		bbr->r_ctl.rc_resend = NULL;
3364 	}
3365 	if (bbr->r_ctl.rc_next == rsm)
3366 		bbr->r_ctl.rc_next = NULL;
3367 	if (bbr->r_ctl.rc_sacklast == rsm)
3368 		bbr->r_ctl.rc_sacklast = NULL;
3369 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3370 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3371 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3372 		rsm->r_limit_type = 0;
3373 		bbr->r_ctl.rc_free_cnt++;
3374 		return;
3375 	}
3376 	bbr->r_ctl.rc_num_maps_alloced--;
3377 	uma_zfree(bbr_zone, rsm);
3378 }
3379 
3380 /*
3381  * Returns the BDP.
3382  */
3383 static uint64_t
3384 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3385 	/*
3386 	 * Calculate the bytes in flight needed given the bw (in bytes per
3387 	 * second) and the specifyed rtt in useconds. We need to put out the
3388 	 * returned value per RTT to match that rate. Gain will normally
3389 	 * raise it up from there.
3390 	 *
3391 	 * This should not overflow as long as the bandwidth is below 1
3392 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3393 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3394 	 */
3395 	uint64_t usec_per_sec;
3396 
3397 	usec_per_sec = USECS_IN_SECOND;
3398 	return ((rtt * bw) / usec_per_sec);
3399 }
3400 
3401 /*
3402  * Return the initial cwnd.
3403  */
3404 static uint32_t
3405 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3406 {
3407 	uint32_t i_cwnd;
3408 
3409 	if (bbr->rc_init_win) {
3410 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3411 	} else if (V_tcp_initcwnd_segments)
3412 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3413 		    max(2 * tp->t_maxseg, 14600));
3414 	else if (V_tcp_do_rfc3390)
3415 		i_cwnd = min(4 * tp->t_maxseg,
3416 		    max(2 * tp->t_maxseg, 4380));
3417 	else {
3418 		/* Per RFC5681 Section 3.1 */
3419 		if (tp->t_maxseg > 2190)
3420 			i_cwnd = 2 * tp->t_maxseg;
3421 		else if (tp->t_maxseg > 1095)
3422 			i_cwnd = 3 * tp->t_maxseg;
3423 		else
3424 			i_cwnd = 4 * tp->t_maxseg;
3425 	}
3426 	return (i_cwnd);
3427 }
3428 
3429 /*
3430  * Given a specified gain, return the target
3431  * cwnd based on that gain.
3432  */
3433 static uint32_t
3434 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3435 {
3436 	uint64_t bdp, rtt;
3437 	uint32_t cwnd;
3438 
3439 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3440 	    (bbr_get_full_bw(bbr) == 0)) {
3441 		/* No measurements yet */
3442 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3443 	}
3444 	/*
3445 	 * Get bytes per RTT needed (rttProp is normally in
3446 	 * bbr_cwndtarget_rtt_touse)
3447 	 */
3448 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3449 	/* Get the bdp from the two values */
3450 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3451 	/* Now apply the gain */
3452 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3453 
3454 	return (cwnd);
3455 }
3456 
3457 static uint32_t
3458 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3459 {
3460 	uint32_t cwnd, mss;
3461 
3462 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3463 	/* Get the base cwnd with gain rounded to a mss */
3464 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3465 	/*
3466 	 * Add in N (2 default since we do not have a
3467 	 * fq layer to trap packets in) quanta's per the I-D
3468 	 * section 4.2.3.2 quanta adjust.
3469 	 */
3470 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3471 	if (bbr->rc_use_google) {
3472 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3473 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3474 			/*
3475 			 * The linux implementation adds
3476 			 * an extra 2 x mss in gain cycle which
3477 			 * is documented no-where except in the code.
3478 			 * so we add more for Neal undocumented feature
3479 			 */
3480 			cwnd += 2 * mss;
3481 		}
3482  		if ((cwnd / mss) & 0x1) {
3483 			/* Round up for odd num mss */
3484 			cwnd += mss;
3485 		}
3486 	}
3487 	/* Are we below the min cwnd? */
3488 	if (cwnd < get_min_cwnd(bbr))
3489 		return (get_min_cwnd(bbr));
3490 	return (cwnd);
3491 }
3492 
3493 static uint16_t
3494 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3495 {
3496 	if (gain < 1)
3497 		gain = 1;
3498 	return (gain);
3499 }
3500 
3501 static uint32_t
3502 bbr_get_header_oh(struct tcp_bbr *bbr)
3503 {
3504 	int seg_oh;
3505 
3506 	seg_oh = 0;
3507 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3508 		/* Do we include TCP overhead? */
3509 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3510 	}
3511 	if (bbr->r_ctl.rc_inc_ip_oh) {
3512 		/* Do we include IP overhead? */
3513 #ifdef INET6
3514 		if (bbr->r_is_v6) {
3515 			seg_oh += sizeof(struct ip6_hdr);
3516 		} else
3517 #endif
3518 		{
3519 
3520 #ifdef INET
3521 			seg_oh += sizeof(struct ip);
3522 #endif
3523 		}
3524 	}
3525 	if (bbr->r_ctl.rc_inc_enet_oh) {
3526 		/* Do we include the ethernet overhead?  */
3527 		seg_oh += sizeof(struct ether_header);
3528 	}
3529 	return(seg_oh);
3530 }
3531 
3532 static uint32_t
3533 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3534 {
3535 	uint64_t divor, res, tim;
3536 
3537 	if (useconds_time == 0)
3538 		return (0);
3539 	gain = bbr_gain_adjust(bbr, gain);
3540 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3541 	tim = useconds_time;
3542 	res = (tim * bw * gain) / divor;
3543 	if (res == 0)
3544 		res = 1;
3545 	return ((uint32_t)res);
3546 }
3547 
3548 /*
3549  * Given a gain and a length return the delay in useconds that
3550  * should be used to evenly space out packets
3551  * on the connection (based on the gain factor).
3552  */
3553 static uint32_t
3554 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3555 {
3556 	uint64_t bw, lentim, res;
3557 	uint32_t usecs, srtt, over = 0;
3558 	uint32_t seg_oh, num_segs, maxseg;
3559 
3560 	if (len == 0)
3561 		return (0);
3562 
3563 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3564 	num_segs = (len + maxseg - 1) / maxseg;
3565 	if (bbr->rc_use_google == 0) {
3566 		seg_oh = bbr_get_header_oh(bbr);
3567 		len += (num_segs * seg_oh);
3568 	}
3569 	gain = bbr_gain_adjust(bbr, gain);
3570 	bw = bbr_get_bw(bbr);
3571 	if (bbr->rc_use_google) {
3572 		uint64_t cbw;
3573 
3574 		/*
3575 		 * Reduce the b/w by the google discount
3576 		 * factor 10 = 1%.
3577 		 */
3578 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3579 		cbw /= (uint64_t)1000;
3580 		/* We don't apply a discount if it results in 0 */
3581 		if (cbw > 0)
3582 			bw = cbw;
3583 	}
3584 	lentim = ((uint64_t)len *
3585 		  (uint64_t)USECS_IN_SECOND *
3586 		  (uint64_t)BBR_UNIT);
3587 	res = lentim / ((uint64_t)gain * bw);
3588 	if (res == 0)
3589 		res = 1;
3590 	usecs = (uint32_t)res;
3591 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3592 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3593 	    (bbr->rc_use_google == 0) &&
3594 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3595 		/*
3596 		 * We cannot let the delay be more than 1/2 the srtt time.
3597 		 * Otherwise we cannot pace out or send properly.
3598 		 */
3599 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3600 		BBR_STAT_INC(bbr_hpts_min_time);
3601 	}
3602 	if (!nolog)
3603 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3604 	return (usecs);
3605 }
3606 
3607 static void
3608 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3609 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3610 {
3611 	INP_WLOCK_ASSERT(tp->t_inpcb);
3612 	uint64_t bw;
3613 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3614 	int32_t meth;
3615 
3616 #ifdef STATS
3617 	if ((tp->t_flags & TF_GPUTINPROG) &&
3618 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3619 		/*
3620 		 * Strech acks and compressed acks will cause this to
3621 		 * oscillate but we are doing it the same way as the main
3622 		 * stack so it will be compariable (though possibly not
3623 		 * ideal).
3624 		 */
3625 		int32_t cgput;
3626 		int64_t gput, time_stamp;
3627 
3628 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3629 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3630 		cgput = gput / time_stamp;
3631 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3632 					 cgput);
3633 		if (tp->t_stats_gput_prev > 0)
3634 			stats_voi_update_abs_s32(tp->t_stats,
3635 						 VOI_TCP_GPUT_ND,
3636 						 ((gput - tp->t_stats_gput_prev) * 100) /
3637 						 tp->t_stats_gput_prev);
3638 		tp->t_flags &= ~TF_GPUTINPROG;
3639 		tp->t_stats_gput_prev = cgput;
3640 	}
3641 #endif
3642 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3643 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3644 		/* We don't change anything in probe-rtt */
3645 		return;
3646 	}
3647 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3648 	saved_bytes = bytes_this_ack;
3649 	bytes_this_ack += sack_changed;
3650 	if (bytes_this_ack > prev_acked) {
3651 		bytes_this_ack -= prev_acked;
3652 		/*
3653 		 * A byte ack'd gives us a full mss
3654 		 * to be like linux i.e. they count packets.
3655 		 */
3656 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3657 			bytes_this_ack = maxseg;
3658 	} else {
3659 		/* Unlikely */
3660 		bytes_this_ack = 0;
3661 	}
3662 	cwnd = tp->snd_cwnd;
3663 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3664 	if (bw)
3665 		target_cwnd = bbr_get_target_cwnd(bbr,
3666 						  bw,
3667 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3668 	else
3669 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3670 	if (IN_RECOVERY(tp->t_flags) &&
3671 	    (bbr->bbr_prev_in_rec == 0)) {
3672 		/*
3673 		 * We are entering recovery and
3674 		 * thus packet conservation.
3675 		 */
3676 		bbr->pkt_conservation = 1;
3677 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3678 		cwnd = ctf_flight_size(tp,
3679 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3680 			bytes_this_ack;
3681 	}
3682 	if (IN_RECOVERY(tp->t_flags)) {
3683 		uint32_t flight;
3684 
3685 		bbr->bbr_prev_in_rec = 1;
3686 		if (cwnd > losses) {
3687 			cwnd -= losses;
3688 			if (cwnd < maxseg)
3689 				cwnd = maxseg;
3690 		} else
3691 			cwnd = maxseg;
3692 		flight = ctf_flight_size(tp,
3693 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3694 		bbr_log_type_cwndupd(bbr, flight, 0,
3695 				     losses, 10, 0, 0, line);
3696 		if (bbr->pkt_conservation) {
3697 			uint32_t time_in;
3698 
3699 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3700 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3701 			else
3702 				time_in = 0;
3703 
3704 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3705 				/* Clear packet conservation after an rttProp */
3706 				bbr->pkt_conservation = 0;
3707 			} else {
3708 				if ((flight + bytes_this_ack) > cwnd)
3709 					cwnd = flight + bytes_this_ack;
3710 				if (cwnd < get_min_cwnd(bbr))
3711 					cwnd = get_min_cwnd(bbr);
3712 				tp->snd_cwnd = cwnd;
3713 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3714 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3715 				return;
3716 			}
3717 		}
3718 	} else
3719 		bbr->bbr_prev_in_rec = 0;
3720 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3721 		bbr->r_ctl.restrict_growth--;
3722 		if (bytes_this_ack > maxseg)
3723 			bytes_this_ack = maxseg;
3724 	}
3725 	if (bbr->rc_filled_pipe) {
3726 		/*
3727 		 * Here we have exited startup and filled the pipe. We will
3728 		 * thus allow the cwnd to shrink to the target. We hit here
3729 		 * mostly.
3730 		 */
3731 		uint32_t s_cwnd;
3732 
3733 		meth = 2;
3734 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3735 		if (s_cwnd > cwnd)
3736 			cwnd = s_cwnd;
3737 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3738 			cwnd = s_cwnd;
3739 	} else {
3740 		/*
3741 		 * Here we are still in startup, we increase cwnd by what
3742 		 * has been acked.
3743 		 */
3744 		if ((cwnd < target_cwnd) ||
3745 		    (bbr->rc_past_init_win == 0)) {
3746 			meth = 3;
3747 			cwnd += bytes_this_ack;
3748 		} else {
3749 			/*
3750 			 * Method 4 means we are at target so no gain in
3751 			 * startup and past the initial window.
3752 			 */
3753 			meth = 4;
3754 		}
3755 	}
3756 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3757 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3758 }
3759 
3760 static void
3761 tcp_bbr_partialack(struct tcpcb *tp)
3762 {
3763 	struct tcp_bbr *bbr;
3764 
3765 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3766 	INP_WLOCK_ASSERT(tp->t_inpcb);
3767 	if (ctf_flight_size(tp,
3768 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3769 	    tp->snd_cwnd) {
3770 		bbr->r_wanted_output = 1;
3771 	}
3772 }
3773 
3774 static void
3775 bbr_post_recovery(struct tcpcb *tp)
3776 {
3777 	struct tcp_bbr *bbr;
3778 	uint32_t  flight;
3779 
3780 	INP_WLOCK_ASSERT(tp->t_inpcb);
3781 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3782 	/*
3783 	 * Here we just exit recovery.
3784 	 */
3785 	EXIT_RECOVERY(tp->t_flags);
3786 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3787 	bbr->r_recovery_bw = 0;
3788 	tp->snd_recover = tp->snd_una;
3789 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3790 	bbr->pkt_conservation = 0;
3791 	if (bbr->rc_use_google == 0) {
3792 		/*
3793 		 * For non-google mode lets
3794 		 * go ahead and make sure we clear
3795 		 * the recovery state so if we
3796 		 * bounce back in to recovery we
3797 		 * will do PC.
3798 		 */
3799 		bbr->bbr_prev_in_rec = 0;
3800 	}
3801 	bbr_log_type_exit_rec(bbr);
3802 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3803 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3804 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3805 	} else {
3806 		/* For probe-rtt case lets fix up its saved_cwnd */
3807 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3808 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3809 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3810 		}
3811 	}
3812 	flight = ctf_flight_size(tp,
3813 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3814 	if ((bbr->rc_use_google == 0) &&
3815 	    bbr_do_red) {
3816 		uint64_t val, lr2use;
3817 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3818 		uint32_t *cwnd_p;
3819 
3820 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3821 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3822 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3823 			ratio = (uint32_t)val;
3824 		} else
3825 			ratio = 1000;
3826 
3827 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3828 				     bbr->r_ctl.recovery_lr, 21,
3829 				     ratio,
3830 				     bbr->r_ctl.rc_red_cwnd_pe,
3831 				     __LINE__);
3832 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3833 			goto done;
3834 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3835 		     bbr_prtt_slam_cwnd) ||
3836 		    (bbr_sub_drain_slam_cwnd &&
3837 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3838 		     bbr->rc_hit_state_1 &&
3839 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3840 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3841 		     bbr_slam_cwnd_in_main_drain)) {
3842 			/*
3843 			 * Here we must poke at the saved cwnd
3844 			 * as well as the cwnd.
3845 			 */
3846 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3847 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3848 		} else {
3849  			cwnd = tp->snd_cwnd;
3850 			cwnd_p = &tp->snd_cwnd;
3851 		}
3852 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3853 		/* Add the overall lr with the recovery lr */
3854 		if (bbr->r_ctl.rc_lost == 0)
3855 			lr2use = 0;
3856 		else if (bbr->r_ctl.rc_delivered == 0)
3857 			lr2use = 1000;
3858 		else {
3859 			lr2use = bbr->r_ctl.rc_lost * 1000;
3860 			lr2use /= bbr->r_ctl.rc_delivered;
3861 		}
3862 		lr2use += bbr->r_ctl.recovery_lr;
3863 		acks_inflight = (flight / (maxseg * 2));
3864 		if (bbr_red_scale) {
3865 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3866 			lr2use /= bbr_red_scale;
3867 			if ((bbr_red_growth_restrict) &&
3868 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3869 			    bbr->r_ctl.restrict_growth += acks_inflight;
3870 		}
3871 		if (lr2use) {
3872 			val = (uint64_t)cwnd * lr2use;
3873 			val /= 1000;
3874 			if (cwnd > val)
3875 				newcwnd = roundup((cwnd - val), maxseg);
3876 			else
3877 				newcwnd = maxseg;
3878 		} else {
3879 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3880 			val /= (uint64_t)bbr_red_div;
3881 			newcwnd = roundup((uint32_t)val, maxseg);
3882 		}
3883 		/* with standard delayed acks how many acks can I expect? */
3884 		if (bbr_drop_limit == 0) {
3885 			/*
3886 			 * Anticpate how much we will
3887 			 * raise the cwnd based on the acks.
3888 			 */
3889 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3890 				/* We do enforce the min (with the acks) */
3891 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3892 			}
3893 		} else {
3894 			/*
3895 			 * A strict drop limit of N is inplace
3896 			 */
3897 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3898 				newcwnd = bbr_drop_limit * maxseg;
3899 			}
3900 		}
3901 		/* For the next N acks do we restrict the growth */
3902 		*cwnd_p = newcwnd;
3903 		if (tp->snd_cwnd > newcwnd)
3904 			tp->snd_cwnd = newcwnd;
3905 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3906 				     (uint32_t)lr2use,
3907 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3908 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3909 	}
3910 done:
3911 	bbr->r_ctl.recovery_lr = 0;
3912 	if (flight <= tp->snd_cwnd) {
3913 		bbr->r_wanted_output = 1;
3914 	}
3915 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3916 }
3917 
3918 static void
3919 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3920 {
3921 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3922 	/* Limit the drop in b/w to 1/2 our current filter. */
3923 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3924 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3925 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3926 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3927 	tcp_bbr_tso_size_check(bbr, cts);
3928 }
3929 
3930 static void
3931 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3932 {
3933 	struct tcp_bbr *bbr;
3934 
3935 	INP_WLOCK_ASSERT(tp->t_inpcb);
3936 #ifdef STATS
3937 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3938 #endif
3939 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3940 	switch (type) {
3941 	case CC_NDUPACK:
3942 		if (!IN_RECOVERY(tp->t_flags)) {
3943 			tp->snd_recover = tp->snd_max;
3944 			/* Start a new epoch */
3945 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3946 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3947 				/*
3948 				 * Move forward the lt epoch
3949 				 * so it won't count the truncated
3950 				 * epoch.
3951 				 */
3952 				bbr->r_ctl.rc_lt_epoch++;
3953 			}
3954 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3955 				/*
3956 				 * Just like the policer detection code
3957 				 * if we are in startup we must push
3958 				 * forward the last startup epoch
3959 				 * to hide the truncated PE.
3960 				 */
3961 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3962 			}
3963 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3964 			ENTER_RECOVERY(tp->t_flags);
3965 			bbr->rc_tlp_rtx_out = 0;
3966 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3967 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3968 			if (tcp_in_hpts(bbr->rc_inp) &&
3969 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3970 				/*
3971 				 * When we enter recovery, we need to restart
3972 				 * any timers. This may mean we gain an agg
3973 				 * early, which will be made up for at the last
3974 				 * rxt out.
3975 				 */
3976 				bbr->rc_timer_first = 1;
3977 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3978 			}
3979 			/*
3980 			 * Calculate a new cwnd based on to the current
3981 			 * delivery rate with no gain. We get the bdp
3982 			 * without gaining it up like we normally would and
3983 			 * we use the last cur_del_rate.
3984 			 */
3985 			if ((bbr->rc_use_google == 0) &&
3986 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3987 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3988 				tp->snd_cwnd = ctf_flight_size(tp,
3989 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3990 					(tp->t_maxseg - bbr->rc_last_options);
3991 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3992 					/* We always gate to min cwnd */
3993 					tp->snd_cwnd = get_min_cwnd(bbr);
3994 				}
3995 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3996 			}
3997 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3998 		}
3999 		break;
4000 	case CC_RTO_ERR:
4001 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
4002 		/* RTO was unnecessary, so reset everything. */
4003 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
4004 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
4005 			tp->snd_cwnd = tp->snd_cwnd_prev;
4006 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
4007 			tp->snd_recover = tp->snd_recover_prev;
4008 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
4009 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
4010 		}
4011 		tp->t_badrxtwin = 0;
4012 		break;
4013 	}
4014 }
4015 
4016 /*
4017  * Indicate whether this ack should be delayed.  We can delay the ack if
4018  * following conditions are met:
4019  *	- There is no delayed ack timer in progress.
4020  *	- Our last ack wasn't a 0-sized window. We never want to delay
4021  *	  the ack that opens up a 0-sized window.
4022  *	- LRO wasn't used for this segment. We make sure by checking that the
4023  *	  segment size is not larger than the MSS.
4024  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4025  *	  connection.
4026  *	- The data being acked is less than a full segment (a stretch ack
4027  *        of more than a segment we should ack.
4028  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4029  */
4030 #define DELAY_ACK(tp, bbr, nsegs)				\
4031 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4032 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4033 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4034 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4035 
4036 /*
4037  * Return the lowest RSM in the map of
4038  * packets still in flight that is not acked.
4039  * This should normally find on the first one
4040  * since we remove packets from the send
4041  * map after they are marked ACKED.
4042  */
4043 static struct bbr_sendmap *
4044 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4045 {
4046 	struct bbr_sendmap *rsm;
4047 
4048 	/*
4049 	 * Walk the time-order transmitted list looking for an rsm that is
4050 	 * not acked. This will be the one that was sent the longest time
4051 	 * ago that is still outstanding.
4052 	 */
4053 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4054 		if (rsm->r_flags & BBR_ACKED) {
4055 			continue;
4056 		}
4057 		goto finish;
4058 	}
4059 finish:
4060 	return (rsm);
4061 }
4062 
4063 static struct bbr_sendmap *
4064 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4065 {
4066 	struct bbr_sendmap *prsm;
4067 
4068 	/*
4069 	 * Walk the sequence order list backward until we hit and arrive at
4070 	 * the highest seq not acked. In theory when this is called it
4071 	 * should be the last segment (which it was not).
4072 	 */
4073 	prsm = rsm;
4074 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4075 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4076 			continue;
4077 		}
4078 		return (prsm);
4079 	}
4080 	return (NULL);
4081 }
4082 
4083 /*
4084  * Returns to the caller the number of microseconds that
4085  * the packet can be outstanding before we think we
4086  * should have had an ack returned.
4087  */
4088 static uint32_t
4089 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4090 {
4091 	/*
4092 	 * lro is the flag we use to determine if we have seen reordering.
4093 	 * If it gets set we have seen reordering. The reorder logic either
4094 	 * works in one of two ways:
4095 	 *
4096 	 * If reorder-fade is configured, then we track the last time we saw
4097 	 * re-ordering occur. If we reach the point where enough time as
4098 	 * passed we no longer consider reordering has occuring.
4099 	 *
4100 	 * Or if reorder-face is 0, then once we see reordering we consider
4101 	 * the connection to alway be subject to reordering and just set lro
4102 	 * to 1.
4103 	 *
4104 	 * In the end if lro is non-zero we add the extra time for
4105 	 * reordering in.
4106 	 */
4107 	int32_t lro;
4108 	uint32_t thresh, t_rxtcur;
4109 
4110 	if (srtt == 0)
4111 		srtt = 1;
4112 	if (bbr->r_ctl.rc_reorder_ts) {
4113 		if (bbr->r_ctl.rc_reorder_fade) {
4114 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4115 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4116 				if (lro == 0) {
4117 					/*
4118 					 * No time as passed since the last
4119 					 * reorder, mark it as reordering.
4120 					 */
4121 					lro = 1;
4122 				}
4123 			} else {
4124 				/* Negative time? */
4125 				lro = 0;
4126 			}
4127 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4128 				/* Turn off reordering seen too */
4129 				bbr->r_ctl.rc_reorder_ts = 0;
4130 				lro = 0;
4131 			}
4132 		} else {
4133 			/* Reodering does not fade */
4134 			lro = 1;
4135 		}
4136 	} else {
4137 		lro = 0;
4138 	}
4139 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4140 	if (lro) {
4141 		/* It must be set, if not you get 1/4 rtt */
4142 		if (bbr->r_ctl.rc_reorder_shift)
4143 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4144 		else
4145 			thresh += (srtt >> 2);
4146 	} else {
4147 		thresh += 1000;
4148 	}
4149 	/* We don't let the rack timeout be above a RTO */
4150 	if ((bbr->rc_tp)->t_srtt == 0)
4151 		t_rxtcur = BBR_INITIAL_RTO;
4152 	else
4153 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4154 	if (thresh > t_rxtcur) {
4155 		thresh = t_rxtcur;
4156 	}
4157 	/* And we don't want it above the RTO max either */
4158 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4159 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4160 	}
4161 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4162 	return (thresh);
4163 }
4164 
4165 /*
4166  * Return to the caller the amount of time in mico-seconds
4167  * that should be used for the TLP timer from the last
4168  * send time of this packet.
4169  */
4170 static uint32_t
4171 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4172     struct bbr_sendmap *rsm, uint32_t srtt,
4173     uint32_t cts)
4174 {
4175 	uint32_t thresh, len, maxseg, t_rxtcur;
4176 	struct bbr_sendmap *prsm;
4177 
4178 	if (srtt == 0)
4179 		srtt = 1;
4180 	if (bbr->rc_tlp_threshold)
4181 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4182 	else
4183 		thresh = (srtt * 2);
4184 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4185 	/* Get the previous sent packet, if any  */
4186 	len = rsm->r_end - rsm->r_start;
4187 
4188 	/* 2.1 behavior */
4189 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4190 	if (prsm && (len <= maxseg)) {
4191 		/*
4192 		 * Two packets outstanding, thresh should be (2*srtt) +
4193 		 * possible inter-packet delay (if any).
4194 		 */
4195 		uint32_t inter_gap = 0;
4196 		int idx, nidx;
4197 
4198 		idx = rsm->r_rtr_cnt - 1;
4199 		nidx = prsm->r_rtr_cnt - 1;
4200 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4201 			/* Yes it was sent later (or at the same time) */
4202 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4203 		}
4204 		thresh += inter_gap;
4205 	} else if (len <= maxseg) {
4206 		/*
4207 		 * Possibly compensate for delayed-ack.
4208 		 */
4209 		uint32_t alt_thresh;
4210 
4211 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4212 		if (alt_thresh > thresh)
4213 			thresh = alt_thresh;
4214 	}
4215 	/* Not above the current  RTO */
4216 	if (tp->t_srtt == 0)
4217 		t_rxtcur = BBR_INITIAL_RTO;
4218 	else
4219 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4220 
4221 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4222 	/* Not above an RTO */
4223 	if (thresh > t_rxtcur) {
4224 		thresh = t_rxtcur;
4225 	}
4226 	/* Not above a RTO max */
4227 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4228 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4229 	}
4230 	/* And now apply the user TLP min */
4231 	if (thresh < bbr_tlp_min) {
4232 		thresh = bbr_tlp_min;
4233 	}
4234 	return (thresh);
4235 }
4236 
4237 /*
4238  * Return one of three RTTs to use (in microseconds).
4239  */
4240 static __inline uint32_t
4241 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4242 {
4243 	uint32_t f_rtt;
4244 	uint32_t srtt;
4245 
4246 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4247 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4248 		/* We have no rtt at all */
4249 		if (bbr->rc_tp->t_srtt == 0)
4250 			f_rtt = BBR_INITIAL_RTO;
4251 		else
4252 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4253 		/*
4254 		 * Since we don't know how good the rtt is apply a
4255 		 * delayed-ack min
4256 		 */
4257 		if (f_rtt < bbr_delayed_ack_time) {
4258 			f_rtt = bbr_delayed_ack_time;
4259 		}
4260 	}
4261 	/* Take the filter version or last measured pkt-rtt */
4262 	if (rtt_type == BBR_RTT_PROP) {
4263 		srtt = f_rtt;
4264 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4265 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4266 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4267 		} else {
4268 			/* No pkt rtt yet */
4269 			srtt = f_rtt;
4270 		}
4271 	} else if (rtt_type == BBR_RTT_RACK) {
4272 		srtt = bbr->r_ctl.rc_last_rtt;
4273 		/* We need to add in any internal delay for our timer */
4274 		if (bbr->rc_ack_was_delayed)
4275 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4276 	} else if (rtt_type == BBR_SRTT) {
4277 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4278 	} else {
4279 		/* TSNH */
4280 		srtt = f_rtt;
4281 #ifdef BBR_INVARIANTS
4282 		panic("Unknown rtt request type %d", rtt_type);
4283 #endif
4284 	}
4285 	return (srtt);
4286 }
4287 
4288 static int
4289 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4290 {
4291 	uint32_t thresh;
4292 
4293 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4294 				      cts, rsm);
4295 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4296 		/* It is lost (past time) */
4297 		return (1);
4298 	}
4299 	return (0);
4300 }
4301 
4302 /*
4303  * Return a sendmap if we need to retransmit something.
4304  */
4305 static struct bbr_sendmap *
4306 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4307 {
4308 	/*
4309 	 * Check to see that we don't need to fall into recovery. We will
4310 	 * need to do so if our oldest transmit is past the time we should
4311 	 * have had an ack.
4312 	 */
4313 
4314 	struct bbr_sendmap *rsm;
4315 	int32_t idx;
4316 
4317 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4318 		/* Nothing outstanding that we know of */
4319 		return (NULL);
4320 	}
4321 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4322 	if (rsm == NULL) {
4323 		/* Nothing in the transmit map */
4324 		return (NULL);
4325 	}
4326 	if (tp->t_flags & TF_SENTFIN) {
4327 		/* Fin restricted, don't find anything once a fin is sent */
4328 		return (NULL);
4329 	}
4330 	if (rsm->r_flags & BBR_ACKED) {
4331 		/*
4332 		 * Ok the first one is acked (this really should not happen
4333 		 * since we remove the from the tmap once they are acked)
4334 		 */
4335 		rsm = bbr_find_lowest_rsm(bbr);
4336 		if (rsm == NULL)
4337 			return (NULL);
4338 	}
4339 	idx = rsm->r_rtr_cnt - 1;
4340 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4341 		/* Send timestamp is the same or less? can't be ready */
4342 		return (NULL);
4343 	}
4344 	/* Get our RTT time */
4345 	if (bbr_is_lost(bbr, rsm, cts) &&
4346 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4347 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4348 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4349 			rsm->r_flags |= BBR_MARKED_LOST;
4350 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4351 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4352 		}
4353 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4354 #ifdef BBR_INVARIANTS
4355 		if ((rsm->r_end - rsm->r_start) == 0)
4356 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4357 #endif
4358 		return (rsm);
4359 	}
4360 	return (NULL);
4361 }
4362 
4363 /*
4364  * RACK Timer, here we simply do logging and house keeping.
4365  * the normal bbr_output_wtime() function will call the
4366  * appropriate thing to check if we need to do a RACK retransmit.
4367  * We return 1, saying don't proceed with bbr_output_wtime only
4368  * when all timers have been stopped (destroyed PCB?).
4369  */
4370 static int
4371 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4372 {
4373 	/*
4374 	 * This timer simply provides an internal trigger to send out data.
4375 	 * The check_recovery_mode call will see if there are needed
4376 	 * retransmissions, if so we will enter fast-recovery. The output
4377 	 * call may or may not do the same thing depending on sysctl
4378 	 * settings.
4379 	 */
4380 	uint32_t lost;
4381 
4382 	if (bbr->rc_all_timers_stopped) {
4383 		return (1);
4384 	}
4385 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4386 		/* Its not time yet */
4387 		return (0);
4388 	}
4389 	BBR_STAT_INC(bbr_to_tot);
4390 	lost = bbr->r_ctl.rc_lost;
4391 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4392 		bbr_set_state(tp, bbr, 0);
4393 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4394 	if (bbr->r_ctl.rc_resend == NULL) {
4395 		/* Lets do the check here */
4396 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4397 	}
4398 	if (bbr_policer_call_from_rack_to)
4399 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4400 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4401 	return (0);
4402 }
4403 
4404 static __inline void
4405 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4406 {
4407 	int idx;
4408 
4409 	nrsm->r_start = start;
4410 	nrsm->r_end = rsm->r_end;
4411 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4412 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4413 	nrsm->r_flags = rsm->r_flags;
4414 	/* We don't transfer forward the SYN flag */
4415 	nrsm->r_flags &= ~BBR_HAS_SYN;
4416 	/* We move forward the FIN flag, not that this should happen */
4417 	rsm->r_flags &= ~BBR_HAS_FIN;
4418 	nrsm->r_dupack = rsm->r_dupack;
4419 	nrsm->r_rtr_bytes = 0;
4420 	nrsm->r_is_gain = rsm->r_is_gain;
4421 	nrsm->r_is_drain = rsm->r_is_drain;
4422 	nrsm->r_delivered = rsm->r_delivered;
4423 	nrsm->r_ts_valid = rsm->r_ts_valid;
4424 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4425 	nrsm->r_del_time = rsm->r_del_time;
4426 	nrsm->r_app_limited = rsm->r_app_limited;
4427 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4428 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4429 	/* We split a piece the lower section looses any just_ret flag. */
4430 	nrsm->r_bbr_state = rsm->r_bbr_state;
4431 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4432 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4433 	}
4434 	rsm->r_end = nrsm->r_start;
4435 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4436 	idx /= 8;
4437 	/* Check if we got too small */
4438 	if ((rsm->r_is_smallmap == 0) &&
4439 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4440 		bbr->r_ctl.rc_num_small_maps_alloced++;
4441 		rsm->r_is_smallmap = 1;
4442 	}
4443 	/* Check the new one as well */
4444 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4445 		bbr->r_ctl.rc_num_small_maps_alloced++;
4446 		nrsm->r_is_smallmap = 1;
4447 	}
4448 }
4449 
4450 static int
4451 bbr_sack_mergable(struct bbr_sendmap *at,
4452 		  uint32_t start, uint32_t end)
4453 {
4454 	/*
4455 	 * Given a sack block defined by
4456 	 * start and end, and a current position
4457 	 * at. Return 1 if either side of at
4458 	 * would show that the block is mergable
4459 	 * to that side. A block to be mergable
4460 	 * must have overlap with the start/end
4461 	 * and be in the SACK'd state.
4462 	 */
4463 	struct bbr_sendmap *l_rsm;
4464 	struct bbr_sendmap *r_rsm;
4465 
4466 	/* first get the either side blocks */
4467 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4468 	r_rsm = TAILQ_NEXT(at, r_next);
4469 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4470 		/* Potentially mergeable */
4471 		if ((l_rsm->r_end == start) ||
4472 		    (SEQ_LT(start, l_rsm->r_end) &&
4473 		     SEQ_GT(end, l_rsm->r_end))) {
4474 			    /*
4475 			     * map blk   |------|
4476 			     * sack blk         |------|
4477 			     * <or>
4478 			     * map blk   |------|
4479 			     * sack blk      |------|
4480 			     */
4481 			    return (1);
4482 		    }
4483 	}
4484 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4485 		/* Potentially mergeable */
4486 		if ((r_rsm->r_start == end) ||
4487 		    (SEQ_LT(start, r_rsm->r_start) &&
4488 		     SEQ_GT(end, r_rsm->r_start))) {
4489 			/*
4490 			 * map blk          |---------|
4491 			 * sack blk    |----|
4492 			 * <or>
4493 			 * map blk          |---------|
4494 			 * sack blk    |-------|
4495 			 */
4496 			return (1);
4497 		}
4498 	}
4499 	return (0);
4500 }
4501 
4502 static struct bbr_sendmap *
4503 bbr_merge_rsm(struct tcp_bbr *bbr,
4504 	      struct bbr_sendmap *l_rsm,
4505 	      struct bbr_sendmap *r_rsm)
4506 {
4507 	/*
4508 	 * We are merging two ack'd RSM's,
4509 	 * the l_rsm is on the left (lower seq
4510 	 * values) and the r_rsm is on the right
4511 	 * (higher seq value). The simplest way
4512 	 * to merge these is to move the right
4513 	 * one into the left. I don't think there
4514 	 * is any reason we need to try to find
4515 	 * the oldest (or last oldest retransmitted).
4516 	 */
4517 	l_rsm->r_end = r_rsm->r_end;
4518 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4519 		l_rsm->r_dupack = r_rsm->r_dupack;
4520 	if (r_rsm->r_rtr_bytes)
4521 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4522 	if (r_rsm->r_in_tmap) {
4523 		/* This really should not happen */
4524 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4525 	}
4526 	if (r_rsm->r_app_limited)
4527 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4528 	/* Now the flags */
4529 	if (r_rsm->r_flags & BBR_HAS_FIN)
4530 		l_rsm->r_flags |= BBR_HAS_FIN;
4531 	if (r_rsm->r_flags & BBR_TLP)
4532 		l_rsm->r_flags |= BBR_TLP;
4533 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4534 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4535 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4536 		/* This really should not happen */
4537 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4538 	}
4539 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4540 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4541 		/* Transfer the split limit to the map we free */
4542 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4543 		l_rsm->r_limit_type = 0;
4544 	}
4545 	bbr_free(bbr, r_rsm);
4546 	return(l_rsm);
4547 }
4548 
4549 /*
4550  * TLP Timer, here we simply setup what segment we want to
4551  * have the TLP expire on, the normal bbr_output_wtime() will then
4552  * send it out.
4553  *
4554  * We return 1, saying don't proceed with bbr_output_wtime only
4555  * when all timers have been stopped (destroyed PCB?).
4556  */
4557 static int
4558 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4559 {
4560 	/*
4561 	 * Tail Loss Probe.
4562 	 */
4563 	struct bbr_sendmap *rsm = NULL;
4564 	struct socket *so;
4565 	uint32_t amm;
4566 	uint32_t out, avail;
4567 	uint32_t maxseg;
4568 	int collapsed_win = 0;
4569 
4570 	if (bbr->rc_all_timers_stopped) {
4571 		return (1);
4572 	}
4573 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4574 		/* Its not time yet */
4575 		return (0);
4576 	}
4577 	if (ctf_progress_timeout_check(tp, true)) {
4578 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4579 		return (-ETIMEDOUT);	/* tcp_drop() */
4580 	}
4581 	/* Did we somehow get into persists? */
4582 	if (bbr->rc_in_persist) {
4583 		return (0);
4584 	}
4585 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4586 		bbr_set_state(tp, bbr, 0);
4587 	BBR_STAT_INC(bbr_tlp_tot);
4588 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4589 	/*
4590 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4591 	 * need to figure out how to force a full MSS segment out.
4592 	 */
4593 	so = tp->t_inpcb->inp_socket;
4594 	avail = sbavail(&so->so_snd);
4595 	out = ctf_outstanding(tp);
4596 	if (out > tp->snd_wnd) {
4597 		/* special case, we need a retransmission */
4598 		collapsed_win = 1;
4599 		goto need_retran;
4600 	}
4601 	if (avail > out) {
4602 		/* New data is available */
4603 		amm = avail - out;
4604 		if (amm > maxseg) {
4605 			amm = maxseg;
4606 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4607 			/* not enough to fill a MTU and no-delay is off */
4608 			goto need_retran;
4609 		}
4610 		/* Set the send-new override */
4611 		if ((out + amm) <= tp->snd_wnd) {
4612 			bbr->rc_tlp_new_data = 1;
4613 		} else {
4614 			goto need_retran;
4615 		}
4616 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4617 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4618 		bbr->r_ctl.rc_tlp_send = NULL;
4619 		/* cap any slots */
4620 		BBR_STAT_INC(bbr_tlp_newdata);
4621 		goto send;
4622 	}
4623 need_retran:
4624 	/*
4625 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4626 	 * optionally the first un-acked segment.
4627 	 */
4628 	if (collapsed_win == 0) {
4629 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4630 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4631 			rsm = bbr_find_high_nonack(bbr, rsm);
4632 		}
4633 		if (rsm == NULL) {
4634 			goto restore;
4635 		}
4636 	} else {
4637 		/*
4638 		 * We must find the last segment
4639 		 * that was acceptable by the client.
4640 		 */
4641 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4642 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4643 				/* Found one */
4644 				break;
4645 			}
4646 		}
4647 		if (rsm == NULL) {
4648 			/* None? if so send the first */
4649 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4650 			if (rsm == NULL)
4651 				goto restore;
4652 		}
4653 	}
4654 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4655 		/*
4656 		 * We need to split this the last segment in two.
4657 		 */
4658 		struct bbr_sendmap *nrsm;
4659 
4660 		nrsm = bbr_alloc_full_limit(bbr);
4661 		if (nrsm == NULL) {
4662 			/*
4663 			 * We can't get memory to split, we can either just
4664 			 * not split it. Or retransmit the whole piece, lets
4665 			 * do the large send (BTLP :-) ).
4666 			 */
4667 			goto go_for_it;
4668 		}
4669 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4670 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4671 		if (rsm->r_in_tmap) {
4672 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4673 			nrsm->r_in_tmap = 1;
4674 		}
4675 		rsm->r_flags &= (~BBR_HAS_FIN);
4676 		rsm = nrsm;
4677 	}
4678 go_for_it:
4679 	bbr->r_ctl.rc_tlp_send = rsm;
4680 	bbr->rc_tlp_rtx_out = 1;
4681 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4682 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4683 		tp->t_rxtshift++;
4684 	} else {
4685 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4686 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4687 	}
4688 send:
4689 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4690 		/*
4691 		 * Can't [re]/transmit a segment we have retranmitted the
4692 		 * max times. We need the retransmit timer to take over.
4693 		 */
4694 restore:
4695 		bbr->rc_tlp_new_data = 0;
4696 		bbr->r_ctl.rc_tlp_send = NULL;
4697 		if (rsm)
4698 			rsm->r_flags &= ~BBR_TLP;
4699 		BBR_STAT_INC(bbr_tlp_retran_fail);
4700 		return (0);
4701 	} else if (rsm) {
4702 		rsm->r_flags |= BBR_TLP;
4703 	}
4704 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4705 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4706 		/*
4707 		 * We have retransmitted to many times for TLP. Switch to
4708 		 * the regular RTO timer
4709 		 */
4710 		goto restore;
4711 	}
4712 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4713 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4714 	return (0);
4715 }
4716 
4717 /*
4718  * Delayed ack Timer, here we simply need to setup the
4719  * ACK_NOW flag and remove the DELACK flag. From there
4720  * the output routine will send the ack out.
4721  *
4722  * We only return 1, saying don't proceed, if all timers
4723  * are stopped (destroyed PCB?).
4724  */
4725 static int
4726 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4727 {
4728 	if (bbr->rc_all_timers_stopped) {
4729 		return (1);
4730 	}
4731 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4732 	tp->t_flags &= ~TF_DELACK;
4733 	tp->t_flags |= TF_ACKNOW;
4734 	KMOD_TCPSTAT_INC(tcps_delack);
4735 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4736 	return (0);
4737 }
4738 
4739 /*
4740  * Here we send a KEEP-ALIVE like probe to the
4741  * peer, we do not send data.
4742  *
4743  * We only return 1, saying don't proceed, if all timers
4744  * are stopped (destroyed PCB?).
4745  */
4746 static int
4747 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4748 {
4749 	struct tcptemp *t_template;
4750 	int32_t retval = 1;
4751 
4752 	if (bbr->rc_all_timers_stopped) {
4753 		return (1);
4754 	}
4755 	if (bbr->rc_in_persist == 0)
4756 		return (0);
4757 	KASSERT(tp->t_inpcb != NULL,
4758 	    ("%s: tp %p tp->t_inpcb == NULL", __func__, tp));
4759 	/*
4760 	 * Persistence timer into zero window. Force a byte to be output, if
4761 	 * possible.
4762 	 */
4763 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4764 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4765 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4766 	/*
4767 	 * Have we exceeded the user specified progress time?
4768 	 */
4769 	if (ctf_progress_timeout_check(tp, true)) {
4770 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4771 		return (-ETIMEDOUT);	/* tcp_drop() */
4772 	}
4773 	/*
4774 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4775 	 * window is closed.  After a full backoff, drop the connection if
4776 	 * the idle time (no responses to probes) reaches the maximum
4777 	 * backoff that we would use if retransmitting.
4778 	 */
4779 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4780 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4781 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4782 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4783 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4784 		return (-ETIMEDOUT);	/* tcp_drop() */
4785 	}
4786 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4787 	    tp->snd_una == tp->snd_max) {
4788 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4789 		retval = 0;
4790 		goto out;
4791 	}
4792 	/*
4793 	 * If the user has closed the socket then drop a persisting
4794 	 * connection after a much reduced timeout.
4795 	 */
4796 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4797 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4798 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4799 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4800 		return (-ETIMEDOUT);	/* tcp_drop() */
4801 	}
4802 	t_template = tcpip_maketemplate(bbr->rc_inp);
4803 	if (t_template) {
4804 		tcp_respond(tp, t_template->tt_ipgen,
4805 			    &t_template->tt_t, (struct mbuf *)NULL,
4806 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4807 		/* This sends an ack */
4808 		if (tp->t_flags & TF_DELACK)
4809 			tp->t_flags &= ~TF_DELACK;
4810 		free(t_template, M_TEMP);
4811 	}
4812 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4813 		tp->t_rxtshift++;
4814 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4815 out:
4816 	return (retval);
4817 }
4818 
4819 /*
4820  * If a keepalive goes off, we had no other timers
4821  * happening. We always return 1 here since this
4822  * routine either drops the connection or sends
4823  * out a segment with respond.
4824  */
4825 static int
4826 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4827 {
4828 	struct tcptemp *t_template;
4829 	struct inpcb *inp;
4830 
4831 	if (bbr->rc_all_timers_stopped) {
4832 		return (1);
4833 	}
4834 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4835 	inp = tp->t_inpcb;
4836 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4837 	/*
4838 	 * Keep-alive timer went off; send something or drop connection if
4839 	 * idle for too long.
4840 	 */
4841 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4842 	if (tp->t_state < TCPS_ESTABLISHED)
4843 		goto dropit;
4844 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4845 	    tp->t_state <= TCPS_CLOSING) {
4846 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4847 			goto dropit;
4848 		/*
4849 		 * Send a packet designed to force a response if the peer is
4850 		 * up and reachable: either an ACK if the connection is
4851 		 * still alive, or an RST if the peer has closed the
4852 		 * connection due to timeout or reboot. Using sequence
4853 		 * number tp->snd_una-1 causes the transmitted zero-length
4854 		 * segment to lie outside the receive window; by the
4855 		 * protocol spec, this requires the correspondent TCP to
4856 		 * respond.
4857 		 */
4858 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4859 		t_template = tcpip_maketemplate(inp);
4860 		if (t_template) {
4861 			tcp_respond(tp, t_template->tt_ipgen,
4862 			    &t_template->tt_t, (struct mbuf *)NULL,
4863 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4864 			free(t_template, M_TEMP);
4865 		}
4866 	}
4867 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4868 	return (1);
4869 dropit:
4870 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4871 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4872 	return (-ETIMEDOUT);	/* tcp_drop() */
4873 }
4874 
4875 /*
4876  * Retransmit helper function, clear up all the ack
4877  * flags and take care of important book keeping.
4878  */
4879 static void
4880 bbr_remxt_tmr(struct tcpcb *tp)
4881 {
4882 	/*
4883 	 * The retransmit timer went off, all sack'd blocks must be
4884 	 * un-acked.
4885 	 */
4886 	struct bbr_sendmap *rsm, *trsm = NULL;
4887 	struct tcp_bbr *bbr;
4888 	uint32_t cts, lost;
4889 
4890 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4891 	cts = tcp_get_usecs(&bbr->rc_tv);
4892 	lost = bbr->r_ctl.rc_lost;
4893 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4894 		bbr_set_state(tp, bbr, 0);
4895 
4896 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4897 		if (rsm->r_flags & BBR_ACKED) {
4898 			uint32_t old_flags;
4899 
4900 			rsm->r_dupack = 0;
4901 			if (rsm->r_in_tmap == 0) {
4902 				/* We must re-add it back to the tlist */
4903 				if (trsm == NULL) {
4904 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4905 				} else {
4906 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4907 				}
4908 				rsm->r_in_tmap = 1;
4909 			}
4910 			old_flags = rsm->r_flags;
4911 			rsm->r_flags |= BBR_RXT_CLEARED;
4912 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4913 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4914 		} else {
4915 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4916 			    (rsm->r_start == tp->snd_una)) {
4917 				/*
4918 				 * Special case for TCP FO. Where
4919 				 * we sent more data beyond the snd_max.
4920 				 * We don't mark that as lost and stop here.
4921 				 */
4922 				break;
4923 			}
4924 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4925 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4926 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4927 			}
4928 			if (bbr_marks_rxt_sack_passed) {
4929 				/*
4930 				 * With this option, we will rack out
4931 				 * in 1ms increments the rest of the packets.
4932 				 */
4933 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4934 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4935 			} else {
4936 				/*
4937 				 * With this option we only mark them lost
4938 				 * and remove all sack'd markings. We will run
4939 				 * another RXT or a TLP. This will cause
4940 				 * us to eventually send more based on what
4941 				 * ack's come in.
4942 				 */
4943 				rsm->r_flags |= BBR_MARKED_LOST;
4944 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4945 				rsm->r_flags &= ~BBR_SACK_PASSED;
4946 			}
4947 		}
4948 		trsm = rsm;
4949 	}
4950 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4951 	/* Clear the count (we just un-acked them) */
4952 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4953 	bbr->rc_tlp_new_data = 0;
4954 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4955 	/* zap the behindness on a rxt */
4956 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4957 	bbr->r_agg_early_set = 0;
4958 	bbr->r_ctl.rc_agg_early = 0;
4959 	bbr->rc_tlp_rtx_out = 0;
4960 	bbr->r_ctl.rc_sacked = 0;
4961 	bbr->r_ctl.rc_sacklast = NULL;
4962 	bbr->r_timer_override = 1;
4963 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4964 }
4965 
4966 /*
4967  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4968  * we will setup to retransmit the lowest seq number outstanding.
4969  */
4970 static int
4971 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4972 {
4973 	int32_t rexmt;
4974 	int32_t retval = 0;
4975 	bool isipv6;
4976 
4977 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4978 	if (bbr->rc_all_timers_stopped) {
4979 		return (1);
4980 	}
4981 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4982 	    (tp->snd_una == tp->snd_max)) {
4983 		/* Nothing outstanding .. nothing to do */
4984 		return (0);
4985 	}
4986 	/*
4987 	 * Retransmission timer went off.  Message has not been acked within
4988 	 * retransmit interval.  Back off to a longer retransmit interval
4989 	 * and retransmit one segment.
4990 	 */
4991 	if (ctf_progress_timeout_check(tp, true)) {
4992 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4993 		return (-ETIMEDOUT);	/* tcp_drop() */
4994 	}
4995 	bbr_remxt_tmr(tp);
4996 	if ((bbr->r_ctl.rc_resend == NULL) ||
4997 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4998 		/*
4999 		 * If the rwnd collapsed on
5000 		 * the one we are retransmitting
5001 		 * it does not count against the
5002 		 * rxt count.
5003 		 */
5004 		tp->t_rxtshift++;
5005 	}
5006 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5007 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
5008 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
5009 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
5010 		/* XXXGL: previously t_softerror was casted to uint16_t */
5011 		MPASS(tp->t_softerror >= 0);
5012 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
5013 		return (retval);	/* tcp_drop() */
5014 	}
5015 	if (tp->t_state == TCPS_SYN_SENT) {
5016 		/*
5017 		 * If the SYN was retransmitted, indicate CWND to be limited
5018 		 * to 1 segment in cc_conn_init().
5019 		 */
5020 		tp->snd_cwnd = 1;
5021 	} else if (tp->t_rxtshift == 1) {
5022 		/*
5023 		 * first retransmit; record ssthresh and cwnd so they can be
5024 		 * recovered if this turns out to be a "bad" retransmit. A
5025 		 * retransmit is considered "bad" if an ACK for this segment
5026 		 * is received within RTT/2 interval; the assumption here is
5027 		 * that the ACK was already in flight.  See "On Estimating
5028 		 * End-to-End Network Path Properties" by Allman and Paxson
5029 		 * for more details.
5030 		 */
5031 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5032 		if (!IN_RECOVERY(tp->t_flags)) {
5033 			tp->snd_cwnd_prev = tp->snd_cwnd;
5034 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5035 			tp->snd_recover_prev = tp->snd_recover;
5036 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5037 			tp->t_flags |= TF_PREVVALID;
5038 		} else {
5039 			tp->t_flags &= ~TF_PREVVALID;
5040 		}
5041 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5042 	} else {
5043 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5044 		tp->t_flags &= ~TF_PREVVALID;
5045 	}
5046 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5047 	if ((tp->t_state == TCPS_SYN_SENT) ||
5048 	    (tp->t_state == TCPS_SYN_RECEIVED))
5049 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5050 	else
5051 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5052 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5053 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5054 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5055 	/*
5056 	 * We enter the path for PLMTUD if connection is established or, if
5057 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5058 	 * amount of data we send is very small, we could send it in couple
5059 	 * of packets and process straight to FIN. In that case we won't
5060 	 * catch ESTABLISHED state.
5061 	 */
5062 #ifdef INET6
5063 	isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) ? true : false;
5064 #else
5065 	isipv6 = false;
5066 #endif
5067 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5068 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5069 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5070 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5071 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5072 		/*
5073 		 * Idea here is that at each stage of mtu probe (usually,
5074 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5075 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5076 		 * should take care of that.
5077 		 */
5078 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5079 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5080 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5081 		    tp->t_rxtshift % 2 == 0)) {
5082 			/*
5083 			 * Enter Path MTU Black-hole Detection mechanism: -
5084 			 * Disable Path MTU Discovery (IP "DF" bit). -
5085 			 * Reduce MTU to lower value than what we negotiated
5086 			 * with peer.
5087 			 */
5088 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5089 				/*
5090 				 * Record that we may have found a black
5091 				 * hole.
5092 				 */
5093 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5094 				/* Keep track of previous MSS. */
5095 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5096 			}
5097 			/*
5098 			 * Reduce the MSS to blackhole value or to the
5099 			 * default in an attempt to retransmit.
5100 			 */
5101 #ifdef INET6
5102 			isipv6 = bbr->r_is_v6;
5103 			if (isipv6 &&
5104 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5105 				/* Use the sysctl tuneable blackhole MSS. */
5106 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5107 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5108 			} else if (isipv6) {
5109 				/* Use the default MSS. */
5110 				tp->t_maxseg = V_tcp_v6mssdflt;
5111 				/*
5112 				 * Disable Path MTU Discovery when we switch
5113 				 * to minmss.
5114 				 */
5115 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5116 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5117 			}
5118 #endif
5119 #if defined(INET6) && defined(INET)
5120 			else
5121 #endif
5122 #ifdef INET
5123 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5124 				/* Use the sysctl tuneable blackhole MSS. */
5125 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5126 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5127 			} else {
5128 				/* Use the default MSS. */
5129 				tp->t_maxseg = V_tcp_mssdflt;
5130 				/*
5131 				 * Disable Path MTU Discovery when we switch
5132 				 * to minmss.
5133 				 */
5134 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5135 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5136 			}
5137 #endif
5138 		} else {
5139 			/*
5140 			 * If further retransmissions are still unsuccessful
5141 			 * with a lowered MTU, maybe this isn't a blackhole
5142 			 * and we restore the previous MSS and blackhole
5143 			 * detection flags. The limit '6' is determined by
5144 			 * giving each probe stage (1448, 1188, 524) 2
5145 			 * chances to recover.
5146 			 */
5147 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5148 			    (tp->t_rxtshift >= 6)) {
5149 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5150 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5151 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5152 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5153 			}
5154 		}
5155 	}
5156 	/*
5157 	 * Disable RFC1323 and SACK if we haven't got any response to our
5158 	 * third SYN to work-around some broken terminal servers (most of
5159 	 * which have hopefully been retired) that have bad VJ header
5160 	 * compression code which trashes TCP segments containing
5161 	 * unknown-to-them TCP options.
5162 	 */
5163 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5164 	    (tp->t_rxtshift == 3))
5165 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5166 	/*
5167 	 * If we backed off this far, our srtt estimate is probably bogus.
5168 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5169 	 * move the current srtt into rttvar to keep the current retransmit
5170 	 * times until then.
5171 	 */
5172 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5173 #ifdef INET6
5174 		if (bbr->r_is_v6)
5175 			in6_losing(tp->t_inpcb);
5176 		else
5177 #endif
5178 			in_losing(tp->t_inpcb);
5179 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5180 		tp->t_srtt = 0;
5181 	}
5182 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5183 	tp->snd_recover = tp->snd_max;
5184 	tp->t_flags |= TF_ACKNOW;
5185 	tp->t_rtttime = 0;
5186 
5187 	return (retval);
5188 }
5189 
5190 static int
5191 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5192 {
5193 	int32_t ret = 0;
5194 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5195 
5196 	if (timers == 0) {
5197 		return (0);
5198 	}
5199 	if (tp->t_state == TCPS_LISTEN) {
5200 		/* no timers on listen sockets */
5201 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5202 			return (0);
5203 		return (1);
5204 	}
5205 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5206 		uint32_t left;
5207 
5208 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5209 			ret = -1;
5210 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5211 			return (0);
5212 		}
5213 		if (hpts_calling == 0) {
5214 			ret = -2;
5215 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5216 			return (0);
5217 		}
5218 		/*
5219 		 * Ok our timer went off early and we are not paced false
5220 		 * alarm, go back to sleep.
5221 		 */
5222 		left = bbr->r_ctl.rc_timer_exp - cts;
5223 		ret = -3;
5224 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5225 		tcp_hpts_insert(tp->t_inpcb, HPTS_USEC_TO_SLOTS(left));
5226 		return (1);
5227 	}
5228 	bbr->rc_tmr_stopped = 0;
5229 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5230 	if (timers & PACE_TMR_DELACK) {
5231 		ret = bbr_timeout_delack(tp, bbr, cts);
5232 	} else if (timers & PACE_TMR_PERSIT) {
5233 		ret = bbr_timeout_persist(tp, bbr, cts);
5234 	} else if (timers & PACE_TMR_RACK) {
5235 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5236 		ret = bbr_timeout_rack(tp, bbr, cts);
5237 	} else if (timers & PACE_TMR_TLP) {
5238 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5239 		ret = bbr_timeout_tlp(tp, bbr, cts);
5240 	} else if (timers & PACE_TMR_RXT) {
5241 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5242 		ret = bbr_timeout_rxt(tp, bbr, cts);
5243 	} else if (timers & PACE_TMR_KEEP) {
5244 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5245 	}
5246 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5247 	return (ret);
5248 }
5249 
5250 static void
5251 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5252 {
5253 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5254 		uint8_t hpts_removed = 0;
5255 
5256 		if (tcp_in_hpts(bbr->rc_inp) &&
5257 		    (bbr->rc_timer_first == 1)) {
5258 			/*
5259 			 * If we are canceling timer's when we have the
5260 			 * timer ahead of the output being paced. We also
5261 			 * must remove ourselves from the hpts.
5262 			 */
5263 			hpts_removed = 1;
5264 			tcp_hpts_remove(bbr->rc_inp);
5265 			if (bbr->r_ctl.rc_last_delay_val) {
5266 				/* Update the last hptsi delay too */
5267 				uint32_t time_since_send;
5268 
5269 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5270 					time_since_send = cts - bbr->rc_pacer_started;
5271 				else
5272 					time_since_send = 0;
5273 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5274 					/* Cut down our slot time */
5275 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5276 				} else {
5277 					bbr->r_ctl.rc_last_delay_val = 0;
5278 				}
5279 				bbr->rc_pacer_started = cts;
5280 			}
5281 		}
5282 		bbr->rc_timer_first = 0;
5283 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5284 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5285 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5286 	}
5287 }
5288 
5289 static void
5290 bbr_timer_stop(struct tcpcb *tp, uint32_t timer_type)
5291 {
5292 	struct tcp_bbr *bbr;
5293 
5294 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5295 	bbr->rc_all_timers_stopped = 1;
5296 	return;
5297 }
5298 
5299 /*
5300  * stop all timers always returning 0.
5301  */
5302 static int
5303 bbr_stopall(struct tcpcb *tp)
5304 {
5305 	return (0);
5306 }
5307 
5308 static void
5309 bbr_timer_activate(struct tcpcb *tp, uint32_t timer_type, uint32_t delta)
5310 {
5311 	return;
5312 }
5313 
5314 /*
5315  * return true if a bbr timer (rack or tlp) is active.
5316  */
5317 static int
5318 bbr_timer_active(struct tcpcb *tp, uint32_t timer_type)
5319 {
5320 	return (0);
5321 }
5322 
5323 static uint32_t
5324 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5325 {
5326 	struct bbr_sendmap *rsm;
5327 
5328 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5329 	if ((rsm == NULL) || (u_rsm == rsm))
5330 		return (cts);
5331 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5332 }
5333 
5334 static void
5335 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5336      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5337 {
5338 	int32_t idx;
5339 
5340 	rsm->r_rtr_cnt++;
5341 	rsm->r_dupack = 0;
5342 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5343 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5344 		rsm->r_flags |= BBR_OVERMAX;
5345 	}
5346 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5347 		/* Take off the collapsed flag at rxt */
5348 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5349 	}
5350 	if (rsm->r_flags & BBR_MARKED_LOST) {
5351 		/* We have retransmitted, its no longer lost */
5352 		rsm->r_flags &= ~BBR_MARKED_LOST;
5353 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5354 	}
5355 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5356 		/*
5357 		 * We hit a RXT timer on it and
5358 		 * we cleared the "acked" flag.
5359 		 * We now have it going back into
5360 		 * flight, we can remove the cleared
5361 		 * flag and possibly do accounting on
5362 		 * this piece.
5363 		 */
5364 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5365 	}
5366 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5367 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5368 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5369 	}
5370 	idx = rsm->r_rtr_cnt - 1;
5371 	rsm->r_tim_lastsent[idx] = cts;
5372 	rsm->r_pacing_delay = pacing_time;
5373 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5374 	rsm->r_ts_valid = bbr->rc_ts_valid;
5375 	if (bbr->rc_ts_valid)
5376 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5377 	if (bbr->r_ctl.r_app_limited_until)
5378 		rsm->r_app_limited = 1;
5379 	else
5380 		rsm->r_app_limited = 0;
5381 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5382 		rsm->r_bbr_state = bbr_state_val(bbr);
5383 	else
5384 		rsm->r_bbr_state = 8;
5385 	if (rsm->r_flags & BBR_ACKED) {
5386 		/* Problably MTU discovery messing with us */
5387 		uint32_t old_flags;
5388 
5389 		old_flags = rsm->r_flags;
5390 		rsm->r_flags &= ~BBR_ACKED;
5391 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5392 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5393 		if (bbr->r_ctl.rc_sacked == 0)
5394 			bbr->r_ctl.rc_sacklast = NULL;
5395 	}
5396 	if (rsm->r_in_tmap) {
5397 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5398 	}
5399 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5400 	rsm->r_in_tmap = 1;
5401 	if (rsm->r_flags & BBR_SACK_PASSED) {
5402 		/* We have retransmitted due to the SACK pass */
5403 		rsm->r_flags &= ~BBR_SACK_PASSED;
5404 		rsm->r_flags |= BBR_WAS_SACKPASS;
5405 	}
5406 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5407 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5408 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5409 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5410 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5411 		rsm->r_is_gain = 1;
5412 		rsm->r_is_drain = 0;
5413 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5414 		rsm->r_is_drain = 1;
5415 		rsm->r_is_gain = 0;
5416 	} else {
5417 		rsm->r_is_drain = 0;
5418 		rsm->r_is_gain = 0;
5419 	}
5420 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5421 }
5422 
5423 /*
5424  * Returns 0, or the sequence where we stopped
5425  * updating. We also update the lenp to be the amount
5426  * of data left.
5427  */
5428 
5429 static uint32_t
5430 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5431     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5432 {
5433 	/*
5434 	 * We (re-)transmitted starting at rsm->r_start for some length
5435 	 * (possibly less than r_end.
5436 	 */
5437 	struct bbr_sendmap *nrsm;
5438 	uint32_t c_end;
5439 	int32_t len;
5440 
5441 	len = *lenp;
5442 	c_end = rsm->r_start + len;
5443 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5444 		/*
5445 		 * We retransmitted the whole piece or more than the whole
5446 		 * slopping into the next rsm.
5447 		 */
5448 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5449 		if (c_end == rsm->r_end) {
5450 			*lenp = 0;
5451 			return (0);
5452 		} else {
5453 			int32_t act_len;
5454 
5455 			/* Hangs over the end return whats left */
5456 			act_len = rsm->r_end - rsm->r_start;
5457 			*lenp = (len - act_len);
5458 			return (rsm->r_end);
5459 		}
5460 		/* We don't get out of this block. */
5461 	}
5462 	/*
5463 	 * Here we retransmitted less than the whole thing which means we
5464 	 * have to split this into what was transmitted and what was not.
5465 	 */
5466 	nrsm = bbr_alloc_full_limit(bbr);
5467 	if (nrsm == NULL) {
5468 		*lenp = 0;
5469 		return (0);
5470 	}
5471 	/*
5472 	 * So here we are going to take the original rsm and make it what we
5473 	 * retransmitted. nrsm will be the tail portion we did not
5474 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5475 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5476 	 * 1, 6 and the new piece will be 6, 11.
5477 	 */
5478 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5479 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5480 	nrsm->r_dupack = 0;
5481 	if (rsm->r_in_tmap) {
5482 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5483 		nrsm->r_in_tmap = 1;
5484 	}
5485 	rsm->r_flags &= (~BBR_HAS_FIN);
5486 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5487 	*lenp = 0;
5488 	return (0);
5489 }
5490 
5491 static uint64_t
5492 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5493 {
5494 	uint64_t bw;
5495 
5496 	bw = bbr_get_bw(bbr);
5497 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5498 	bw /= (uint64_t)BBR_UNIT;
5499 	return(bw);
5500 }
5501 
5502 static void
5503 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5504 		       uint64_t act_rate, uint64_t rate_wanted)
5505 {
5506 	/*
5507 	 * We could not get a full gains worth
5508 	 * of rate.
5509 	 */
5510 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5511 		/* we can't even get the real rate */
5512 		uint64_t red;
5513 
5514 		bbr->skip_gain = 1;
5515 		bbr->gain_is_limited = 0;
5516 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5517 		if (red)
5518 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5519 	} else {
5520 		/* We can use a lower gain */
5521 		bbr->skip_gain = 0;
5522 		bbr->gain_is_limited = 1;
5523 	}
5524 }
5525 
5526 static void
5527 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5528 {
5529 	const struct tcp_hwrate_limit_table *nrte;
5530 	int error, rate = -1;
5531 
5532 	if (bbr->r_ctl.crte == NULL)
5533 		return;
5534 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5535 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5536 		/* Lost our routes? */
5537 		/* Clear the way for a re-attempt */
5538 		bbr->bbr_attempt_hdwr_pace = 0;
5539 lost_rate:
5540 		bbr->gain_is_limited = 0;
5541 		bbr->skip_gain = 0;
5542 		bbr->bbr_hdrw_pacing = 0;
5543 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5544 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5545 		tcp_bbr_tso_size_check(bbr, cts);
5546 		return;
5547 	}
5548 	rate = bbr_get_hardware_rate(bbr);
5549 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5550 				   bbr->rc_tp,
5551 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5552 				   rate,
5553 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5554 				   &error, NULL);
5555 	if (nrte == NULL) {
5556 		goto lost_rate;
5557 	}
5558 	if (nrte != bbr->r_ctl.crte) {
5559 		bbr->r_ctl.crte = nrte;
5560 		if (error == 0)  {
5561 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5562 			if (bbr->r_ctl.crte->rate < rate) {
5563 				/* We have a problem */
5564 				bbr_setup_less_of_rate(bbr, cts,
5565 						       bbr->r_ctl.crte->rate, rate);
5566 			} else {
5567 				/* We are good */
5568 				bbr->gain_is_limited = 0;
5569 				bbr->skip_gain = 0;
5570 			}
5571 		} else {
5572 			/* A failure should release the tag */
5573 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5574 			bbr->gain_is_limited = 0;
5575 			bbr->skip_gain = 0;
5576 			bbr->bbr_hdrw_pacing = 0;
5577 		}
5578 		bbr_type_log_hdwr_pacing(bbr,
5579 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5580 					 rate,
5581 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5582 					 __LINE__,
5583 					 cts,
5584 					 error);
5585 	}
5586 }
5587 
5588 static void
5589 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5590 {
5591 	/*
5592 	 * If we have hardware pacing support
5593 	 * we need to factor that in for our
5594 	 * TSO size.
5595 	 */
5596 	const struct tcp_hwrate_limit_table *rlp;
5597 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5598 
5599 	if ((bbr->bbr_hdrw_pacing == 0) ||
5600 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5601 	    (bbr->r_ctl.crte == NULL))
5602 		return;
5603 	if (bbr->hw_pacing_set == 0) {
5604 		/* Not yet by the hdwr pacing count delay */
5605 		return;
5606 	}
5607 	if (bbr_hdwr_pace_adjust == 0) {
5608 		/* No adjustment */
5609 		return;
5610 	}
5611 	rlp = bbr->r_ctl.crte;
5612 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5613 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5614 	else
5615 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5616 	/*
5617 	 * So lets first get the
5618 	 * time we will take between
5619 	 * TSO sized sends currently without
5620 	 * hardware help.
5621 	 */
5622 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5623 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5624 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5625 	hdwr_delay *= rlp->time_between;
5626 	if (cur_delay > hdwr_delay)
5627 		delta = cur_delay - hdwr_delay;
5628 	else
5629 		delta = 0;
5630 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5631 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5632 			     1);
5633 	if (delta &&
5634 	    (delta < (max(rlp->time_between,
5635 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5636 		/*
5637 		 * Now lets divide by the pacing
5638 		 * time between each segment the
5639 		 * hardware sends rounding up and
5640 		 * derive a bytes from that. We multiply
5641 		 * that by bbr_hdwr_pace_adjust to get
5642 		 * more bang for our buck.
5643 		 *
5644 		 * The goal is to have the software pacer
5645 		 * waiting no more than an additional
5646 		 * pacing delay if we can (without the
5647 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5648 		 */
5649 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5650 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5651 		seg_sz *= bbr_hdwr_pace_adjust;
5652 		if (bbr_hdwr_pace_floor &&
5653 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5654 			/* Currently hardware paces
5655 			 * out rs_min_seg segments at a time.
5656 			 * We need to make sure we always send at least
5657 			 * a full burst of bbr_hdwr_pace_floor down.
5658 			 */
5659 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5660 		}
5661 		seg_sz *= maxseg;
5662 	} else if (delta == 0) {
5663 		/*
5664 		 * The highest pacing rate is
5665 		 * above our b/w gained. This means
5666 		 * we probably are going quite fast at
5667 		 * the hardware highest rate. Lets just multiply
5668 		 * the calculated TSO size by the
5669 		 * multiplier factor (its probably
5670 		 * 4 segments in the default config for
5671 		 * mlx).
5672 		 */
5673 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5674 		if (bbr_hdwr_pace_floor &&
5675 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5676 			/* Currently hardware paces
5677 			 * out rs_min_seg segments at a time.
5678 			 * We need to make sure we always send at least
5679 			 * a full burst of bbr_hdwr_pace_floor down.
5680 			 */
5681 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5682 		}
5683 	} else {
5684 		/*
5685 		 * The pacing time difference is so
5686 		 * big that the hardware will
5687 		 * pace out more rapidly then we
5688 		 * really want and then we
5689 		 * will have a long delay. Lets just keep
5690 		 * the same TSO size so its as if
5691 		 * we were not using hdwr pacing (we
5692 		 * just gain a bit of spacing from the
5693 		 * hardware if seg_sz > 1).
5694 		 */
5695 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5696 	}
5697 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5698 		new_tso = seg_sz;
5699 	else
5700 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5701 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5702 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5703 
5704 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5705 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5706 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5707 	}
5708 }
5709 
5710 static void
5711 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5712 {
5713 	uint64_t bw;
5714 	uint32_t old_tso = 0, new_tso;
5715 	uint32_t maxseg, bytes;
5716 	uint32_t tls_seg=0;
5717 	/*
5718 	 * Google/linux uses the following algorithm to determine
5719 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5720 	 *
5721 	 *  bytes = bw_in_bytes_per_second / 1000
5722 	 *  bytes = min(bytes, 64k)
5723 	 *  tso_segs = bytes / MSS
5724 	 *  if (bw < 1.2Mbs)
5725 	 *      min_tso_segs = 1
5726 	 *  else
5727 	 *	min_tso_segs = 2
5728 	 * tso_segs = max(tso_segs, min_tso_segs)
5729 	 *
5730 	 * * Note apply a device specific limit (we apply this in the
5731 	 *   tcp_m_copym).
5732 	 * Note that before the initial measurement is made google bursts out
5733 	 * a full iwnd just like new-reno/cubic.
5734 	 *
5735 	 * We do not use this algorithm. Instead we
5736 	 * use a two phased approach:
5737 	 *
5738 	 *  if ( bw <= per-tcb-cross-over)
5739 	 *     goal_tso =  calculate how much with this bw we
5740 	 *                 can send in goal-time seconds.
5741 	 *     if (goal_tso > mss)
5742 	 *         seg = goal_tso / mss
5743 	 *         tso = seg * mss
5744 	 *     else
5745 	 *         tso = mss
5746 	 *     if (tso > per-tcb-max)
5747 	 *         tso = per-tcb-max
5748 	 *  else if ( bw > 512Mbps)
5749 	 *     tso = max-tso (64k/mss)
5750 	 *  else
5751 	 *     goal_tso = bw / per-tcb-divsor
5752 	 *     seg = (goal_tso + mss-1)/mss
5753 	 *     tso = seg * mss
5754 	 *
5755 	 * if (tso < per-tcb-floor)
5756 	 *    tso = per-tcb-floor
5757 	 * if (tso > per-tcb-utter_max)
5758 	 *    tso = per-tcb-utter_max
5759 	 *
5760 	 * Note the default per-tcb-divisor is 1000 (same as google).
5761 	 * the goal cross over is 30Mbps however. To recreate googles
5762 	 * algorithm you need to set:
5763 	 *
5764 	 * cross-over = 23,168,000 bps
5765 	 * goal-time = 18000
5766 	 * per-tcb-max = 2
5767 	 * per-tcb-divisor = 1000
5768 	 * per-tcb-floor = 1
5769 	 *
5770 	 * This will get you "google bbr" behavior with respect to tso size.
5771 	 *
5772 	 * Note we do set anything TSO size until we are past the initial
5773 	 * window. Before that we gnerally use either a single MSS
5774 	 * or we use the full IW size (so we burst a IW at a time)
5775 	 */
5776 
5777 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5778 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5779 	} else {
5780 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5781 	}
5782 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5783 	if (bbr->rc_past_init_win == 0) {
5784 		/*
5785 		 * Not enough data has been acknowledged to make a
5786 		 * judgement. Set up the initial TSO based on if we
5787 		 * are sending a full IW at once or not.
5788 		 */
5789 		if (bbr->rc_use_google)
5790 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5791 		else if (bbr->bbr_init_win_cheat)
5792 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5793 		else
5794 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5795 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5796 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5797 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5798 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5799 		}
5800 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5801 			bbr_adjust_for_hw_pacing(bbr, cts);
5802 		return;
5803 	}
5804 	/**
5805 	 * Now lets set the TSO goal based on our delivery rate in
5806 	 * bytes per second. Note we only do this if
5807 	 * we have acked at least the initial cwnd worth of data.
5808 	 */
5809 	bw = bbr_get_bw(bbr);
5810 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5811 	     (bbr->rc_use_google == 0)) {
5812 		/* We clamp to one MSS in recovery */
5813 		new_tso = maxseg;
5814 	} else if (bbr->rc_use_google) {
5815 		int min_tso_segs;
5816 
5817 		/* Google considers the gain too */
5818 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5819 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5820 			bw /= BBR_UNIT;
5821 		}
5822 		bytes = bw / 1024;
5823 		if (bytes > (64 * 1024))
5824 			bytes = 64 * 1024;
5825 		new_tso = bytes / maxseg;
5826 		if (bw < ONE_POINT_TWO_MEG)
5827 			min_tso_segs = 1;
5828 		else
5829 			min_tso_segs = 2;
5830 		if (new_tso < min_tso_segs)
5831 			new_tso = min_tso_segs;
5832 		new_tso *= maxseg;
5833 	} else if (bbr->rc_no_pacing) {
5834 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5835 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5836 		/*
5837 		 * Calculate the worse case b/w TSO if we are inserting no
5838 		 * more than a delay_target number of TSO's.
5839 		 */
5840 		uint32_t tso_len, min_tso;
5841 
5842 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5843 		if (tso_len > maxseg) {
5844 			new_tso = tso_len / maxseg;
5845 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5846 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5847 			new_tso *= maxseg;
5848 		} else {
5849 			/*
5850 			 * less than a full sized frame yikes.. long rtt or
5851 			 * low bw?
5852 			 */
5853 			min_tso = bbr_minseg(bbr);
5854 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5855 				new_tso = rounddown(tso_len, min_tso);
5856 			else
5857 				new_tso = min_tso;
5858 		}
5859 	} else if (bw > FIVETWELVE_MBPS) {
5860 		/*
5861 		 * This guy is so fast b/w wise that we can TSO as large as
5862 		 * possible of segments that the NIC will allow.
5863 		 */
5864 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5865 	} else {
5866 		/*
5867 		 * This formula is based on attempting to send a segment or
5868 		 * more every bbr_hptsi_per_second. The default is 1000
5869 		 * which means you are targeting what you can send every 1ms
5870 		 * based on the peers bw.
5871 		 *
5872 		 * If the number drops to say 500, then you are looking more
5873 		 * at 2ms and you will raise how much we send in a single
5874 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5875 		 * trade off of course is you will send more at once and
5876 		 * thus tend to clump up the sends into larger "bursts"
5877 		 * building a queue.
5878 		 */
5879 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5880 		new_tso = roundup(bw, (uint64_t)maxseg);
5881 		/*
5882 		 * Gate the floor to match what our lower than 48Mbps
5883 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5884 		 * becomes the floor for this calculation.
5885 		 */
5886 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5887 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5888 	}
5889 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5890 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5891 	if (new_tso > PACE_MAX_IP_BYTES)
5892 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5893 	/* Enforce an utter maximum. */
5894 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5895 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5896 	}
5897 	if (old_tso != new_tso) {
5898 		/* Only log changes */
5899 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5900 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5901 	}
5902 	/* We have hardware pacing! */
5903 	bbr_adjust_for_hw_pacing(bbr, cts);
5904 }
5905 
5906 static void
5907 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5908     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5909     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5910     struct sockbuf *sb)
5911 {
5912 
5913 	struct bbr_sendmap *rsm, *nrsm;
5914 	register uint32_t snd_max, snd_una;
5915 	uint32_t pacing_time;
5916 	/*
5917 	 * Add to the RACK log of packets in flight or retransmitted. If
5918 	 * there is a TS option we will use the TS echoed, if not we will
5919 	 * grab a TS.
5920 	 *
5921 	 * Retransmissions will increment the count and move the ts to its
5922 	 * proper place. Note that if options do not include TS's then we
5923 	 * won't be able to effectively use the ACK for an RTT on a retran.
5924 	 *
5925 	 * Notes about r_start and r_end. Lets consider a send starting at
5926 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5927 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5928 	 * This means that r_end is actually the first sequence for the next
5929 	 * slot (11).
5930 	 *
5931 	 */
5932 	INP_WLOCK_ASSERT(tp->t_inpcb);
5933 	if (err) {
5934 		/*
5935 		 * We don't log errors -- we could but snd_max does not
5936 		 * advance in this case either.
5937 		 */
5938 		return;
5939 	}
5940 	if (th_flags & TH_RST) {
5941 		/*
5942 		 * We don't log resets and we return immediately from
5943 		 * sending
5944 		 */
5945 		*abandon = 1;
5946 		return;
5947 	}
5948 	snd_una = tp->snd_una;
5949 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5950 		/*
5951 		 * The call to bbr_log_output is made before bumping
5952 		 * snd_max. This means we can record one extra byte on a SYN
5953 		 * or FIN if seq_out is adding more on and a FIN is present
5954 		 * (and we are not resending).
5955 		 */
5956 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5957 			len++;
5958 		if (th_flags & TH_FIN)
5959 			len++;
5960 	}
5961 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5962 		/* Are sending an old segment to induce an ack (keep-alive)? */
5963 		return;
5964 	}
5965 	if (SEQ_LT(seq_out, snd_una)) {
5966 		/* huh? should we panic? */
5967 		uint32_t end;
5968 
5969 		end = seq_out + len;
5970 		seq_out = snd_una;
5971 		len = end - seq_out;
5972 	}
5973 	snd_max = tp->snd_max;
5974 	if (len == 0) {
5975 		/* We don't log zero window probes */
5976 		return;
5977 	}
5978 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5979 	/* First question is it a retransmission? */
5980 	if (seq_out == snd_max) {
5981 again:
5982 		rsm = bbr_alloc(bbr);
5983 		if (rsm == NULL) {
5984 			return;
5985 		}
5986 		rsm->r_flags = 0;
5987 		if (th_flags & TH_SYN)
5988 			rsm->r_flags |= BBR_HAS_SYN;
5989 		if (th_flags & TH_FIN)
5990 			rsm->r_flags |= BBR_HAS_FIN;
5991 		rsm->r_tim_lastsent[0] = cts;
5992 		rsm->r_rtr_cnt = 1;
5993 		rsm->r_rtr_bytes = 0;
5994 		rsm->r_start = seq_out;
5995 		rsm->r_end = rsm->r_start + len;
5996 		rsm->r_dupack = 0;
5997 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5998 		rsm->r_pacing_delay = pacing_time;
5999 		rsm->r_ts_valid = bbr->rc_ts_valid;
6000 		if (bbr->rc_ts_valid)
6001 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
6002 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
6003 		if (bbr->r_ctl.r_app_limited_until)
6004 			rsm->r_app_limited = 1;
6005 		else
6006 			rsm->r_app_limited = 0;
6007 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
6008 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
6009 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
6010 		/*
6011 		 * Here we must also add in this rsm since snd_max
6012 		 * is updated after we return from a new send.
6013 		 */
6014 		rsm->r_flight_at_send += len;
6015 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
6016 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
6017 		rsm->r_in_tmap = 1;
6018 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
6019 			rsm->r_bbr_state = bbr_state_val(bbr);
6020 		else
6021 			rsm->r_bbr_state = 8;
6022 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
6023 			rsm->r_is_gain = 1;
6024 			rsm->r_is_drain = 0;
6025 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6026 			rsm->r_is_drain = 1;
6027 			rsm->r_is_gain = 0;
6028 		} else {
6029 			rsm->r_is_drain = 0;
6030 			rsm->r_is_gain = 0;
6031 		}
6032 		return;
6033 	}
6034 	/*
6035 	 * If we reach here its a retransmission and we need to find it.
6036 	 */
6037 more:
6038 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6039 		rsm = hintrsm;
6040 		hintrsm = NULL;
6041 	} else if (bbr->r_ctl.rc_next) {
6042 		/* We have a hint from a previous run */
6043 		rsm = bbr->r_ctl.rc_next;
6044 	} else {
6045 		/* No hints sorry */
6046 		rsm = NULL;
6047 	}
6048 	if ((rsm) && (rsm->r_start == seq_out)) {
6049 		/*
6050 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6051 		 * likely case.
6052 		 */
6053 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6054 		if (len == 0) {
6055 			return;
6056 		} else {
6057 			goto more;
6058 		}
6059 	}
6060 	/* Ok it was not the last pointer go through it the hard way. */
6061 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6062 		if (rsm->r_start == seq_out) {
6063 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6064 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6065 			if (len == 0) {
6066 				return;
6067 			} else {
6068 				continue;
6069 			}
6070 		}
6071 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6072 			/* Transmitted within this piece */
6073 			/*
6074 			 * Ok we must split off the front and then let the
6075 			 * update do the rest
6076 			 */
6077 			nrsm = bbr_alloc_full_limit(bbr);
6078 			if (nrsm == NULL) {
6079 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6080 				return;
6081 			}
6082 			/*
6083 			 * copy rsm to nrsm and then trim the front of rsm
6084 			 * to not include this part.
6085 			 */
6086 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6087 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6088 			if (rsm->r_in_tmap) {
6089 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6090 				nrsm->r_in_tmap = 1;
6091 			}
6092 			rsm->r_flags &= (~BBR_HAS_FIN);
6093 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6094 			if (len == 0) {
6095 				return;
6096 			}
6097 		}
6098 	}
6099 	/*
6100 	 * Hmm not found in map did they retransmit both old and on into the
6101 	 * new?
6102 	 */
6103 	if (seq_out == tp->snd_max) {
6104 		goto again;
6105 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6106 #ifdef BBR_INVARIANTS
6107 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6108 		    seq_out, len, tp->snd_una, tp->snd_max);
6109 		printf("Starting Dump of all rack entries\n");
6110 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6111 			printf("rsm:%p start:%u end:%u\n",
6112 			    rsm, rsm->r_start, rsm->r_end);
6113 		}
6114 		printf("Dump complete\n");
6115 		panic("seq_out not found rack:%p tp:%p",
6116 		    bbr, tp);
6117 #endif
6118 	} else {
6119 #ifdef BBR_INVARIANTS
6120 		/*
6121 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6122 		 * flag)
6123 		 */
6124 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6125 		    seq_out, len, tp->snd_max, tp);
6126 #endif
6127 	}
6128 }
6129 
6130 static void
6131 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6132 {
6133 	/*
6134 	 * Collapse timeout back the cum-ack moved.
6135 	 */
6136 	tp->t_rxtshift = 0;
6137 	tp->t_softerror = 0;
6138 }
6139 
6140 static void
6141 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6142 {
6143 	bbr->rtt_valid = 1;
6144 	bbr->r_ctl.cur_rtt = rtt_usecs;
6145 	bbr->r_ctl.ts_in = tsin;
6146 	if (rsm_send_time)
6147 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6148 }
6149 
6150 static void
6151 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6152 {
6153 	/**
6154 	 * We have in our bbr control:
6155 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6156 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6157 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6158 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6159 	 *
6160 	 * Now we can calculate the time between the sends by doing:
6161 	 *
6162 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6163 	 *
6164 	 * And the peer's time between receiving them by doing:
6165 	 *
6166 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6167 	 *
6168 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6169 	 * We also may find that we can't use the timestamps if say we see
6170 	 * that the peer_delta indicates that though we may have taken 10ms to
6171 	 * pace out the data, it only saw 1ms between the two packets. This would
6172 	 * indicate that somewhere on the path is a batching entity that is giving
6173 	 * out time-slices of the actual b/w. This would mean we could not use
6174 	 * reliably the peers timestamps.
6175 	 *
6176 	 * We expect delta > peer_delta initially. Until we figure out the
6177 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6178 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6179 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6180 	 * put a 1 there. If the value is faster then ours, we will disable the
6181 	 * use of timestamps (though we could revist this later if we find it to be not
6182 	 * just an isolated one or two flows)).
6183 	 *
6184 	 * To detect the batching middle boxes we will come up with our compensation and
6185 	 * if with it in place, we find the peer is drastically off (by some margin) in
6186 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6187 	 *
6188 	 */
6189 	uint64_t delta, peer_delta, delta_up;
6190 
6191 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6192 	if (delta < bbr_min_usec_delta) {
6193 		/*
6194 		 * Have not seen a min amount of time
6195 		 * between our send times so we can
6196 		 * make a determination of the timestamp
6197 		 * yet.
6198 		 */
6199 		return;
6200 	}
6201 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6202 	if (peer_delta < bbr_min_peer_delta) {
6203 		/*
6204 		 * We may have enough in the form of
6205 		 * our delta but the peers number
6206 		 * has not changed that much. It could
6207 		 * be its clock ratio is such that
6208 		 * we need more data (10ms tick) or
6209 		 * there may be other compression scenarios
6210 		 * going on. In any event we need the
6211 		 * spread to be larger.
6212 		 */
6213 		return;
6214 	}
6215 	/* Ok lets first see which way our delta is going */
6216 	if (peer_delta > delta) {
6217 		/* Very unlikely, the peer without
6218 		 * compensation shows that it saw
6219 		 * the two sends arrive further apart
6220 		 * then we saw then in micro-seconds.
6221 		 */
6222 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6223 			/* well it looks like the peer is a micro-second clock. */
6224 			bbr->rc_ts_clock_set = 1;
6225 			bbr->r_ctl.bbr_peer_tsratio = 1;
6226 		} else {
6227 			bbr->rc_ts_cant_be_used = 1;
6228 			bbr->rc_ts_clock_set = 1;
6229 		}
6230 		return;
6231 	}
6232 	/* Ok we know that the peer_delta is smaller than our send distance */
6233 	bbr->rc_ts_clock_set = 1;
6234 	/* First question is it within the percentage that they are using usec time? */
6235 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6236 	if ((peer_delta + delta_up) >= delta) {
6237 		/* Its a usec clock */
6238 		bbr->r_ctl.bbr_peer_tsratio = 1;
6239 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6240 		return;
6241 	}
6242 	/* Ok if not usec, what about 10usec (though unlikely)? */
6243 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6244 	if (((peer_delta * 10) + delta_up) >= delta) {
6245 		bbr->r_ctl.bbr_peer_tsratio = 10;
6246 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6247 		return;
6248 	}
6249 	/* And what about 100usec (though again unlikely)? */
6250 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6251 	if (((peer_delta * 100) + delta_up) >= delta) {
6252 		bbr->r_ctl.bbr_peer_tsratio = 100;
6253 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6254 		return;
6255 	}
6256 	/* And how about 1 msec (the most likely one)? */
6257 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6258 	if (((peer_delta * 1000) + delta_up) >= delta) {
6259 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6260 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6261 		return;
6262 	}
6263 	/* Ok if not msec could it be 10 msec? */
6264 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6265 	if (((peer_delta * 10000) + delta_up) >= delta) {
6266 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6267 		return;
6268 	}
6269 	/* If we fall down here the clock tick so slowly we can't use it */
6270 	bbr->rc_ts_cant_be_used = 1;
6271 	bbr->r_ctl.bbr_peer_tsratio = 0;
6272 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6273 }
6274 
6275 /*
6276  * Collect new round-trip time estimate
6277  * and update averages and current timeout.
6278  */
6279 static void
6280 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6281 {
6282 	int32_t delta;
6283 	uint32_t rtt, tsin;
6284 	int32_t rtt_ticks;
6285 
6286 	if (bbr->rtt_valid == 0)
6287 		/* No valid sample */
6288 		return;
6289 
6290 	rtt = bbr->r_ctl.cur_rtt;
6291 	tsin = bbr->r_ctl.ts_in;
6292 	if (bbr->rc_prtt_set_ts) {
6293 		/*
6294 		 * We are to force feed the rttProp filter due
6295 		 * to an entry into PROBE_RTT. This assures
6296 		 * that the times are sync'd between when we
6297 		 * go into PROBE_RTT and the filter expiration.
6298 		 *
6299 		 * Google does not use a true filter, so they do
6300 		 * this implicitly since they only keep one value
6301 		 * and when they enter probe-rtt they update the
6302 		 * value to the newest rtt.
6303 		 */
6304 		uint32_t rtt_prop;
6305 
6306 		bbr->rc_prtt_set_ts = 0;
6307 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6308 		if (rtt > rtt_prop)
6309 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6310 		else
6311 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6312 	}
6313 	if (bbr->rc_ack_was_delayed)
6314 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6315 
6316 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6317 		bbr->r_ctl.rc_lowest_rtt = rtt;
6318 	bbr_log_rtt_sample(bbr, rtt, tsin);
6319 	if (bbr->r_init_rtt) {
6320 		/*
6321 		 * The initial rtt is not-trusted, nuke it and lets get
6322 		 * our first valid measurement in.
6323 		 */
6324 		bbr->r_init_rtt = 0;
6325 		tp->t_srtt = 0;
6326 	}
6327 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6328 		/*
6329 		 * So we have not yet figured out
6330 		 * what the peers TSTMP value is
6331 		 * in (most likely ms). We need a
6332 		 * series of cum-ack's to determine
6333 		 * this reliably.
6334 		 */
6335 		if (bbr->rc_ack_is_cumack) {
6336 			if (bbr->rc_ts_data_set) {
6337 				/* Lets attempt to determine the timestamp granularity. */
6338 				bbr_make_timestamp_determination(bbr);
6339 			} else {
6340 				bbr->rc_ts_data_set = 1;
6341 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6342 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6343 			}
6344 		} else {
6345 			/*
6346 			 * We have to have consecutive acks
6347 			 * reset any "filled" state to none.
6348 			 */
6349 			bbr->rc_ts_data_set = 0;
6350 		}
6351 	}
6352 	/* Round it up */
6353 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6354 	if (rtt_ticks == 0)
6355 		rtt_ticks = 1;
6356 	if (tp->t_srtt != 0) {
6357 		/*
6358 		 * srtt is stored as fixed point with 5 bits after the
6359 		 * binary point (i.e., scaled by 8).  The following magic is
6360 		 * equivalent to the smoothing algorithm in rfc793 with an
6361 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6362 		 * Adjust rtt to origin 0.
6363 		 */
6364 
6365 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6366 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6367 
6368 		tp->t_srtt += delta;
6369 		if (tp->t_srtt <= 0)
6370 			tp->t_srtt = 1;
6371 
6372 		/*
6373 		 * We accumulate a smoothed rtt variance (actually, a
6374 		 * smoothed mean difference), then set the retransmit timer
6375 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6376 		 * is stored as fixed point with 4 bits after the binary
6377 		 * point (scaled by 16).  The following is equivalent to
6378 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6379 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6380 		 * wired-in beta.
6381 		 */
6382 		if (delta < 0)
6383 			delta = -delta;
6384 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6385 		tp->t_rttvar += delta;
6386 		if (tp->t_rttvar <= 0)
6387 			tp->t_rttvar = 1;
6388 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
6389 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6390 	} else {
6391 		/*
6392 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6393 		 * variance to half the rtt (so our first retransmit happens
6394 		 * at 3*rtt).
6395 		 */
6396 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6397 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6398 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6399 	}
6400 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6401 	tp->t_rttupdated++;
6402 #ifdef STATS
6403 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6404 #endif
6405 	/*
6406 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6407 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6408 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6409 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6410 	 * uncertainty in the firing of the timer.  The bias will give us
6411 	 * exactly the 1.5 tick we need.  But, because the bias is
6412 	 * statistical, we have to test that we don't drop below the minimum
6413 	 * feasible timer (which is 2 ticks).
6414 	 */
6415 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6416 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6417 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6418 
6419 	/*
6420 	 * We received an ack for a packet that wasn't retransmitted; it is
6421 	 * probably safe to discard any error indications we've received
6422 	 * recently.  This isn't quite right, but close enough for now (a
6423 	 * route might have failed after we sent a segment, and the return
6424 	 * path might not be symmetrical).
6425 	 */
6426 	tp->t_softerror = 0;
6427 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6428 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6429 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6430 }
6431 
6432 static void
6433 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6434 {
6435 	bbr->r_ctl.rc_rtt_shrinks = cts;
6436 	if (bbr_can_force_probertt &&
6437 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6438 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6439 		/*
6440 		 * We should enter probe-rtt its been too long
6441 		 * since we have been there.
6442 		 */
6443 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6444 	} else
6445 		bbr_check_probe_rtt_limits(bbr, cts);
6446 }
6447 
6448 static void
6449 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6450 {
6451 	uint64_t orig_bw;
6452 
6453 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6454 		/* We never apply a zero measurement */
6455 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6456 				    0, 0, 0, 0, 0, 0);
6457 		return;
6458 	}
6459 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6460 		bbr->r_ctl.r_measurement_count++;
6461 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6462 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6463 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6464 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6465 			    0, 0, 0, 0, 0, 0);
6466 	if (orig_bw &&
6467 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6468 		if (bbr->bbr_hdrw_pacing) {
6469 			/*
6470 			 * Apply a new rate to the hardware
6471 			 * possibly.
6472 			 */
6473 			bbr_update_hardware_pacing_rate(bbr, cts);
6474 		}
6475 		bbr_set_state_target(bbr, __LINE__);
6476 		tcp_bbr_tso_size_check(bbr, cts);
6477 		if (bbr->r_recovery_bw)  {
6478 			bbr_setup_red_bw(bbr, cts);
6479 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6480 		}
6481 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6482 		tcp_bbr_tso_size_check(bbr, cts);
6483 }
6484 
6485 static void
6486 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6487 {
6488 	if (bbr->rc_in_persist == 0) {
6489 		/* We log only when not in persist */
6490 		/* Translate to a Bytes Per Second */
6491 		uint64_t tim, bw, ts_diff, ts_bw;
6492 		uint32_t delivered;
6493 
6494 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6495 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6496 		else
6497 			tim = 1;
6498 		/*
6499 		 * Now that we have processed the tim (skipping the sample
6500 		 * or possibly updating the time, go ahead and
6501 		 * calculate the cdr.
6502 		 */
6503 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6504 		bw = (uint64_t)delivered;
6505 		bw *= (uint64_t)USECS_IN_SECOND;
6506 		bw /= tim;
6507 		if (bw == 0) {
6508 			/* We must have a calculatable amount */
6509 			return;
6510 		}
6511 		/*
6512 		 * If we are using this b/w shove it in now so we
6513 		 * can see in the trace viewer if it gets over-ridden.
6514 		 */
6515 		if (rsm->r_ts_valid &&
6516 		    bbr->rc_ts_valid &&
6517 		    bbr->rc_ts_clock_set &&
6518 		    (bbr->rc_ts_cant_be_used == 0) &&
6519 		    bbr->rc_use_ts_limit) {
6520 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6521 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6522 			if ((delivered == 0) ||
6523 			    (rtt < 1000)) {
6524 				/* Can't use the ts */
6525 				bbr_log_type_bbrupd(bbr, 61, cts,
6526 						    ts_diff,
6527 						    bbr->r_ctl.last_inbound_ts,
6528 						    rsm->r_del_ack_ts, 0,
6529 						    0, 0, 0, delivered);
6530 			} else {
6531 				ts_bw = (uint64_t)delivered;
6532 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6533 				ts_bw /= ts_diff;
6534 				bbr_log_type_bbrupd(bbr, 62, cts,
6535 						    (ts_bw >> 32),
6536 						    (ts_bw & 0xffffffff), 0, 0,
6537 						    0, 0, ts_diff, delivered);
6538 				if ((bbr->ts_can_raise) &&
6539 				    (ts_bw > bw)) {
6540 					bbr_log_type_bbrupd(bbr, 8, cts,
6541 							    delivered,
6542 							    ts_diff,
6543 							    (bw >> 32),
6544 							    (bw & 0x00000000ffffffff),
6545 							    0, 0, 0, 0);
6546 					bw = ts_bw;
6547 				} else if (ts_bw && (ts_bw < bw)) {
6548 					bbr_log_type_bbrupd(bbr, 7, cts,
6549 							    delivered,
6550 							    ts_diff,
6551 							    (bw >> 32),
6552 							    (bw & 0x00000000ffffffff),
6553 							    0, 0, 0, 0);
6554 					bw = ts_bw;
6555 				}
6556 			}
6557 		}
6558 		if (rsm->r_first_sent_time &&
6559 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6560 			uint64_t sbw, sti;
6561 			/*
6562 			 * We use what was in flight at the time of our
6563 			 * send  and the size of this send to figure
6564 			 * out what we have been sending at (amount).
6565 			 * For the time we take from the time of
6566 			 * the send of the first send outstanding
6567 			 * until this send plus this sends pacing
6568 			 * time. This gives us a good calculation
6569 			 * as to the rate we have been sending at.
6570 			 */
6571 
6572 			sbw = (uint64_t)(rsm->r_flight_at_send);
6573 			sbw *= (uint64_t)USECS_IN_SECOND;
6574 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6575 			sti += rsm->r_pacing_delay;
6576 			sbw /= sti;
6577 			if (sbw < bw) {
6578 				bbr_log_type_bbrupd(bbr, 6, cts,
6579 						    delivered,
6580 						    (uint32_t)sti,
6581 						    (bw >> 32),
6582 						    (uint32_t)bw,
6583 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6584 						    (uint32_t)sbw);
6585 				bw = sbw;
6586 			}
6587 		}
6588 		/* Use the google algorithm for b/w measurements */
6589 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6590 		if ((rsm->r_app_limited == 0) ||
6591 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6592 			tcp_bbr_commit_bw(bbr, cts);
6593 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6594 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6595 		}
6596 	}
6597 }
6598 
6599 static void
6600 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6601 {
6602 	if (bbr->rc_in_persist == 0) {
6603 		/* We log only when not in persist */
6604 		/* Translate to a Bytes Per Second */
6605 		uint64_t tim, bw;
6606 		uint32_t delivered;
6607 		int no_apply = 0;
6608 
6609 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6610 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6611 		else
6612 			tim = 1;
6613 		/*
6614 		 * Now that we have processed the tim (skipping the sample
6615 		 * or possibly updating the time, go ahead and
6616 		 * calculate the cdr.
6617 		 */
6618 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6619 		bw = (uint64_t)delivered;
6620 		bw *= (uint64_t)USECS_IN_SECOND;
6621 		bw /= tim;
6622 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6623 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6624 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6625 
6626 			no_apply = 1;
6627 		}
6628 		/*
6629 		 * If we are using this b/w shove it in now so we
6630 		 * can see in the trace viewer if it gets over-ridden.
6631 		 */
6632 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6633 		/* Gate by the sending rate */
6634 		if (rsm->r_first_sent_time &&
6635 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6636 			uint64_t sbw, sti;
6637 			/*
6638 			 * We use what was in flight at the time of our
6639 			 * send  and the size of this send to figure
6640 			 * out what we have been sending at (amount).
6641 			 * For the time we take from the time of
6642 			 * the send of the first send outstanding
6643 			 * until this send plus this sends pacing
6644 			 * time. This gives us a good calculation
6645 			 * as to the rate we have been sending at.
6646 			 */
6647 
6648 			sbw = (uint64_t)(rsm->r_flight_at_send);
6649 			sbw *= (uint64_t)USECS_IN_SECOND;
6650 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6651 			sti += rsm->r_pacing_delay;
6652 			sbw /= sti;
6653 			if (sbw < bw) {
6654 				bbr_log_type_bbrupd(bbr, 6, cts,
6655 						    delivered,
6656 						    (uint32_t)sti,
6657 						    (bw >> 32),
6658 						    (uint32_t)bw,
6659 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6660 						    (uint32_t)sbw);
6661 				bw = sbw;
6662 			}
6663 			if ((sti > tim) &&
6664 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6665 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6666 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6667 				no_apply = 1;
6668 			} else
6669 				no_apply = 0;
6670 		}
6671 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6672 		if ((no_apply == 0) &&
6673 		    ((rsm->r_app_limited == 0) ||
6674 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6675 			tcp_bbr_commit_bw(bbr, cts);
6676 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6677 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6678 		}
6679 	}
6680 }
6681 
6682 static void
6683 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6684     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6685 {
6686 	uint64_t old_rttprop;
6687 
6688 	/* Update our delivery time and amount */
6689 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6690 	bbr->r_ctl.rc_del_time = cts;
6691 	if (rtt == 0) {
6692 		/*
6693 		 * 0 means its a retransmit, for now we don't use these for
6694 		 * the rest of BBR.
6695 		 */
6696 		return;
6697 	}
6698 	if ((bbr->rc_use_google == 0) &&
6699 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6700 	    (match != BBR_RTT_BY_TIMESTAMP)){
6701 		/*
6702 		 * We get a lot of rtt updates, lets not pay attention to
6703 		 * any that are not an exact match. That way we don't have
6704 		 * to worry about timestamps and the whole nonsense of
6705 		 * unsure if its a retransmission etc (if we ever had the
6706 		 * timestamp fixed to always have the last thing sent this
6707 		 * would not be a issue).
6708 		 */
6709 		return;
6710 	}
6711 	if ((bbr_no_retran && bbr->rc_use_google) &&
6712 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6713 	    (match != BBR_RTT_BY_TIMESTAMP)){
6714 		/*
6715 		 * We only do measurements in google mode
6716 		 * with bbr_no_retran on for sure things.
6717 		 */
6718 		return;
6719 	}
6720 	/* Only update srtt if we know by exact match */
6721 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6722 	if (ack_type == BBR_CUM_ACKED)
6723 		bbr->rc_ack_is_cumack = 1;
6724 	else
6725 		bbr->rc_ack_is_cumack = 0;
6726 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6727 	/*
6728 	 * Note the following code differs to the original
6729 	 * BBR spec. It calls for <= not <. However after a
6730 	 * long discussion in email with Neal, he acknowledged
6731 	 * that it should be < than so that we will have flows
6732 	 * going into probe-rtt (we were seeing cases where that
6733 	 * did not happen and caused ugly things to occur). We
6734 	 * have added this agreed upon fix to our code base.
6735 	 */
6736 	if (rtt < old_rttprop) {
6737 		/* Update when we last saw a rtt drop */
6738 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6739 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6740 	}
6741 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6742 	    match, rsm->r_start, rsm->r_flags);
6743 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6744 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6745 		/*
6746 		 * The RTT-prop moved, reset the target (may be a
6747 		 * nop for some states).
6748 		 */
6749 		bbr_set_state_target(bbr, __LINE__);
6750 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6751 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6752 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6753 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6754 			/* It went up */
6755 			bbr_check_probe_rtt_limits(bbr, cts);
6756 	}
6757 	if ((bbr->rc_use_google == 0) &&
6758 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6759 		/*
6760 		 * We don't do b/w update with
6761 		 * these since they are not really
6762 		 * reliable.
6763 		 */
6764 		return;
6765 	}
6766 	if (bbr->r_ctl.r_app_limited_until &&
6767 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6768 		/* We are no longer app-limited */
6769 		bbr->r_ctl.r_app_limited_until = 0;
6770 	}
6771 	if (bbr->rc_use_google) {
6772 		bbr_google_measurement(bbr, rsm, rtt, cts);
6773 	} else {
6774 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6775 	}
6776 }
6777 
6778 /*
6779  * Convert a timestamp that the main stack
6780  * uses (milliseconds) into one that bbr uses
6781  * (microseconds). Return that converted timestamp.
6782  */
6783 static uint32_t
6784 bbr_ts_convert(uint32_t cts) {
6785 	uint32_t sec, msec;
6786 
6787 	sec = cts / MS_IN_USEC;
6788 	msec = cts - (MS_IN_USEC * sec);
6789 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6790 }
6791 
6792 /*
6793  * Return 0 if we did not update the RTT time, return
6794  * 1 if we did.
6795  */
6796 static int
6797 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6798     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6799 {
6800 	int32_t i;
6801 	uint32_t t, uts = 0;
6802 
6803 	if ((rsm->r_flags & BBR_ACKED) ||
6804 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6805 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6806 		/* Already done */
6807 		return (0);
6808 	}
6809 	if (rsm->r_rtt_not_allowed) {
6810 		/* Not allowed */
6811 		return (0);
6812 	}
6813 	if (rsm->r_rtr_cnt == 1) {
6814 		/*
6815 		 * Only one transmit. Hopefully the normal case.
6816 		 */
6817 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6818 			t = cts - rsm->r_tim_lastsent[0];
6819 		else
6820 			t = 1;
6821 		if ((int)t <= 0)
6822 			t = 1;
6823 		bbr->r_ctl.rc_last_rtt = t;
6824 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6825 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6826 		return (1);
6827 	}
6828 	/* Convert to usecs */
6829 	if ((bbr_can_use_ts_for_rtt == 1) &&
6830 	    (bbr->rc_use_google == 1) &&
6831 	    (ack_type == BBR_CUM_ACKED) &&
6832 	    (to->to_flags & TOF_TS) &&
6833 	    (to->to_tsecr != 0)) {
6834 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6835 		if (t < 1)
6836 			t = 1;
6837 		t *= MS_IN_USEC;
6838 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6839 				    BBR_RTT_BY_TIMESTAMP,
6840 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6841 				    ack_type, to);
6842 		return (1);
6843 	}
6844 	uts = bbr_ts_convert(to->to_tsecr);
6845 	if ((to->to_flags & TOF_TS) &&
6846 	    (to->to_tsecr != 0) &&
6847 	    (ack_type == BBR_CUM_ACKED) &&
6848 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6849 		/*
6850 		 * Now which timestamp does it match? In this block the ACK
6851 		 * may be coming from a previous transmission.
6852 		 */
6853 		uint32_t fudge;
6854 
6855 		fudge = BBR_TIMER_FUDGE;
6856 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6857 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6858 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6859 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6860 					t = cts - rsm->r_tim_lastsent[i];
6861 				else
6862 					t = 1;
6863 				if ((int)t <= 0)
6864 					t = 1;
6865 				bbr->r_ctl.rc_last_rtt = t;
6866 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6867 						    rsm->r_tim_lastsent[i], ack_type, to);
6868 				if ((i + 1) < rsm->r_rtr_cnt) {
6869 					/* Likely */
6870 					return (0);
6871 				} else if (rsm->r_flags & BBR_TLP) {
6872 					bbr->rc_tlp_rtx_out = 0;
6873 				}
6874 				return (1);
6875 			}
6876 		}
6877 		/* Fall through if we can't find a matching timestamp */
6878 	}
6879 	/*
6880 	 * Ok its a SACK block that we retransmitted. or a windows
6881 	 * machine without timestamps. We can tell nothing from the
6882 	 * time-stamp since its not there or the time the peer last
6883 	 * recieved a segment that moved forward its cum-ack point.
6884 	 *
6885 	 * Lets look at the last retransmit and see what we can tell
6886 	 * (with BBR for space we only keep 2 note we have to keep
6887 	 * at least 2 so the map can not be condensed more).
6888 	 */
6889 	i = rsm->r_rtr_cnt - 1;
6890 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6891 		t = cts - rsm->r_tim_lastsent[i];
6892 	else
6893 		goto not_sure;
6894 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6895 		/*
6896 		 * We retransmitted and the ack came back in less
6897 		 * than the smallest rtt we have observed in the
6898 		 * windowed rtt. We most likey did an improper
6899 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6900 		 * the rack-draft.
6901 		 *
6902 		 * Use the prior transmission to update all the
6903 		 * information as long as there is only one prior
6904 		 * transmission.
6905 		 */
6906 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6907 #ifdef BBR_INVARIANTS
6908 			if (rsm->r_rtr_cnt == 1)
6909 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6910 #endif
6911 			i = rsm->r_rtr_cnt - 2;
6912 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6913 				t = cts - rsm->r_tim_lastsent[i];
6914 			else
6915 				t = 1;
6916 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6917 					    rsm->r_tim_lastsent[i], ack_type, to);
6918 			return (0);
6919 		} else {
6920 			/*
6921 			 * Too many prior transmissions, just
6922 			 * updated BBR delivered
6923 			 */
6924 not_sure:
6925 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6926 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6927 		}
6928 	} else {
6929 		/*
6930 		 * We retransmitted it and the retransmit did the
6931 		 * job.
6932 		 */
6933 		if (rsm->r_flags & BBR_TLP)
6934 			bbr->rc_tlp_rtx_out = 0;
6935 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6936 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6937 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6938 		else
6939 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6940 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6941 		return (1);
6942 	}
6943 	return (0);
6944 }
6945 
6946 /*
6947  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6948  */
6949 static void
6950 bbr_log_sack_passed(struct tcpcb *tp,
6951     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6952 {
6953 	struct bbr_sendmap *nrsm;
6954 
6955 	nrsm = rsm;
6956 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6957 	    bbr_head, r_tnext) {
6958 		if (nrsm == rsm) {
6959 			/* Skip orginal segment he is acked */
6960 			continue;
6961 		}
6962 		if (nrsm->r_flags & BBR_ACKED) {
6963 			/* Skip ack'd segments */
6964 			continue;
6965 		}
6966 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6967 			/*
6968 			 * We found one that is already marked
6969 			 * passed, we have been here before and
6970 			 * so all others below this are marked.
6971 			 */
6972 			break;
6973 		}
6974 		BBR_STAT_INC(bbr_sack_passed);
6975 		nrsm->r_flags |= BBR_SACK_PASSED;
6976 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6977 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6978 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6979 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6980 			nrsm->r_flags |= BBR_MARKED_LOST;
6981 		}
6982 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6983 	}
6984 }
6985 
6986 /*
6987  * Returns the number of bytes that were
6988  * newly ack'd by sack blocks.
6989  */
6990 static uint32_t
6991 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6992     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6993 {
6994 	int32_t times = 0;
6995 	uint32_t start, end, changed = 0;
6996 	struct bbr_sendmap *rsm, *nrsm;
6997 	int32_t used_ref = 1;
6998 	uint8_t went_back = 0, went_fwd = 0;
6999 
7000 	start = sack->start;
7001 	end = sack->end;
7002 	rsm = *prsm;
7003 	if (rsm == NULL)
7004 		used_ref = 0;
7005 
7006 	/* Do we locate the block behind where we last were? */
7007 	if (rsm && SEQ_LT(start, rsm->r_start)) {
7008 		went_back = 1;
7009 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
7010 			if (SEQ_GEQ(start, rsm->r_start) &&
7011 			    SEQ_LT(start, rsm->r_end)) {
7012 				goto do_rest_ofb;
7013 			}
7014 		}
7015 	}
7016 start_at_beginning:
7017 	went_fwd = 1;
7018 	/*
7019 	 * Ok lets locate the block where this guy is fwd from rsm (if its
7020 	 * set)
7021 	 */
7022 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
7023 		if (SEQ_GEQ(start, rsm->r_start) &&
7024 		    SEQ_LT(start, rsm->r_end)) {
7025 			break;
7026 		}
7027 	}
7028 do_rest_ofb:
7029 	if (rsm == NULL) {
7030 		/*
7031 		 * This happens when we get duplicate sack blocks with the
7032 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7033 		 * will not change there location so we would just start at
7034 		 * the end of the first one and get lost.
7035 		 */
7036 		if (tp->t_flags & TF_SENTFIN) {
7037 			/*
7038 			 * Check to see if we have not logged the FIN that
7039 			 * went out.
7040 			 */
7041 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7042 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7043 				/*
7044 				 * Ok we did not get the FIN logged.
7045 				 */
7046 				nrsm->r_end++;
7047 				rsm = nrsm;
7048 				goto do_rest_ofb;
7049 			}
7050 		}
7051 		if (times == 1) {
7052 #ifdef BBR_INVARIANTS
7053 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7054 			    tp, bbr, sack, to, prsm);
7055 #else
7056 			goto out;
7057 #endif
7058 		}
7059 		times++;
7060 		BBR_STAT_INC(bbr_sack_proc_restart);
7061 		rsm = NULL;
7062 		goto start_at_beginning;
7063 	}
7064 	/* Ok we have an ACK for some piece of rsm */
7065 	if (rsm->r_start != start) {
7066 		/*
7067 		 * Need to split this in two pieces the before and after.
7068 		 */
7069 		if (bbr_sack_mergable(rsm, start, end))
7070 			nrsm = bbr_alloc_full_limit(bbr);
7071 		else
7072 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7073 		if (nrsm == NULL) {
7074 			/* We could not allocate ignore the sack */
7075 			struct sackblk blk;
7076 
7077 			blk.start = start;
7078 			blk.end = end;
7079 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7080 			goto out;
7081 		}
7082 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7083 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7084 		if (rsm->r_in_tmap) {
7085 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7086 			nrsm->r_in_tmap = 1;
7087 		}
7088 		rsm->r_flags &= (~BBR_HAS_FIN);
7089 		rsm = nrsm;
7090 	}
7091 	if (SEQ_GEQ(end, rsm->r_end)) {
7092 		/*
7093 		 * The end of this block is either beyond this guy or right
7094 		 * at this guy.
7095 		 */
7096 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7097 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7098 			changed += (rsm->r_end - rsm->r_start);
7099 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7100 			bbr_log_sack_passed(tp, bbr, rsm);
7101 			if (rsm->r_flags & BBR_MARKED_LOST) {
7102 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7103 			}
7104 			/* Is Reordering occuring? */
7105 			if (rsm->r_flags & BBR_SACK_PASSED) {
7106 				BBR_STAT_INC(bbr_reorder_seen);
7107 				bbr->r_ctl.rc_reorder_ts = cts;
7108 				if (rsm->r_flags & BBR_MARKED_LOST) {
7109 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7110 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7111 						/* LT sampling also needs adjustment */
7112 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7113 				}
7114 			}
7115 			rsm->r_flags |= BBR_ACKED;
7116 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7117 			if (rsm->r_in_tmap) {
7118 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7119 				rsm->r_in_tmap = 0;
7120 			}
7121 		}
7122 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7123 		if (end == rsm->r_end) {
7124 			/* This block only - done */
7125 			goto out;
7126 		}
7127 		/* There is more not coverend by this rsm move on */
7128 		start = rsm->r_end;
7129 		nrsm = TAILQ_NEXT(rsm, r_next);
7130 		rsm = nrsm;
7131 		times = 0;
7132 		goto do_rest_ofb;
7133 	}
7134 	if (rsm->r_flags & BBR_ACKED) {
7135 		/* Been here done that */
7136 		goto out;
7137 	}
7138 	/* Ok we need to split off this one at the tail */
7139 	if (bbr_sack_mergable(rsm, start, end))
7140 		nrsm = bbr_alloc_full_limit(bbr);
7141 	else
7142 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7143 	if (nrsm == NULL) {
7144 		/* failed XXXrrs what can we do but loose the sack info? */
7145 		struct sackblk blk;
7146 
7147 		blk.start = start;
7148 		blk.end = end;
7149 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7150 		goto out;
7151 	}
7152 	/* Clone it */
7153 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7154 	/* The sack block does not cover this guy fully */
7155 	rsm->r_flags &= (~BBR_HAS_FIN);
7156 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7157 	if (rsm->r_in_tmap) {
7158 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7159 		nrsm->r_in_tmap = 1;
7160 	}
7161 	nrsm->r_dupack = 0;
7162 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7163 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7164 	changed += (rsm->r_end - rsm->r_start);
7165 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7166 	bbr_log_sack_passed(tp, bbr, rsm);
7167 	/* Is Reordering occuring? */
7168 	if (rsm->r_flags & BBR_MARKED_LOST) {
7169 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7170 	}
7171 	if (rsm->r_flags & BBR_SACK_PASSED) {
7172 		BBR_STAT_INC(bbr_reorder_seen);
7173 		bbr->r_ctl.rc_reorder_ts = cts;
7174 		if (rsm->r_flags & BBR_MARKED_LOST) {
7175 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7176 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7177 				/* LT sampling also needs adjustment */
7178 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7179 		}
7180 	}
7181 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7182 	rsm->r_flags |= BBR_ACKED;
7183 	if (rsm->r_in_tmap) {
7184 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7185 		rsm->r_in_tmap = 0;
7186 	}
7187 out:
7188 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7189 		/*
7190 		 * Now can we merge this newly acked
7191 		 * block with either the previous or
7192 		 * next block?
7193 		 */
7194 		nrsm = TAILQ_NEXT(rsm, r_next);
7195 		if (nrsm &&
7196 		    (nrsm->r_flags & BBR_ACKED)) {
7197 			/* yep this and next can be merged */
7198 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7199 		}
7200 		/* Now what about the previous? */
7201 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7202 		if (nrsm &&
7203 		    (nrsm->r_flags & BBR_ACKED)) {
7204 			/* yep the previous and this can be merged */
7205 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7206 		}
7207 	}
7208 	if (used_ref == 0) {
7209 		BBR_STAT_INC(bbr_sack_proc_all);
7210 	} else {
7211 		BBR_STAT_INC(bbr_sack_proc_short);
7212 	}
7213 	if (went_fwd && went_back) {
7214 		BBR_STAT_INC(bbr_sack_search_both);
7215 	} else if (went_fwd) {
7216 		BBR_STAT_INC(bbr_sack_search_fwd);
7217 	} else if (went_back) {
7218 		BBR_STAT_INC(bbr_sack_search_back);
7219 	}
7220 	/* Save off where the next seq is */
7221 	if (rsm)
7222 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7223 	else
7224 		bbr->r_ctl.rc_sacklast = NULL;
7225 	*prsm = rsm;
7226 	return (changed);
7227 }
7228 
7229 static void inline
7230 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7231 {
7232 	struct bbr_sendmap *tmap;
7233 
7234 	BBR_STAT_INC(bbr_reneges_seen);
7235 	tmap = NULL;
7236 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7237 		/* Its no longer sacked, mark it so */
7238 		uint32_t oflags;
7239 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7240 #ifdef BBR_INVARIANTS
7241 		if (rsm->r_in_tmap) {
7242 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7243 			    bbr, rsm, rsm->r_flags);
7244 		}
7245 #endif
7246 		oflags = rsm->r_flags;
7247 		if (rsm->r_flags & BBR_MARKED_LOST) {
7248 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7249 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7250 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7251 				/* LT sampling also needs adjustment */
7252 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7253 		}
7254 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7255 		rsm->r_flags |= BBR_WAS_RENEGED;
7256 		rsm->r_flags |= BBR_RXT_CLEARED;
7257 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7258 		/* Rebuild it into our tmap */
7259 		if (tmap == NULL) {
7260 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7261 			tmap = rsm;
7262 		} else {
7263 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7264 			tmap = rsm;
7265 		}
7266 		tmap->r_in_tmap = 1;
7267 		/*
7268 		 * XXXrrs Delivered? Should we do anything here?
7269 		 *
7270 		 * Of course we don't on a rxt timeout so maybe its ok that
7271 		 * we don't?
7272 		 *
7273 		 * For now lets not.
7274 		 */
7275 		rsm = TAILQ_NEXT(rsm, r_next);
7276 	}
7277 	/*
7278 	 * Now lets possibly clear the sack filter so we start recognizing
7279 	 * sacks that cover this area.
7280 	 */
7281 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7282 }
7283 
7284 static void
7285 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7286 {
7287 	struct tcp_bbr *bbr;
7288 	struct bbr_sendmap *rsm;
7289 	uint32_t cts;
7290 
7291 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7292 	cts = bbr->r_ctl.rc_rcvtime;
7293 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7294 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7295 		if ((rsm->r_end - rsm->r_start) <= 1) {
7296 			/* Log out the SYN completely */
7297 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7298 			rsm->r_rtr_bytes = 0;
7299 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7300 			if (rsm->r_in_tmap) {
7301 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7302 				rsm->r_in_tmap = 0;
7303 			}
7304 			if (bbr->r_ctl.rc_next == rsm) {
7305 				/* scoot along the marker */
7306 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7307 			}
7308 			if (to != NULL)
7309 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7310 			bbr_free(bbr, rsm);
7311 		} else {
7312 			/* There is more (Fast open)? strip out SYN. */
7313 			rsm->r_flags &= ~BBR_HAS_SYN;
7314 			rsm->r_start++;
7315 		}
7316 	}
7317 }
7318 
7319 /*
7320  * Returns the number of bytes that were
7321  * acknowledged by SACK blocks.
7322  */
7323 
7324 static uint32_t
7325 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7326     uint32_t *prev_acked)
7327 {
7328 	uint32_t changed, last_seq, entered_recovery = 0;
7329 	struct tcp_bbr *bbr;
7330 	struct bbr_sendmap *rsm;
7331 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7332 	register uint32_t th_ack;
7333 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7334 	uint32_t cts, acked, ack_point, sack_changed = 0;
7335 	uint32_t p_maxseg, maxseg, p_acked = 0;
7336 
7337 	INP_WLOCK_ASSERT(tp->t_inpcb);
7338 	if (tcp_get_flags(th) & TH_RST) {
7339 		/* We don't log resets */
7340 		return (0);
7341 	}
7342 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7343 	cts = bbr->r_ctl.rc_rcvtime;
7344 
7345 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7346 	changed = 0;
7347 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7348 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7349 	th_ack = th->th_ack;
7350 	if (SEQ_GT(th_ack, tp->snd_una)) {
7351 		acked = th_ack - tp->snd_una;
7352 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7353 		bbr->rc_tp->t_acktime = ticks;
7354 	} else
7355 		acked = 0;
7356 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7357 		/* Only sent here for sack processing */
7358 		goto proc_sack;
7359 	}
7360 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7361 		changed = th_ack - rsm->r_start;
7362 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7363 		/*
7364 		 * For the SYN incoming case we will not have called
7365 		 * tcp_output for the sending of the SYN, so there will be
7366 		 * no map. All other cases should probably be a panic.
7367 		 */
7368 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7369 			/*
7370 			 * We have a timestamp that can be used to generate
7371 			 * an initial RTT.
7372 			 */
7373 			uint32_t ts, now, rtt;
7374 
7375 			ts = bbr_ts_convert(to->to_tsecr);
7376 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7377 			rtt = now - ts;
7378 			if (rtt < 1)
7379 				rtt = 1;
7380 			bbr_log_type_bbrrttprop(bbr, rtt,
7381 						tp->iss, 0, cts,
7382 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7383 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7384 			changed = 1;
7385 			bbr->r_wanted_output = 1;
7386 			goto out;
7387 		}
7388 		goto proc_sack;
7389 	} else if (rsm == NULL) {
7390 		goto out;
7391 	}
7392 	if (changed) {
7393 		/*
7394 		 * The ACK point is advancing to th_ack, we must drop off
7395 		 * the packets in the rack log and calculate any eligble
7396 		 * RTT's.
7397 		 */
7398 		bbr->r_wanted_output = 1;
7399 more:
7400 		if (rsm == NULL) {
7401 			if (tp->t_flags & TF_SENTFIN) {
7402 				/* if we send a FIN we will not hav a map */
7403 				goto proc_sack;
7404 			}
7405 #ifdef BBR_INVARIANTS
7406 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7407 			    tp,
7408 			    th, tp->t_state, bbr,
7409 			    tp->snd_una, tp->snd_max, changed);
7410 #endif
7411 			goto proc_sack;
7412 		}
7413 	}
7414 	if (SEQ_LT(th_ack, rsm->r_start)) {
7415 		/* Huh map is missing this */
7416 #ifdef BBR_INVARIANTS
7417 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7418 		    rsm->r_start,
7419 		    th_ack, tp->t_state,
7420 		    bbr->r_state, bbr);
7421 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7422 #endif
7423 		goto proc_sack;
7424 	} else if (th_ack == rsm->r_start) {
7425 		/* None here to ack */
7426 		goto proc_sack;
7427 	}
7428 	/*
7429 	 * Clear the dup ack counter, it will
7430 	 * either be freed or if there is some
7431 	 * remaining we need to start it at zero.
7432 	 */
7433 	rsm->r_dupack = 0;
7434 	/* Now do we consume the whole thing? */
7435 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7436 		/* Its all consumed. */
7437 		uint32_t left;
7438 
7439 		if (rsm->r_flags & BBR_ACKED) {
7440 			/*
7441 			 * It was acked on the scoreboard -- remove it from
7442 			 * total
7443 			 */
7444 			p_acked += (rsm->r_end - rsm->r_start);
7445 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7446 			if (bbr->r_ctl.rc_sacked == 0)
7447 				bbr->r_ctl.rc_sacklast = NULL;
7448 		} else {
7449 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7450 			if (rsm->r_flags & BBR_MARKED_LOST) {
7451 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7452 			}
7453 			if (rsm->r_flags & BBR_SACK_PASSED) {
7454 				/*
7455 				 * There are acked segments ACKED on the
7456 				 * scoreboard further up. We are seeing
7457 				 * reordering.
7458 				 */
7459 				BBR_STAT_INC(bbr_reorder_seen);
7460 				bbr->r_ctl.rc_reorder_ts = cts;
7461 				if (rsm->r_flags & BBR_MARKED_LOST) {
7462 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7463 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7464 						/* LT sampling also needs adjustment */
7465 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7466 				}
7467 			}
7468 			rsm->r_flags &= ~BBR_MARKED_LOST;
7469 		}
7470 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7471 		rsm->r_rtr_bytes = 0;
7472 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7473 		if (rsm->r_in_tmap) {
7474 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7475 			rsm->r_in_tmap = 0;
7476 		}
7477 		if (bbr->r_ctl.rc_next == rsm) {
7478 			/* scoot along the marker */
7479 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7480 		}
7481 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7482 		/* Adjust the packet counts */
7483 		left = th_ack - rsm->r_end;
7484 		/* Free back to zone */
7485 		bbr_free(bbr, rsm);
7486 		if (left) {
7487 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7488 			goto more;
7489 		}
7490 		goto proc_sack;
7491 	}
7492 	if (rsm->r_flags & BBR_ACKED) {
7493 		/*
7494 		 * It was acked on the scoreboard -- remove it from total
7495 		 * for the part being cum-acked.
7496 		 */
7497 		p_acked += (rsm->r_end - rsm->r_start);
7498 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7499 		if (bbr->r_ctl.rc_sacked == 0)
7500 			bbr->r_ctl.rc_sacklast = NULL;
7501 	} else {
7502 		/*
7503 		 * It was acked up to th_ack point for the first time
7504 		 */
7505 		struct bbr_sendmap lrsm;
7506 
7507 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7508 		lrsm.r_end = th_ack;
7509 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7510 	}
7511 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7512 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7513 		/*
7514 		 * It was marked lost and partly ack'd now
7515 		 * for the first time. We lower the rc_lost_bytes
7516 		 * and still leave it MARKED.
7517 		 */
7518 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7519 	}
7520 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7521 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7522 	rsm->r_rtr_bytes = 0;
7523 	/* adjust packet count */
7524 	rsm->r_start = th_ack;
7525 proc_sack:
7526 	/* Check for reneging */
7527 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7528 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7529 		/*
7530 		 * The peer has moved snd_una up to the edge of this send,
7531 		 * i.e. one that it had previously acked. The only way that
7532 		 * can be true if the peer threw away data (space issues)
7533 		 * that it had previously sacked (else it would have given
7534 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7535 		 * markings here.
7536 		 *
7537 		 * Note we have to look to make sure th_ack is our
7538 		 * rsm->r_start in case we get an old ack where th_ack is
7539 		 * behind snd_una.
7540 		 */
7541 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7542 	}
7543 	if ((to->to_flags & TOF_SACK) == 0) {
7544 		/* We are done nothing left to log */
7545 		goto out;
7546 	}
7547 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7548 	if (rsm) {
7549 		last_seq = rsm->r_end;
7550 	} else {
7551 		last_seq = tp->snd_max;
7552 	}
7553 	/* Sack block processing */
7554 	if (SEQ_GT(th_ack, tp->snd_una))
7555 		ack_point = th_ack;
7556 	else
7557 		ack_point = tp->snd_una;
7558 	for (i = 0; i < to->to_nsacks; i++) {
7559 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7560 		    &sack, sizeof(sack));
7561 		sack.start = ntohl(sack.start);
7562 		sack.end = ntohl(sack.end);
7563 		if (SEQ_GT(sack.end, sack.start) &&
7564 		    SEQ_GT(sack.start, ack_point) &&
7565 		    SEQ_LT(sack.start, tp->snd_max) &&
7566 		    SEQ_GT(sack.end, ack_point) &&
7567 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7568 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7569 			    (SEQ_LT(sack.end, last_seq)) &&
7570 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7571 				/*
7572 				 * Not the last piece and its smaller than
7573 				 * 1/8th of a p_maxseg. We ignore this.
7574 				 */
7575 				BBR_STAT_INC(bbr_runt_sacks);
7576 				continue;
7577 			}
7578 			sack_blocks[num_sack_blks] = sack;
7579 			num_sack_blks++;
7580 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7581 		    SEQ_LEQ(sack.end, th_ack)) {
7582 			/*
7583 			 * Its a D-SACK block.
7584 			 */
7585 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7586 		}
7587 	}
7588 	if (num_sack_blks == 0)
7589 		goto out;
7590 	/*
7591 	 * Sort the SACK blocks so we can update the rack scoreboard with
7592 	 * just one pass.
7593 	 */
7594 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7595 				  num_sack_blks, th->th_ack);
7596 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7597 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7598 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7599 	num_sack_blks = new_sb;
7600 	if (num_sack_blks < 2) {
7601 		goto do_sack_work;
7602 	}
7603 	/* Sort the sacks */
7604 	for (i = 0; i < num_sack_blks; i++) {
7605 		for (j = i + 1; j < num_sack_blks; j++) {
7606 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7607 				sack = sack_blocks[i];
7608 				sack_blocks[i] = sack_blocks[j];
7609 				sack_blocks[j] = sack;
7610 			}
7611 		}
7612 	}
7613 	/*
7614 	 * Now are any of the sack block ends the same (yes some
7615 	 * implememtations send these)?
7616 	 */
7617 again:
7618 	if (num_sack_blks > 1) {
7619 		for (i = 0; i < num_sack_blks; i++) {
7620 			for (j = i + 1; j < num_sack_blks; j++) {
7621 				if (sack_blocks[i].end == sack_blocks[j].end) {
7622 					/*
7623 					 * Ok these two have the same end we
7624 					 * want the smallest end and then
7625 					 * throw away the larger and start
7626 					 * again.
7627 					 */
7628 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7629 						/*
7630 						 * The second block covers
7631 						 * more area use that
7632 						 */
7633 						sack_blocks[i].start = sack_blocks[j].start;
7634 					}
7635 					/*
7636 					 * Now collapse out the dup-sack and
7637 					 * lower the count
7638 					 */
7639 					for (k = (j + 1); k < num_sack_blks; k++) {
7640 						sack_blocks[j].start = sack_blocks[k].start;
7641 						sack_blocks[j].end = sack_blocks[k].end;
7642 						j++;
7643 					}
7644 					num_sack_blks--;
7645 					goto again;
7646 				}
7647 			}
7648 		}
7649 	}
7650 do_sack_work:
7651 	rsm = bbr->r_ctl.rc_sacklast;
7652 	for (i = 0; i < num_sack_blks; i++) {
7653 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7654 		if (acked) {
7655 			bbr->r_wanted_output = 1;
7656 			changed += acked;
7657 			sack_changed += acked;
7658 		}
7659 	}
7660 out:
7661 	*prev_acked = p_acked;
7662 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7663 		/*
7664 		 * Ok we have a high probability that we need to go in to
7665 		 * recovery since we have data sack'd
7666 		 */
7667 		struct bbr_sendmap *rsm;
7668 
7669 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7670 		if (rsm) {
7671 			/* Enter recovery */
7672 			entered_recovery = 1;
7673 			bbr->r_wanted_output = 1;
7674 			/*
7675 			 * When we enter recovery we need to assure we send
7676 			 * one packet.
7677 			 */
7678 			if (bbr->r_ctl.rc_resend == NULL) {
7679 				bbr->r_ctl.rc_resend = rsm;
7680 			}
7681 		}
7682 	}
7683 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7684 		/*
7685 		 * See if we need to rack-retransmit anything if so set it
7686 		 * up as the thing to resend assuming something else is not
7687 		 * already in that position.
7688 		 */
7689 		if (bbr->r_ctl.rc_resend == NULL) {
7690 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7691 		}
7692 	}
7693 	/*
7694 	 * We return the amount that changed via sack, this is used by the
7695 	 * ack-received code to augment what was changed between th_ack <->
7696 	 * snd_una.
7697 	 */
7698 	return (sack_changed);
7699 }
7700 
7701 static void
7702 bbr_strike_dupack(struct tcp_bbr *bbr)
7703 {
7704 	struct bbr_sendmap *rsm;
7705 
7706 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7707 	if (rsm && (rsm->r_dupack < 0xff)) {
7708 		rsm->r_dupack++;
7709 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7710 			bbr->r_wanted_output = 1;
7711 	}
7712 }
7713 
7714 /*
7715  * Return value of 1, we do not need to call bbr_process_data().
7716  * return value of 0, bbr_process_data can be called.
7717  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7718  * its unlocked and probably unsafe to touch the TCB.
7719  */
7720 static int
7721 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7722     struct tcpcb *tp, struct tcpopt *to,
7723     uint32_t tiwin, int32_t tlen,
7724     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7725 {
7726 	int32_t ourfinisacked = 0;
7727 	int32_t acked_amount;
7728 	uint16_t nsegs;
7729 	int32_t acked;
7730 	uint32_t lost, sack_changed = 0;
7731 	struct mbuf *mfree;
7732 	struct tcp_bbr *bbr;
7733 	uint32_t prev_acked = 0;
7734 
7735 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7736 	lost = bbr->r_ctl.rc_lost;
7737 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7738 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7739 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7740 		bbr->r_wanted_output = 1;
7741 		return (1);
7742 	}
7743 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7744 		/* Process the ack */
7745 		if (bbr->rc_in_persist)
7746 			tp->t_rxtshift = 0;
7747 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7748 			bbr_strike_dupack(bbr);
7749 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7750 	}
7751 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7752 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7753 		/*
7754 		 * Old ack, behind the last one rcv'd or a duplicate ack
7755 		 * with SACK info.
7756 		 */
7757 		if (th->th_ack == tp->snd_una) {
7758 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7759 			if (bbr->r_state == TCPS_SYN_SENT) {
7760 				/*
7761 				 * Special case on where we sent SYN. When
7762 				 * the SYN-ACK is processed in syn_sent
7763 				 * state it bumps the snd_una. This causes
7764 				 * us to hit here even though we did ack 1
7765 				 * byte.
7766 				 *
7767 				 * Go through the nothing left case so we
7768 				 * send data.
7769 				 */
7770 				goto nothing_left;
7771 			}
7772 		}
7773 		return (0);
7774 	}
7775 	/*
7776 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7777 	 * something we sent.
7778 	 */
7779 	if (tp->t_flags & TF_NEEDSYN) {
7780 		/*
7781 		 * T/TCP: Connection was half-synchronized, and our SYN has
7782 		 * been ACK'd (so connection is now fully synchronized).  Go
7783 		 * to non-starred state, increment snd_una for ACK of SYN,
7784 		 * and check if we can do window scaling.
7785 		 */
7786 		tp->t_flags &= ~TF_NEEDSYN;
7787 		tp->snd_una++;
7788 		/* Do window scaling? */
7789 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7790 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7791 			tp->rcv_scale = tp->request_r_scale;
7792 			/* Send window already scaled. */
7793 		}
7794 	}
7795 	INP_WLOCK_ASSERT(tp->t_inpcb);
7796 
7797 	acked = BYTES_THIS_ACK(tp, th);
7798 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7799 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7800 
7801 	/*
7802 	 * If we just performed our first retransmit, and the ACK arrives
7803 	 * within our recovery window, then it was a mistake to do the
7804 	 * retransmit in the first place.  Recover our original cwnd and
7805 	 * ssthresh, and proceed to transmit where we left off.
7806 	 */
7807 	if (tp->t_flags & TF_PREVVALID) {
7808 		tp->t_flags &= ~TF_PREVVALID;
7809 		if (tp->t_rxtshift == 1 &&
7810 		    (int)(ticks - tp->t_badrxtwin) < 0)
7811 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7812 	}
7813 	SOCKBUF_LOCK(&so->so_snd);
7814 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7815 	tp->snd_wnd -= acked_amount;
7816 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7817 	/* NB: sowwakeup_locked() does an implicit unlock. */
7818 	sowwakeup_locked(so);
7819 	m_freem(mfree);
7820 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7821 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7822 	}
7823 	tp->snd_una = th->th_ack;
7824 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7825 	if (IN_RECOVERY(tp->t_flags)) {
7826 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7827 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7828 			tcp_bbr_partialack(tp);
7829 		} else {
7830 			bbr_post_recovery(tp);
7831 		}
7832 	}
7833 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7834 		tp->snd_recover = tp->snd_una;
7835 	}
7836 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7837 		tp->snd_nxt = tp->snd_max;
7838 	}
7839 	if (tp->snd_una == tp->snd_max) {
7840 		/* Nothing left outstanding */
7841 nothing_left:
7842 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7843 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
7844 			bbr->rc_tp->t_acktime = 0;
7845 		if ((sbused(&so->so_snd) == 0) &&
7846 		    (tp->t_flags & TF_SENTFIN)) {
7847 			ourfinisacked = 1;
7848 		}
7849 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7850 		if (bbr->rc_in_persist == 0) {
7851 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7852 		}
7853 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7854 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7855 		/*
7856 		 * We invalidate the last ack here since we
7857 		 * don't want to transfer forward the time
7858 		 * for our sum's calculations.
7859 		 */
7860 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7861 		    (sbavail(&so->so_snd) == 0) &&
7862 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7863 			/*
7864 			 * The socket was gone and the peer sent data, time
7865 			 * to reset him.
7866 			 */
7867 			*ret_val = 1;
7868 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7869 			/* tcp_close will kill the inp pre-log the Reset */
7870 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7871 			tp = tcp_close(tp);
7872 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7873 			BBR_STAT_INC(bbr_dropped_af_data);
7874 			return (1);
7875 		}
7876 		/* Set need output so persist might get set */
7877 		bbr->r_wanted_output = 1;
7878 	}
7879 	if (ofia)
7880 		*ofia = ourfinisacked;
7881 	return (0);
7882 }
7883 
7884 static void
7885 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7886 {
7887 	if (bbr->rc_in_persist == 0) {
7888 		bbr_timer_cancel(bbr, __LINE__, cts);
7889 		bbr->r_ctl.rc_last_delay_val = 0;
7890 		tp->t_rxtshift = 0;
7891 		bbr->rc_in_persist = 1;
7892 		bbr->r_ctl.rc_went_idle_time = cts;
7893 		/* We should be capped when rw went to 0 but just in case */
7894 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7895 		/* Time freezes for the state, so do the accounting now */
7896 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7897 			uint32_t time_in;
7898 
7899 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7900 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7901 				int32_t idx;
7902 
7903 				idx = bbr_state_val(bbr);
7904 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7905 			} else {
7906 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7907 			}
7908 		}
7909 		bbr->r_ctl.rc_bbr_state_time = cts;
7910 	}
7911 }
7912 
7913 static void
7914 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7915 {
7916 	/*
7917 	 * Note that if idle time does not exceed our
7918 	 * threshold, we do nothing continuing the state
7919 	 * transitions we were last walking through.
7920 	 */
7921 	if (idle_time >= bbr_idle_restart_threshold) {
7922 		if (bbr->rc_use_idle_restart) {
7923 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7924 			/*
7925 			 * Set our target using BBR_UNIT, so
7926 			 * we increase at a dramatic rate but
7927 			 * we stop when we get the pipe
7928 			 * full again for our current b/w estimate.
7929 			 */
7930 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7931 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7932 			bbr_set_state_target(bbr, __LINE__);
7933 			/* Now setup our gains to ramp up */
7934 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7935 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7936 			bbr_log_type_statechange(bbr, cts, __LINE__);
7937 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7938 			bbr_substate_change(bbr, cts, __LINE__, 1);
7939 		}
7940 	}
7941 }
7942 
7943 static void
7944 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7945 {
7946 	uint32_t idle_time;
7947 
7948 	if (bbr->rc_in_persist == 0)
7949 		return;
7950 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7951 	bbr->rc_in_persist = 0;
7952 	bbr->rc_hit_state_1 = 0;
7953 	bbr->r_ctl.rc_del_time = cts;
7954 	/*
7955 	 * We invalidate the last ack here since we
7956 	 * don't want to transfer forward the time
7957 	 * for our sum's calculations.
7958 	 */
7959 	if (tcp_in_hpts(bbr->rc_inp)) {
7960 		tcp_hpts_remove(bbr->rc_inp);
7961 		bbr->rc_timer_first = 0;
7962 		bbr->r_ctl.rc_hpts_flags = 0;
7963 		bbr->r_ctl.rc_last_delay_val = 0;
7964 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7965 		bbr->r_agg_early_set = 0;
7966 		bbr->r_ctl.rc_agg_early = 0;
7967 	}
7968 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7969 	if (idle_time >= bbr_rtt_probe_time) {
7970 		/*
7971 		 * This qualifies as a RTT_PROBE session since we drop the
7972 		 * data outstanding to nothing and waited more than
7973 		 * bbr_rtt_probe_time.
7974 		 */
7975 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7976 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7977 	}
7978 	tp->t_rxtshift = 0;
7979 	/*
7980 	 * If in probeBW and we have persisted more than an RTT lets do
7981 	 * special handling.
7982 	 */
7983 	/* Force a time based epoch */
7984 	bbr_set_epoch(bbr, cts, __LINE__);
7985 	/*
7986 	 * Setup the lost so we don't count anything against the guy
7987 	 * we have been stuck with during persists.
7988 	 */
7989 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7990 	/* Time un-freezes for the state */
7991 	bbr->r_ctl.rc_bbr_state_time = cts;
7992 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7993 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7994 		/*
7995 		 * If we are going back to probe-bw
7996 		 * or probe_rtt, we may need to possibly
7997 		 * do a fast restart.
7998 		 */
7999 		bbr_restart_after_idle(bbr, cts, idle_time);
8000 	}
8001 }
8002 
8003 static void
8004 bbr_collapsed_window(struct tcp_bbr *bbr)
8005 {
8006 	/*
8007 	 * Now we must walk the
8008 	 * send map and divide the
8009 	 * ones left stranded. These
8010 	 * guys can't cause us to abort
8011 	 * the connection and are really
8012 	 * "unsent". However if a buggy
8013 	 * client actually did keep some
8014 	 * of the data i.e. collapsed the win
8015 	 * and refused to ack and then opened
8016 	 * the win and acked that data. We would
8017 	 * get into an ack war, the simplier
8018 	 * method then of just pretending we
8019 	 * did not send those segments something
8020 	 * won't work.
8021 	 */
8022 	struct bbr_sendmap *rsm, *nrsm;
8023 	tcp_seq max_seq;
8024 	uint32_t maxseg;
8025 	int can_split = 0;
8026 	int fnd = 0;
8027 
8028 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8029 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8030 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8031 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8032 		/* Find the first seq past or at maxseq */
8033 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8034 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8035 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8036 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8037 			fnd = 1;
8038 			break;
8039 		}
8040 	}
8041 	bbr->rc_has_collapsed = 0;
8042 	if (!fnd) {
8043 		/* Nothing to do strange */
8044 		return;
8045 	}
8046 	/*
8047 	 * Now can we split?
8048 	 *
8049 	 * We don't want to split if splitting
8050 	 * would generate too many small segments
8051 	 * less we let an attacker fragment our
8052 	 * send_map and leave us out of memory.
8053 	 */
8054 	if ((max_seq != rsm->r_start) &&
8055 	    (max_seq != rsm->r_end)){
8056 		/* can we split? */
8057 		int res1, res2;
8058 
8059 		res1 = max_seq - rsm->r_start;
8060 		res2 = rsm->r_end - max_seq;
8061 		if ((res1 >= (maxseg/8)) &&
8062 		    (res2 >= (maxseg/8))) {
8063 			/* No small pieces here */
8064 			can_split = 1;
8065 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8066 			/* We are under the limit */
8067 			can_split = 1;
8068 		}
8069 	}
8070 	/* Ok do we need to split this rsm? */
8071 	if (max_seq == rsm->r_start) {
8072 		/* It's this guy no split required */
8073 		nrsm = rsm;
8074 	} else if (max_seq == rsm->r_end) {
8075 		/* It's the next one no split required. */
8076 		nrsm = TAILQ_NEXT(rsm, r_next);
8077 		if (nrsm == NULL) {
8078 			/* Huh? */
8079 			return;
8080 		}
8081 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8082 		/* yep we need to split it */
8083 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8084 		if (nrsm == NULL) {
8085 			/* failed XXXrrs what can we do mark the whole? */
8086 			nrsm = rsm;
8087 			goto no_split;
8088 		}
8089 		/* Clone it */
8090 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8091 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8092 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8093 		if (rsm->r_in_tmap) {
8094 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8095 			nrsm->r_in_tmap = 1;
8096 		}
8097 	} else {
8098 		/*
8099 		 * Split not allowed just start here just
8100 		 * use this guy.
8101 		 */
8102 		nrsm = rsm;
8103 	}
8104 no_split:
8105 	BBR_STAT_INC(bbr_collapsed_win);
8106 	/* reuse fnd as a count */
8107 	fnd = 0;
8108 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8109 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8110 		fnd++;
8111 		bbr->rc_has_collapsed = 1;
8112 	}
8113 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8114 }
8115 
8116 static void
8117 bbr_un_collapse_window(struct tcp_bbr *bbr)
8118 {
8119 	struct bbr_sendmap *rsm;
8120 	int cleared = 0;
8121 
8122 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8123 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8124 			/* Clear the flag */
8125 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8126 			cleared++;
8127 		} else
8128 			break;
8129 	}
8130 	bbr_log_type_rwnd_collapse(bbr,
8131 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8132 	bbr->rc_has_collapsed = 0;
8133 }
8134 
8135 /*
8136  * Return value of 1, the TCB is unlocked and most
8137  * likely gone, return value of 0, the TCB is still
8138  * locked.
8139  */
8140 static int
8141 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8142     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8143     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8144 {
8145 	/*
8146 	 * Update window information. Don't look at window if no ACK: TAC's
8147 	 * send garbage on first SYN.
8148 	 */
8149 	uint16_t nsegs;
8150 	int32_t tfo_syn;
8151 	struct tcp_bbr *bbr;
8152 
8153 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8154 	INP_WLOCK_ASSERT(tp->t_inpcb);
8155 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8156 	if ((thflags & TH_ACK) &&
8157 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8158 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8159 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8160 		/* keep track of pure window updates */
8161 		if (tlen == 0 &&
8162 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8163 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8164 		tp->snd_wnd = tiwin;
8165 		tp->snd_wl1 = th->th_seq;
8166 		tp->snd_wl2 = th->th_ack;
8167 		if (tp->snd_wnd > tp->max_sndwnd)
8168 			tp->max_sndwnd = tp->snd_wnd;
8169 		bbr->r_wanted_output = 1;
8170 	} else if (thflags & TH_ACK) {
8171 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8172 			tp->snd_wnd = tiwin;
8173 			tp->snd_wl1 = th->th_seq;
8174 			tp->snd_wl2 = th->th_ack;
8175 		}
8176 	}
8177 	if (tp->snd_wnd < ctf_outstanding(tp))
8178 		/* The peer collapsed its window on us */
8179 		bbr_collapsed_window(bbr);
8180  	else if (bbr->rc_has_collapsed)
8181 		bbr_un_collapse_window(bbr);
8182 	/* Was persist timer active and now we have window space? */
8183 	if ((bbr->rc_in_persist != 0) &&
8184 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8185 				bbr_minseg(bbr)))) {
8186 		/*
8187 		 * Make the rate persist at end of persist mode if idle long
8188 		 * enough
8189 		 */
8190 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8191 
8192 		/* Make sure we output to start the timer */
8193 		bbr->r_wanted_output = 1;
8194 	}
8195 	/* Do we need to enter persist? */
8196 	if ((bbr->rc_in_persist == 0) &&
8197 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8198 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8199 	    (tp->snd_max == tp->snd_una) &&
8200 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8201 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8202 		/* No send window.. we must enter persist */
8203 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8204 	}
8205 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8206 		m_freem(m);
8207 		return (0);
8208 	}
8209 	/*
8210 	 * We don't support urgent data but
8211 	 * drag along the up just to make sure
8212 	 * if there is a stack switch no one
8213 	 * is surprised.
8214 	 */
8215 	tp->rcv_up = tp->rcv_nxt;
8216 	INP_WLOCK_ASSERT(tp->t_inpcb);
8217 
8218 	/*
8219 	 * Process the segment text, merging it into the TCP sequencing
8220 	 * queue, and arranging for acknowledgment of receipt if necessary.
8221 	 * This process logically involves adjusting tp->rcv_wnd as data is
8222 	 * presented to the user (this happens in tcp_usrreq.c, case
8223 	 * PRU_RCVD).  If a FIN has already been received on this connection
8224 	 * then we just ignore the text.
8225 	 */
8226 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8227 		   IS_FASTOPEN(tp->t_flags));
8228 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8229 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8230 		tcp_seq save_start = th->th_seq;
8231 		tcp_seq save_rnxt  = tp->rcv_nxt;
8232 		int     save_tlen  = tlen;
8233 
8234 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8235 		/*
8236 		 * Insert segment which includes th into TCP reassembly
8237 		 * queue with control block tp.  Set thflags to whether
8238 		 * reassembly now includes a segment with FIN.  This handles
8239 		 * the common case inline (segment is the next to be
8240 		 * received on an established connection, and the queue is
8241 		 * empty), avoiding linkage into and removal from the queue
8242 		 * and repetition of various conversions. Set DELACK for
8243 		 * segments received in order, but ack immediately when
8244 		 * segments are out of order (so fast retransmit can work).
8245 		 */
8246 		if (th->th_seq == tp->rcv_nxt &&
8247 		    SEGQ_EMPTY(tp) &&
8248 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8249 		    tfo_syn)) {
8250 #ifdef NETFLIX_SB_LIMITS
8251 			u_int mcnt, appended;
8252 
8253 			if (so->so_rcv.sb_shlim) {
8254 				mcnt = m_memcnt(m);
8255 				appended = 0;
8256 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8257 				    CFO_NOSLEEP, NULL) == false) {
8258 					counter_u64_add(tcp_sb_shlim_fails, 1);
8259 					m_freem(m);
8260 					return (0);
8261 				}
8262 			}
8263 
8264 #endif
8265 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8266 				bbr->bbr_segs_rcvd += max(1, nsegs);
8267 				tp->t_flags |= TF_DELACK;
8268 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8269 			} else {
8270 				bbr->r_wanted_output = 1;
8271 				tp->t_flags |= TF_ACKNOW;
8272 			}
8273 			tp->rcv_nxt += tlen;
8274 			if (tlen &&
8275 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8276 			    (tp->t_fbyte_in == 0)) {
8277 				tp->t_fbyte_in = ticks;
8278 				if (tp->t_fbyte_in == 0)
8279 					tp->t_fbyte_in = 1;
8280 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8281 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8282 			}
8283 			thflags = tcp_get_flags(th) & TH_FIN;
8284 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8285 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8286 			SOCKBUF_LOCK(&so->so_rcv);
8287 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8288 				m_freem(m);
8289 			else
8290 #ifdef NETFLIX_SB_LIMITS
8291 				appended =
8292 #endif
8293 					sbappendstream_locked(&so->so_rcv, m, 0);
8294 			/* NB: sorwakeup_locked() does an implicit unlock. */
8295 			sorwakeup_locked(so);
8296 #ifdef NETFLIX_SB_LIMITS
8297 			if (so->so_rcv.sb_shlim && appended != mcnt)
8298 				counter_fo_release(so->so_rcv.sb_shlim,
8299 				    mcnt - appended);
8300 #endif
8301 
8302 		} else {
8303 			/*
8304 			 * XXX: Due to the header drop above "th" is
8305 			 * theoretically invalid by now.  Fortunately
8306 			 * m_adj() doesn't actually frees any mbufs when
8307 			 * trimming from the head.
8308 			 */
8309 			tcp_seq temp = save_start;
8310 
8311 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8312 			tp->t_flags |= TF_ACKNOW;
8313 			if (tp->t_flags & TF_WAKESOR) {
8314 				tp->t_flags &= ~TF_WAKESOR;
8315 				/* NB: sorwakeup_locked() does an implicit unlock. */
8316 				sorwakeup_locked(so);
8317 			}
8318 		}
8319 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8320 		    (save_tlen > 0) &&
8321 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8322 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8323 				/*
8324 				 * DSACK actually handled in the fastpath
8325 				 * above.
8326 				 */
8327 				tcp_update_sack_list(tp, save_start,
8328 				    save_start + save_tlen);
8329 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8330 				if ((tp->rcv_numsacks >= 1) &&
8331 				    (tp->sackblks[0].end == save_start)) {
8332 					/*
8333 					 * Partial overlap, recorded at todrop
8334 					 * above.
8335 					 */
8336 					tcp_update_sack_list(tp,
8337 					    tp->sackblks[0].start,
8338 					    tp->sackblks[0].end);
8339 				} else {
8340 					tcp_update_dsack_list(tp, save_start,
8341 					    save_start + save_tlen);
8342 				}
8343 			} else if (tlen >= save_tlen) {
8344 				/* Update of sackblks. */
8345 				tcp_update_dsack_list(tp, save_start,
8346 				    save_start + save_tlen);
8347 			} else if (tlen > 0) {
8348 				tcp_update_dsack_list(tp, save_start,
8349 				    save_start + tlen);
8350 			}
8351 		}
8352 	} else {
8353 		m_freem(m);
8354 		thflags &= ~TH_FIN;
8355 	}
8356 
8357 	/*
8358 	 * If FIN is received ACK the FIN and let the user know that the
8359 	 * connection is closing.
8360 	 */
8361 	if (thflags & TH_FIN) {
8362 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8363 			/* The socket upcall is handled by socantrcvmore. */
8364 			socantrcvmore(so);
8365 			/*
8366 			 * If connection is half-synchronized (ie NEEDSYN
8367 			 * flag on) then delay ACK, so it may be piggybacked
8368 			 * when SYN is sent. Otherwise, since we received a
8369 			 * FIN then no more input can be expected, send ACK
8370 			 * now.
8371 			 */
8372 			if (tp->t_flags & TF_NEEDSYN) {
8373 				tp->t_flags |= TF_DELACK;
8374 				bbr_timer_cancel(bbr,
8375 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8376 			} else {
8377 				tp->t_flags |= TF_ACKNOW;
8378 			}
8379 			tp->rcv_nxt++;
8380 		}
8381 		switch (tp->t_state) {
8382 			/*
8383 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8384 			 * CLOSE_WAIT state.
8385 			 */
8386 		case TCPS_SYN_RECEIVED:
8387 			tp->t_starttime = ticks;
8388 			/* FALLTHROUGH */
8389 		case TCPS_ESTABLISHED:
8390 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8391 			break;
8392 
8393 			/*
8394 			 * If still in FIN_WAIT_1 STATE FIN has not been
8395 			 * acked so enter the CLOSING state.
8396 			 */
8397 		case TCPS_FIN_WAIT_1:
8398 			tcp_state_change(tp, TCPS_CLOSING);
8399 			break;
8400 
8401 			/*
8402 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8403 			 * starting the time-wait timer, turning off the
8404 			 * other standard timers.
8405 			 */
8406 		case TCPS_FIN_WAIT_2:
8407 			bbr->rc_timer_first = 1;
8408 			bbr_timer_cancel(bbr,
8409 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8410 			INP_WLOCK_ASSERT(tp->t_inpcb);
8411 			tcp_twstart(tp);
8412 			return (1);
8413 		}
8414 	}
8415 	/*
8416 	 * Return any desired output.
8417 	 */
8418 	if ((tp->t_flags & TF_ACKNOW) ||
8419 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8420 		bbr->r_wanted_output = 1;
8421 	}
8422 	INP_WLOCK_ASSERT(tp->t_inpcb);
8423 	return (0);
8424 }
8425 
8426 /*
8427  * Here nothing is really faster, its just that we
8428  * have broken out the fast-data path also just like
8429  * the fast-ack. Return 1 if we processed the packet
8430  * return 0 if you need to take the "slow-path".
8431  */
8432 static int
8433 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8434     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8435     uint32_t tiwin, int32_t nxt_pkt)
8436 {
8437 	uint16_t nsegs;
8438 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8439 	struct tcp_bbr *bbr;
8440 #ifdef NETFLIX_SB_LIMITS
8441 	u_int mcnt, appended;
8442 #endif
8443 #ifdef TCPDEBUG
8444 	/*
8445 	 * The size of tcp_saveipgen must be the size of the max ip header,
8446 	 * now IPv6.
8447 	 */
8448 	u_char tcp_saveipgen[IP6_HDR_LEN];
8449 	struct tcphdr tcp_savetcp;
8450 	short ostate = 0;
8451 
8452 #endif
8453 	/* On the hpts and we would have called output */
8454 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8455 
8456 	/*
8457 	 * If last ACK falls within this segment's sequence numbers, record
8458 	 * the timestamp. NOTE that the test is modified according to the
8459 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8460 	 */
8461 	if (bbr->r_ctl.rc_resend != NULL) {
8462 		return (0);
8463 	}
8464 	if (tiwin && tiwin != tp->snd_wnd) {
8465 		return (0);
8466 	}
8467 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8468 		return (0);
8469 	}
8470 	if (__predict_false((to->to_flags & TOF_TS) &&
8471 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8472 		return (0);
8473 	}
8474 	if (__predict_false((th->th_ack != tp->snd_una))) {
8475 		return (0);
8476 	}
8477 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8478 		return (0);
8479 	}
8480 	if ((to->to_flags & TOF_TS) != 0 &&
8481 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8482 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8483 		tp->ts_recent = to->to_tsval;
8484 	}
8485 	/*
8486 	 * This is a pure, in-sequence data packet with nothing on the
8487 	 * reassembly queue and we have enough buffer space to take it.
8488 	 */
8489 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8490 
8491 #ifdef NETFLIX_SB_LIMITS
8492 	if (so->so_rcv.sb_shlim) {
8493 		mcnt = m_memcnt(m);
8494 		appended = 0;
8495 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8496 		    CFO_NOSLEEP, NULL) == false) {
8497 			counter_u64_add(tcp_sb_shlim_fails, 1);
8498 			m_freem(m);
8499 			return (1);
8500 		}
8501 	}
8502 #endif
8503 	/* Clean receiver SACK report if present */
8504 	if (tp->rcv_numsacks)
8505 		tcp_clean_sackreport(tp);
8506 	KMOD_TCPSTAT_INC(tcps_preddat);
8507 	tp->rcv_nxt += tlen;
8508 	if (tlen &&
8509 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8510 	    (tp->t_fbyte_in == 0)) {
8511 		tp->t_fbyte_in = ticks;
8512 		if (tp->t_fbyte_in == 0)
8513 			tp->t_fbyte_in = 1;
8514 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8515 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8516 	}
8517 	/*
8518 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8519 	 */
8520 	tp->snd_wl1 = th->th_seq;
8521 	/*
8522 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8523 	 */
8524 	tp->rcv_up = tp->rcv_nxt;
8525 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8526 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8527 #ifdef TCPDEBUG
8528 	if (so->so_options & SO_DEBUG)
8529 		tcp_trace(TA_INPUT, ostate, tp,
8530 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
8531 #endif
8532 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8533 
8534 	/* Add data to socket buffer. */
8535 	SOCKBUF_LOCK(&so->so_rcv);
8536 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8537 		m_freem(m);
8538 	} else {
8539 		/*
8540 		 * Set new socket buffer size. Give up when limit is
8541 		 * reached.
8542 		 */
8543 		if (newsize)
8544 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8545 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8546 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8547 
8548 #ifdef NETFLIX_SB_LIMITS
8549 		appended =
8550 #endif
8551 			sbappendstream_locked(&so->so_rcv, m, 0);
8552 		ctf_calc_rwin(so, tp);
8553 	}
8554 	/* NB: sorwakeup_locked() does an implicit unlock. */
8555 	sorwakeup_locked(so);
8556 #ifdef NETFLIX_SB_LIMITS
8557 	if (so->so_rcv.sb_shlim && mcnt != appended)
8558 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8559 #endif
8560 	if (DELAY_ACK(tp, bbr, nsegs)) {
8561 		bbr->bbr_segs_rcvd += max(1, nsegs);
8562 		tp->t_flags |= TF_DELACK;
8563 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8564 	} else {
8565 		bbr->r_wanted_output = 1;
8566 		tp->t_flags |= TF_ACKNOW;
8567 	}
8568 	return (1);
8569 }
8570 
8571 /*
8572  * This subfunction is used to try to highly optimize the
8573  * fast path. We again allow window updates that are
8574  * in sequence to remain in the fast-path. We also add
8575  * in the __predict's to attempt to help the compiler.
8576  * Note that if we return a 0, then we can *not* process
8577  * it and the caller should push the packet into the
8578  * slow-path. If we return 1, then all is well and
8579  * the packet is fully processed.
8580  */
8581 static int
8582 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8583     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8584     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8585 {
8586 	int32_t acked;
8587 	uint16_t nsegs;
8588 	uint32_t sack_changed;
8589 #ifdef TCPDEBUG
8590 	/*
8591 	 * The size of tcp_saveipgen must be the size of the max ip header,
8592 	 * now IPv6.
8593 	 */
8594 	u_char tcp_saveipgen[IP6_HDR_LEN];
8595 	struct tcphdr tcp_savetcp;
8596 	short ostate = 0;
8597 
8598 #endif
8599 	uint32_t prev_acked = 0;
8600 	struct tcp_bbr *bbr;
8601 
8602 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8603 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8604 		return (0);
8605 	}
8606 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8607 		/* Above what we have sent? */
8608 		return (0);
8609 	}
8610 	if (__predict_false(tiwin == 0)) {
8611 		/* zero window */
8612 		return (0);
8613 	}
8614 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8615 		/* We need a SYN or a FIN, unlikely.. */
8616 		return (0);
8617 	}
8618 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8619 		/* Timestamp is behind .. old ack with seq wrap? */
8620 		return (0);
8621 	}
8622 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8623 		/* Still recovering */
8624 		return (0);
8625 	}
8626 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8627 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8628 		/* We are retransmitting */
8629 		return (0);
8630 	}
8631 	if (__predict_false(bbr->rc_in_persist != 0)) {
8632 		/* In persist mode */
8633 		return (0);
8634 	}
8635 	if (bbr->r_ctl.rc_sacked) {
8636 		/* We have sack holes on our scoreboard */
8637 		return (0);
8638 	}
8639 	/* Ok if we reach here, we can process a fast-ack */
8640 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8641 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8642 	/*
8643 	 * We never detect loss in fast ack [we can't
8644 	 * have a sack and can't be in recovery so
8645 	 * we always pass 0 (nothing detected)].
8646 	 */
8647 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8648 	/* Did the window get updated? */
8649 	if (tiwin != tp->snd_wnd) {
8650 		tp->snd_wnd = tiwin;
8651 		tp->snd_wl1 = th->th_seq;
8652 		if (tp->snd_wnd > tp->max_sndwnd)
8653 			tp->max_sndwnd = tp->snd_wnd;
8654 	}
8655 	/* Do we need to exit persists? */
8656 	if ((bbr->rc_in_persist != 0) &&
8657 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8658 			       bbr_minseg(bbr)))) {
8659 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8660 		bbr->r_wanted_output = 1;
8661 	}
8662 	/* Do we need to enter persists? */
8663 	if ((bbr->rc_in_persist == 0) &&
8664 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8665 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8666 	    (tp->snd_max == tp->snd_una) &&
8667 	    sbavail(&tp->t_inpcb->inp_socket->so_snd) &&
8668 	    (sbavail(&tp->t_inpcb->inp_socket->so_snd) > tp->snd_wnd)) {
8669 		/* No send window.. we must enter persist */
8670 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8671 	}
8672 	/*
8673 	 * If last ACK falls within this segment's sequence numbers, record
8674 	 * the timestamp. NOTE that the test is modified according to the
8675 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8676 	 */
8677 	if ((to->to_flags & TOF_TS) != 0 &&
8678 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8679 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8680 		tp->ts_recent = to->to_tsval;
8681 	}
8682 	/*
8683 	 * This is a pure ack for outstanding data.
8684 	 */
8685 	KMOD_TCPSTAT_INC(tcps_predack);
8686 
8687 	/*
8688 	 * "bad retransmit" recovery.
8689 	 */
8690 	if (tp->t_flags & TF_PREVVALID) {
8691 		tp->t_flags &= ~TF_PREVVALID;
8692 		if (tp->t_rxtshift == 1 &&
8693 		    (int)(ticks - tp->t_badrxtwin) < 0)
8694 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8695 	}
8696 	/*
8697 	 * Recalculate the transmit timer / rtt.
8698 	 *
8699 	 * Some boxes send broken timestamp replies during the SYN+ACK
8700 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8701 	 * and blow up the retransmit timer.
8702 	 */
8703 	acked = BYTES_THIS_ACK(tp, th);
8704 
8705 #ifdef TCP_HHOOK
8706 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8707 	hhook_run_tcp_est_in(tp, th, to);
8708 #endif
8709 
8710 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8711 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8712 	sbdrop(&so->so_snd, acked);
8713 
8714 	if (SEQ_GT(th->th_ack, tp->snd_una))
8715 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8716 	tp->snd_una = th->th_ack;
8717 	if (tp->snd_wnd < ctf_outstanding(tp))
8718 		/* The peer collapsed its window on us */
8719 		bbr_collapsed_window(bbr);
8720 	else if (bbr->rc_has_collapsed)
8721 		bbr_un_collapse_window(bbr);
8722 
8723 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8724 		tp->snd_recover = tp->snd_una;
8725 	}
8726 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8727 	/*
8728 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8729 	 */
8730 	tp->snd_wl2 = th->th_ack;
8731 	m_freem(m);
8732 	/*
8733 	 * If all outstanding data are acked, stop retransmit timer,
8734 	 * otherwise restart timer using current (possibly backed-off)
8735 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8736 	 * If data are ready to send, let tcp_output decide between more
8737 	 * output or persist.
8738 	 */
8739 #ifdef TCPDEBUG
8740 	if (so->so_options & SO_DEBUG)
8741 		tcp_trace(TA_INPUT, ostate, tp,
8742 		    (void *)tcp_saveipgen,
8743 		    &tcp_savetcp, 0);
8744 #endif
8745 	/* Wake up the socket if we have room to write more */
8746 	sowwakeup(so);
8747 	if (tp->snd_una == tp->snd_max) {
8748 		/* Nothing left outstanding */
8749 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8750 		if (sbavail(&tp->t_inpcb->inp_socket->so_snd) == 0)
8751 			bbr->rc_tp->t_acktime = 0;
8752 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8753 		if (bbr->rc_in_persist == 0) {
8754 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8755 		}
8756 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8757 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8758 		/*
8759 		 * We invalidate the last ack here since we
8760 		 * don't want to transfer forward the time
8761 		 * for our sum's calculations.
8762 		 */
8763 		bbr->r_wanted_output = 1;
8764 	}
8765 	if (sbavail(&so->so_snd)) {
8766 		bbr->r_wanted_output = 1;
8767 	}
8768 	return (1);
8769 }
8770 
8771 /*
8772  * Return value of 1, the TCB is unlocked and most
8773  * likely gone, return value of 0, the TCB is still
8774  * locked.
8775  */
8776 static int
8777 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8778     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8779     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8780 {
8781 	int32_t todrop;
8782 	int32_t ourfinisacked = 0;
8783 	struct tcp_bbr *bbr;
8784 	int32_t ret_val = 0;
8785 
8786 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8787 	ctf_calc_rwin(so, tp);
8788 	/*
8789 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8790 	 * SYN, drop the input. if seg contains a RST, then drop the
8791 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8792 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8793 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8794 	 * not support ECN so we will not say we are capable. if SYN has
8795 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8796 	 * segment to be acked (eventually) continue processing rest of
8797 	 * data/controls, beginning with URG
8798 	 */
8799 	if ((thflags & TH_ACK) &&
8800 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8801 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8802 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8803 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8804 		return (1);
8805 	}
8806 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8807 		TCP_PROBE5(connect__refused, NULL, tp,
8808 		    mtod(m, const char *), tp, th);
8809 		tp = tcp_drop(tp, ECONNREFUSED);
8810 		ctf_do_drop(m, tp);
8811 		return (1);
8812 	}
8813 	if (thflags & TH_RST) {
8814 		ctf_do_drop(m, tp);
8815 		return (1);
8816 	}
8817 	if (!(thflags & TH_SYN)) {
8818 		ctf_do_drop(m, tp);
8819 		return (1);
8820 	}
8821 	tp->irs = th->th_seq;
8822 	tcp_rcvseqinit(tp);
8823 	if (thflags & TH_ACK) {
8824 		int tfo_partial = 0;
8825 
8826 		KMOD_TCPSTAT_INC(tcps_connects);
8827 		soisconnected(so);
8828 #ifdef MAC
8829 		mac_socketpeer_set_from_mbuf(m, so);
8830 #endif
8831 		/* Do window scaling on this connection? */
8832 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8833 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8834 			tp->rcv_scale = tp->request_r_scale;
8835 		}
8836 		tp->rcv_adv += min(tp->rcv_wnd,
8837 		    TCP_MAXWIN << tp->rcv_scale);
8838 		/*
8839 		 * If not all the data that was sent in the TFO SYN
8840 		 * has been acked, resend the remainder right away.
8841 		 */
8842 		if (IS_FASTOPEN(tp->t_flags) &&
8843 		    (tp->snd_una != tp->snd_max)) {
8844 			tp->snd_nxt = th->th_ack;
8845 			tfo_partial = 1;
8846 		}
8847 		/*
8848 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8849 		 * will be turned on later.
8850 		 */
8851 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8852 			bbr->bbr_segs_rcvd += 1;
8853 			tp->t_flags |= TF_DELACK;
8854 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8855 		} else {
8856 			bbr->r_wanted_output = 1;
8857 			tp->t_flags |= TF_ACKNOW;
8858 		}
8859 		if (SEQ_GT(th->th_ack, tp->iss)) {
8860 			/*
8861 			 * The SYN is acked
8862 			 * handle it specially.
8863 			 */
8864 			bbr_log_syn(tp, to);
8865 		}
8866 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8867 			/*
8868 			 * We advance snd_una for the
8869 			 * fast open case. If th_ack is
8870 			 * acknowledging data beyond
8871 			 * snd_una we can't just call
8872 			 * ack-processing since the
8873 			 * data stream in our send-map
8874 			 * will start at snd_una + 1 (one
8875 			 * beyond the SYN). If its just
8876 			 * equal we don't need to do that
8877 			 * and there is no send_map.
8878 			 */
8879 			tp->snd_una++;
8880 		}
8881 		/*
8882 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8883 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8884 		 */
8885 		tp->t_starttime = ticks;
8886 		if (tp->t_flags & TF_NEEDFIN) {
8887 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8888 			tp->t_flags &= ~TF_NEEDFIN;
8889 			thflags &= ~TH_SYN;
8890 		} else {
8891 			tcp_state_change(tp, TCPS_ESTABLISHED);
8892 			TCP_PROBE5(connect__established, NULL, tp,
8893 			    mtod(m, const char *), tp, th);
8894 			cc_conn_init(tp);
8895 		}
8896 	} else {
8897 		/*
8898 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8899 		 * open.  If segment contains CC option and there is a
8900 		 * cached CC, apply TAO test. If it succeeds, connection is *
8901 		 * half-synchronized. Otherwise, do 3-way handshake:
8902 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8903 		 * there was no CC option, clear cached CC value.
8904 		 */
8905 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
8906 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8907 	}
8908 	INP_WLOCK_ASSERT(tp->t_inpcb);
8909 	/*
8910 	 * Advance th->th_seq to correspond to first data byte. If data,
8911 	 * trim to stay within window, dropping FIN if necessary.
8912 	 */
8913 	th->th_seq++;
8914 	if (tlen > tp->rcv_wnd) {
8915 		todrop = tlen - tp->rcv_wnd;
8916 		m_adj(m, -todrop);
8917 		tlen = tp->rcv_wnd;
8918 		thflags &= ~TH_FIN;
8919 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8920 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8921 	}
8922 	tp->snd_wl1 = th->th_seq - 1;
8923 	tp->rcv_up = th->th_seq;
8924 	/*
8925 	 * Client side of transaction: already sent SYN and data. If the
8926 	 * remote host used T/TCP to validate the SYN, our data will be
8927 	 * ACK'd; if so, enter normal data segment processing in the middle
8928 	 * of step 5, ack processing. Otherwise, goto step 6.
8929 	 */
8930 	if (thflags & TH_ACK) {
8931 		if ((to->to_flags & TOF_TS) != 0) {
8932 			uint32_t t, rtt;
8933 
8934 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8935 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8936 				rtt = t - to->to_tsecr;
8937 				if (rtt == 0) {
8938 					rtt = 1;
8939 				}
8940 				rtt *= MS_IN_USEC;
8941 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8942 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8943 						       rtt, bbr->r_ctl.rc_rcvtime);
8944 			}
8945 		}
8946 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8947 			return (ret_val);
8948 		/* We may have changed to FIN_WAIT_1 above */
8949 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8950 			/*
8951 			 * In FIN_WAIT_1 STATE in addition to the processing
8952 			 * for the ESTABLISHED state if our FIN is now
8953 			 * acknowledged then enter FIN_WAIT_2.
8954 			 */
8955 			if (ourfinisacked) {
8956 				/*
8957 				 * If we can't receive any more data, then
8958 				 * closing user can proceed. Starting the
8959 				 * timer is contrary to the specification,
8960 				 * but if we don't get a FIN we'll hang
8961 				 * forever.
8962 				 *
8963 				 * XXXjl: we should release the tp also, and
8964 				 * use a compressed state.
8965 				 */
8966 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8967 					soisdisconnected(so);
8968 					tcp_timer_activate(tp, TT_2MSL,
8969 					    (tcp_fast_finwait2_recycle ?
8970 					    tcp_finwait2_timeout :
8971 					    TP_MAXIDLE(tp)));
8972 				}
8973 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8974 			}
8975 		}
8976 	}
8977 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8978 	    tiwin, thflags, nxt_pkt));
8979 }
8980 
8981 /*
8982  * Return value of 1, the TCB is unlocked and most
8983  * likely gone, return value of 0, the TCB is still
8984  * locked.
8985  */
8986 static int
8987 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8988 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8989 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8990 {
8991 	int32_t ourfinisacked = 0;
8992 	int32_t ret_val;
8993 	struct tcp_bbr *bbr;
8994 
8995 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8996 	ctf_calc_rwin(so, tp);
8997 	if ((thflags & TH_ACK) &&
8998 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8999 	     SEQ_GT(th->th_ack, tp->snd_max))) {
9000 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9001 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9002 		return (1);
9003 	}
9004 	if (IS_FASTOPEN(tp->t_flags)) {
9005 		/*
9006 		 * When a TFO connection is in SYN_RECEIVED, the only valid
9007 		 * packets are the initial SYN, a retransmit/copy of the
9008 		 * initial SYN (possibly with a subset of the original
9009 		 * data), a valid ACK, a FIN, or a RST.
9010 		 */
9011 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
9012 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9013 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9014 			return (1);
9015 		} else if (thflags & TH_SYN) {
9016 			/* non-initial SYN is ignored */
9017 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
9018 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
9019 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
9020 				ctf_do_drop(m, NULL);
9021 				return (0);
9022 			}
9023 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
9024 			ctf_do_drop(m, NULL);
9025 			return (0);
9026 		}
9027 	}
9028 	if ((thflags & TH_RST) ||
9029 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9030 		return (ctf_process_rst(m, th, so, tp));
9031 	/*
9032 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9033 	 * it's less than ts_recent, drop it.
9034 	 */
9035 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9036 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9037 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9038 			return (ret_val);
9039 	}
9040 	/*
9041 	 * In the SYN-RECEIVED state, validate that the packet belongs to
9042 	 * this connection before trimming the data to fit the receive
9043 	 * window.  Check the sequence number versus IRS since we know the
9044 	 * sequence numbers haven't wrapped.  This is a partial fix for the
9045 	 * "LAND" DoS attack.
9046 	 */
9047 	if (SEQ_LT(th->th_seq, tp->irs)) {
9048 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9049 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9050 		return (1);
9051 	}
9052 	INP_WLOCK_ASSERT(tp->t_inpcb);
9053 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9054 		return (ret_val);
9055 	}
9056 	/*
9057 	 * If last ACK falls within this segment's sequence numbers, record
9058 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9059 	 * from the latest proposal of the tcplw@cray.com list (Braden
9060 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9061 	 * with our earlier PAWS tests, so this check should be solely
9062 	 * predicated on the sequence space of this segment. 3) That we
9063 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9064 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9065 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9066 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9067 	 * p.869. In such cases, we can still calculate the RTT correctly
9068 	 * when RCV.NXT == Last.ACK.Sent.
9069 	 */
9070 	if ((to->to_flags & TOF_TS) != 0 &&
9071 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9072 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9073 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9074 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9075 		tp->ts_recent = to->to_tsval;
9076 	}
9077 	tp->snd_wnd = tiwin;
9078 	/*
9079 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9080 	 * is on (half-synchronized state), then queue data for later
9081 	 * processing; else drop segment and return.
9082 	 */
9083 	if ((thflags & TH_ACK) == 0) {
9084 		if (IS_FASTOPEN(tp->t_flags)) {
9085 			cc_conn_init(tp);
9086 		}
9087 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9088 					 tiwin, thflags, nxt_pkt));
9089 	}
9090 	KMOD_TCPSTAT_INC(tcps_connects);
9091 	soisconnected(so);
9092 	/* Do window scaling? */
9093 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9094 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9095 		tp->rcv_scale = tp->request_r_scale;
9096 	}
9097 	/*
9098 	 * ok for the first time in lets see if we can use the ts to figure
9099 	 * out what the initial RTT was.
9100 	 */
9101 	if ((to->to_flags & TOF_TS) != 0) {
9102 		uint32_t t, rtt;
9103 
9104 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9105 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9106 			rtt = t - to->to_tsecr;
9107 			if (rtt == 0) {
9108 				rtt = 1;
9109 			}
9110 			rtt *= MS_IN_USEC;
9111 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9112 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9113 		}
9114 	}
9115 	/* Drop off any SYN in the send map (probably not there)  */
9116 	if (thflags & TH_ACK)
9117 		bbr_log_syn(tp, to);
9118 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9119 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9120 		tp->t_tfo_pending = NULL;
9121 	}
9122 	/*
9123 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9124 	 * FIN-WAIT-1
9125 	 */
9126 	tp->t_starttime = ticks;
9127 	if (tp->t_flags & TF_NEEDFIN) {
9128 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9129 		tp->t_flags &= ~TF_NEEDFIN;
9130 	} else {
9131 		tcp_state_change(tp, TCPS_ESTABLISHED);
9132 		TCP_PROBE5(accept__established, NULL, tp,
9133 			   mtod(m, const char *), tp, th);
9134 		/*
9135 		 * TFO connections call cc_conn_init() during SYN
9136 		 * processing.  Calling it again here for such connections
9137 		 * is not harmless as it would undo the snd_cwnd reduction
9138 		 * that occurs when a TFO SYN|ACK is retransmitted.
9139 		 */
9140 		if (!IS_FASTOPEN(tp->t_flags))
9141 			cc_conn_init(tp);
9142 	}
9143 	/*
9144 	 * Account for the ACK of our SYN prior to
9145 	 * regular ACK processing below, except for
9146 	 * simultaneous SYN, which is handled later.
9147 	 */
9148 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9149 		tp->snd_una++;
9150 	/*
9151 	 * If segment contains data or ACK, will call tcp_reass() later; if
9152 	 * not, do so now to pass queued data to user.
9153 	 */
9154 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9155 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9156 			(struct mbuf *)0);
9157 		if (tp->t_flags & TF_WAKESOR) {
9158 			tp->t_flags &= ~TF_WAKESOR;
9159 			/* NB: sorwakeup_locked() does an implicit unlock. */
9160 			sorwakeup_locked(so);
9161 		}
9162 	}
9163 	tp->snd_wl1 = th->th_seq - 1;
9164 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9165 		return (ret_val);
9166 	}
9167 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9168 		/* We could have went to FIN_WAIT_1 (or EST) above */
9169 		/*
9170 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9171 		 * ESTABLISHED state if our FIN is now acknowledged then
9172 		 * enter FIN_WAIT_2.
9173 		 */
9174 		if (ourfinisacked) {
9175 			/*
9176 			 * If we can't receive any more data, then closing
9177 			 * user can proceed. Starting the timer is contrary
9178 			 * to the specification, but if we don't get a FIN
9179 			 * we'll hang forever.
9180 			 *
9181 			 * XXXjl: we should release the tp also, and use a
9182 			 * compressed state.
9183 			 */
9184 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9185 				soisdisconnected(so);
9186 				tcp_timer_activate(tp, TT_2MSL,
9187 						   (tcp_fast_finwait2_recycle ?
9188 						    tcp_finwait2_timeout :
9189 						    TP_MAXIDLE(tp)));
9190 			}
9191 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9192 		}
9193 	}
9194 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9195 				 tiwin, thflags, nxt_pkt));
9196 }
9197 
9198 /*
9199  * Return value of 1, the TCB is unlocked and most
9200  * likely gone, return value of 0, the TCB is still
9201  * locked.
9202  */
9203 static int
9204 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9205     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9206     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9207 {
9208 	struct tcp_bbr *bbr;
9209 	int32_t ret_val;
9210 
9211 	/*
9212 	 * Header prediction: check for the two common cases of a
9213 	 * uni-directional data xfer.  If the packet has no control flags,
9214 	 * is in-sequence, the window didn't change and we're not
9215 	 * retransmitting, it's a candidate.  If the length is zero and the
9216 	 * ack moved forward, we're the sender side of the xfer.  Just free
9217 	 * the data acked & wake any higher level process that was blocked
9218 	 * waiting for space.  If the length is non-zero and the ack didn't
9219 	 * move, we're the receiver side.  If we're getting packets in-order
9220 	 * (the reassembly queue is empty), add the data toc The socket
9221 	 * buffer and note that we need a delayed ack. Make sure that the
9222 	 * hidden state-flags are also off. Since we check for
9223 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9224 	 */
9225 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9226 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9227 		/*
9228 		 * If we have delived under 4 segments increase the initial
9229 		 * window if raised by the peer. We use this to determine
9230 		 * dynamic and static rwnd's at the end of a connection.
9231 		 */
9232 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9233 	}
9234 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9235 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9236 	    __predict_true(SEGQ_EMPTY(tp)) &&
9237 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9238 		if (tlen == 0) {
9239 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9240 			    tiwin, nxt_pkt, iptos)) {
9241 				return (0);
9242 			}
9243 		} else {
9244 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9245 			    tiwin, nxt_pkt)) {
9246 				return (0);
9247 			}
9248 		}
9249 	}
9250 	ctf_calc_rwin(so, tp);
9251 
9252 	if ((thflags & TH_RST) ||
9253 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9254 		return (ctf_process_rst(m, th, so, tp));
9255 	/*
9256 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9257 	 * synchronized state.
9258 	 */
9259 	if (thflags & TH_SYN) {
9260 		ctf_challenge_ack(m, th, tp, &ret_val);
9261 		return (ret_val);
9262 	}
9263 	/*
9264 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9265 	 * it's less than ts_recent, drop it.
9266 	 */
9267 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9268 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9269 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9270 			return (ret_val);
9271 	}
9272 	INP_WLOCK_ASSERT(tp->t_inpcb);
9273 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9274 		return (ret_val);
9275 	}
9276 	/*
9277 	 * If last ACK falls within this segment's sequence numbers, record
9278 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9279 	 * from the latest proposal of the tcplw@cray.com list (Braden
9280 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9281 	 * with our earlier PAWS tests, so this check should be solely
9282 	 * predicated on the sequence space of this segment. 3) That we
9283 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9284 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9285 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9286 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9287 	 * p.869. In such cases, we can still calculate the RTT correctly
9288 	 * when RCV.NXT == Last.ACK.Sent.
9289 	 */
9290 	if ((to->to_flags & TOF_TS) != 0 &&
9291 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9292 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9293 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9294 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9295 		tp->ts_recent = to->to_tsval;
9296 	}
9297 	/*
9298 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9299 	 * is on (half-synchronized state), then queue data for later
9300 	 * processing; else drop segment and return.
9301 	 */
9302 	if ((thflags & TH_ACK) == 0) {
9303 		if (tp->t_flags & TF_NEEDSYN) {
9304 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9305 			    tiwin, thflags, nxt_pkt));
9306 		} else if (tp->t_flags & TF_ACKNOW) {
9307 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9308 			bbr->r_wanted_output = 1;
9309 			return (ret_val);
9310 		} else {
9311 			ctf_do_drop(m, NULL);
9312 			return (0);
9313 		}
9314 	}
9315 	/*
9316 	 * Ack processing.
9317 	 */
9318 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9319 		return (ret_val);
9320 	}
9321 	if (sbavail(&so->so_snd)) {
9322 		if (ctf_progress_timeout_check(tp, true)) {
9323 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9324 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9325 			return (1);
9326 		}
9327 	}
9328 	/* State changes only happen in bbr_process_data() */
9329 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9330 	    tiwin, thflags, nxt_pkt));
9331 }
9332 
9333 /*
9334  * Return value of 1, the TCB is unlocked and most
9335  * likely gone, return value of 0, the TCB is still
9336  * locked.
9337  */
9338 static int
9339 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9340     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9341     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9342 {
9343 	struct tcp_bbr *bbr;
9344 	int32_t ret_val;
9345 
9346 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9347 	ctf_calc_rwin(so, tp);
9348 	if ((thflags & TH_RST) ||
9349 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9350 		return (ctf_process_rst(m, th, so, tp));
9351 	/*
9352 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9353 	 * synchronized state.
9354 	 */
9355 	if (thflags & TH_SYN) {
9356 		ctf_challenge_ack(m, th, tp, &ret_val);
9357 		return (ret_val);
9358 	}
9359 	/*
9360 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9361 	 * it's less than ts_recent, drop it.
9362 	 */
9363 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9364 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9365 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9366 			return (ret_val);
9367 	}
9368 	INP_WLOCK_ASSERT(tp->t_inpcb);
9369 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9370 		return (ret_val);
9371 	}
9372 	/*
9373 	 * If last ACK falls within this segment's sequence numbers, record
9374 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9375 	 * from the latest proposal of the tcplw@cray.com list (Braden
9376 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9377 	 * with our earlier PAWS tests, so this check should be solely
9378 	 * predicated on the sequence space of this segment. 3) That we
9379 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9380 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9381 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9382 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9383 	 * p.869. In such cases, we can still calculate the RTT correctly
9384 	 * when RCV.NXT == Last.ACK.Sent.
9385 	 */
9386 	if ((to->to_flags & TOF_TS) != 0 &&
9387 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9388 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9389 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9390 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9391 		tp->ts_recent = to->to_tsval;
9392 	}
9393 	/*
9394 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9395 	 * is on (half-synchronized state), then queue data for later
9396 	 * processing; else drop segment and return.
9397 	 */
9398 	if ((thflags & TH_ACK) == 0) {
9399 		if (tp->t_flags & TF_NEEDSYN) {
9400 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9401 			    tiwin, thflags, nxt_pkt));
9402 		} else if (tp->t_flags & TF_ACKNOW) {
9403 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9404 			bbr->r_wanted_output = 1;
9405 			return (ret_val);
9406 		} else {
9407 			ctf_do_drop(m, NULL);
9408 			return (0);
9409 		}
9410 	}
9411 	/*
9412 	 * Ack processing.
9413 	 */
9414 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9415 		return (ret_val);
9416 	}
9417 	if (sbavail(&so->so_snd)) {
9418 		if (ctf_progress_timeout_check(tp, true)) {
9419 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9420 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9421 			return (1);
9422 		}
9423 	}
9424 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9425 	    tiwin, thflags, nxt_pkt));
9426 }
9427 
9428 static int
9429 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9430     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9431 {
9432 
9433 	if (bbr->rc_allow_data_af_clo == 0) {
9434 close_now:
9435 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9436 		/* tcp_close will kill the inp pre-log the Reset */
9437 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9438 		tp = tcp_close(tp);
9439 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9440 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9441 		return (1);
9442 	}
9443 	if (sbavail(&so->so_snd) == 0)
9444 		goto close_now;
9445 	/* Ok we allow data that is ignored and a followup reset */
9446 	tp->rcv_nxt = th->th_seq + *tlen;
9447 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9448 	bbr->r_wanted_output = 1;
9449 	*tlen = 0;
9450 	return (0);
9451 }
9452 
9453 /*
9454  * Return value of 1, the TCB is unlocked and most
9455  * likely gone, return value of 0, the TCB is still
9456  * locked.
9457  */
9458 static int
9459 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9460     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9461     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9462 {
9463 	int32_t ourfinisacked = 0;
9464 	int32_t ret_val;
9465 	struct tcp_bbr *bbr;
9466 
9467 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9468 	ctf_calc_rwin(so, tp);
9469 	if ((thflags & TH_RST) ||
9470 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9471 		return (ctf_process_rst(m, th, so, tp));
9472 	/*
9473 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9474 	 * synchronized state.
9475 	 */
9476 	if (thflags & TH_SYN) {
9477 		ctf_challenge_ack(m, th, tp, &ret_val);
9478 		return (ret_val);
9479 	}
9480 	/*
9481 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9482 	 * it's less than ts_recent, drop it.
9483 	 */
9484 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9485 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9486 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9487 			return (ret_val);
9488 	}
9489 	INP_WLOCK_ASSERT(tp->t_inpcb);
9490 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9491 		return (ret_val);
9492 	}
9493 	/*
9494 	 * If new data are received on a connection after the user processes
9495 	 * are gone, then RST the other end.
9496 	 */
9497 	if ((so->so_state & SS_NOFDREF) && tlen) {
9498 		/*
9499 		 * We call a new function now so we might continue and setup
9500 		 * to reset at all data being ack'd.
9501 		 */
9502 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9503 			return (1);
9504 	}
9505 	/*
9506 	 * If last ACK falls within this segment's sequence numbers, record
9507 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9508 	 * from the latest proposal of the tcplw@cray.com list (Braden
9509 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9510 	 * with our earlier PAWS tests, so this check should be solely
9511 	 * predicated on the sequence space of this segment. 3) That we
9512 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9513 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9514 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9515 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9516 	 * p.869. In such cases, we can still calculate the RTT correctly
9517 	 * when RCV.NXT == Last.ACK.Sent.
9518 	 */
9519 	if ((to->to_flags & TOF_TS) != 0 &&
9520 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9521 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9522 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9523 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9524 		tp->ts_recent = to->to_tsval;
9525 	}
9526 	/*
9527 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9528 	 * is on (half-synchronized state), then queue data for later
9529 	 * processing; else drop segment and return.
9530 	 */
9531 	if ((thflags & TH_ACK) == 0) {
9532 		if (tp->t_flags & TF_NEEDSYN) {
9533 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9534 			    tiwin, thflags, nxt_pkt));
9535 		} else if (tp->t_flags & TF_ACKNOW) {
9536 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9537 			bbr->r_wanted_output = 1;
9538 			return (ret_val);
9539 		} else {
9540 			ctf_do_drop(m, NULL);
9541 			return (0);
9542 		}
9543 	}
9544 	/*
9545 	 * Ack processing.
9546 	 */
9547 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9548 		return (ret_val);
9549 	}
9550 	if (ourfinisacked) {
9551 		/*
9552 		 * If we can't receive any more data, then closing user can
9553 		 * proceed. Starting the timer is contrary to the
9554 		 * specification, but if we don't get a FIN we'll hang
9555 		 * forever.
9556 		 *
9557 		 * XXXjl: we should release the tp also, and use a
9558 		 * compressed state.
9559 		 */
9560 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9561 			soisdisconnected(so);
9562 			tcp_timer_activate(tp, TT_2MSL,
9563 			    (tcp_fast_finwait2_recycle ?
9564 			    tcp_finwait2_timeout :
9565 			    TP_MAXIDLE(tp)));
9566 		}
9567 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9568 	}
9569 	if (sbavail(&so->so_snd)) {
9570 		if (ctf_progress_timeout_check(tp, true)) {
9571 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9572 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9573 			return (1);
9574 		}
9575 	}
9576 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9577 	    tiwin, thflags, nxt_pkt));
9578 }
9579 
9580 /*
9581  * Return value of 1, the TCB is unlocked and most
9582  * likely gone, return value of 0, the TCB is still
9583  * locked.
9584  */
9585 static int
9586 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9587     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9588     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9589 {
9590 	int32_t ourfinisacked = 0;
9591 	int32_t ret_val;
9592 	struct tcp_bbr *bbr;
9593 
9594 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9595 	ctf_calc_rwin(so, tp);
9596 	if ((thflags & TH_RST) ||
9597 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9598 		return (ctf_process_rst(m, th, so, tp));
9599 	/*
9600 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9601 	 * synchronized state.
9602 	 */
9603 	if (thflags & TH_SYN) {
9604 		ctf_challenge_ack(m, th, tp, &ret_val);
9605 		return (ret_val);
9606 	}
9607 	/*
9608 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9609 	 * it's less than ts_recent, drop it.
9610 	 */
9611 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9612 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9613 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9614 			return (ret_val);
9615 	}
9616 	INP_WLOCK_ASSERT(tp->t_inpcb);
9617 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9618 		return (ret_val);
9619 	}
9620 	/*
9621 	 * If new data are received on a connection after the user processes
9622 	 * are gone, then RST the other end.
9623 	 */
9624 	if ((so->so_state & SS_NOFDREF) && tlen) {
9625 		/*
9626 		 * We call a new function now so we might continue and setup
9627 		 * to reset at all data being ack'd.
9628 		 */
9629 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9630 			return (1);
9631 	}
9632 	/*
9633 	 * If last ACK falls within this segment's sequence numbers, record
9634 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9635 	 * from the latest proposal of the tcplw@cray.com list (Braden
9636 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9637 	 * with our earlier PAWS tests, so this check should be solely
9638 	 * predicated on the sequence space of this segment. 3) That we
9639 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9640 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9641 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9642 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9643 	 * p.869. In such cases, we can still calculate the RTT correctly
9644 	 * when RCV.NXT == Last.ACK.Sent.
9645 	 */
9646 	if ((to->to_flags & TOF_TS) != 0 &&
9647 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9648 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9649 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9650 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9651 		tp->ts_recent = to->to_tsval;
9652 	}
9653 	/*
9654 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9655 	 * is on (half-synchronized state), then queue data for later
9656 	 * processing; else drop segment and return.
9657 	 */
9658 	if ((thflags & TH_ACK) == 0) {
9659 		if (tp->t_flags & TF_NEEDSYN) {
9660 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9661 			    tiwin, thflags, nxt_pkt));
9662 		} else if (tp->t_flags & TF_ACKNOW) {
9663 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9664 			bbr->r_wanted_output = 1;
9665 			return (ret_val);
9666 		} else {
9667 			ctf_do_drop(m, NULL);
9668 			return (0);
9669 		}
9670 	}
9671 	/*
9672 	 * Ack processing.
9673 	 */
9674 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9675 		return (ret_val);
9676 	}
9677 	if (ourfinisacked) {
9678 		tcp_twstart(tp);
9679 		m_freem(m);
9680 		return (1);
9681 	}
9682 	if (sbavail(&so->so_snd)) {
9683 		if (ctf_progress_timeout_check(tp, true)) {
9684 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9685 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9686 			return (1);
9687 		}
9688 	}
9689 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9690 	    tiwin, thflags, nxt_pkt));
9691 }
9692 
9693 /*
9694  * Return value of 1, the TCB is unlocked and most
9695  * likely gone, return value of 0, the TCB is still
9696  * locked.
9697  */
9698 static int
9699 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9700     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9701     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9702 {
9703 	int32_t ourfinisacked = 0;
9704 	int32_t ret_val;
9705 	struct tcp_bbr *bbr;
9706 
9707 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9708 	ctf_calc_rwin(so, tp);
9709 	if ((thflags & TH_RST) ||
9710 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9711 		return (ctf_process_rst(m, th, so, tp));
9712 	/*
9713 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9714 	 * synchronized state.
9715 	 */
9716 	if (thflags & TH_SYN) {
9717 		ctf_challenge_ack(m, th, tp, &ret_val);
9718 		return (ret_val);
9719 	}
9720 	/*
9721 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9722 	 * it's less than ts_recent, drop it.
9723 	 */
9724 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9725 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9726 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9727 			return (ret_val);
9728 	}
9729 	INP_WLOCK_ASSERT(tp->t_inpcb);
9730 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9731 		return (ret_val);
9732 	}
9733 	/*
9734 	 * If new data are received on a connection after the user processes
9735 	 * are gone, then RST the other end.
9736 	 */
9737 	if ((so->so_state & SS_NOFDREF) && tlen) {
9738 		/*
9739 		 * We call a new function now so we might continue and setup
9740 		 * to reset at all data being ack'd.
9741 		 */
9742 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9743 			return (1);
9744 	}
9745 	/*
9746 	 * If last ACK falls within this segment's sequence numbers, record
9747 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9748 	 * from the latest proposal of the tcplw@cray.com list (Braden
9749 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9750 	 * with our earlier PAWS tests, so this check should be solely
9751 	 * predicated on the sequence space of this segment. 3) That we
9752 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9753 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9754 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9755 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9756 	 * p.869. In such cases, we can still calculate the RTT correctly
9757 	 * when RCV.NXT == Last.ACK.Sent.
9758 	 */
9759 	if ((to->to_flags & TOF_TS) != 0 &&
9760 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9761 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9762 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9763 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9764 		tp->ts_recent = to->to_tsval;
9765 	}
9766 	/*
9767 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9768 	 * is on (half-synchronized state), then queue data for later
9769 	 * processing; else drop segment and return.
9770 	 */
9771 	if ((thflags & TH_ACK) == 0) {
9772 		if (tp->t_flags & TF_NEEDSYN) {
9773 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9774 			    tiwin, thflags, nxt_pkt));
9775 		} else if (tp->t_flags & TF_ACKNOW) {
9776 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9777 			bbr->r_wanted_output = 1;
9778 			return (ret_val);
9779 		} else {
9780 			ctf_do_drop(m, NULL);
9781 			return (0);
9782 		}
9783 	}
9784 	/*
9785 	 * case TCPS_LAST_ACK: Ack processing.
9786 	 */
9787 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9788 		return (ret_val);
9789 	}
9790 	if (ourfinisacked) {
9791 		tp = tcp_close(tp);
9792 		ctf_do_drop(m, tp);
9793 		return (1);
9794 	}
9795 	if (sbavail(&so->so_snd)) {
9796 		if (ctf_progress_timeout_check(tp, true)) {
9797 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9798 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9799 			return (1);
9800 		}
9801 	}
9802 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9803 	    tiwin, thflags, nxt_pkt));
9804 }
9805 
9806 /*
9807  * Return value of 1, the TCB is unlocked and most
9808  * likely gone, return value of 0, the TCB is still
9809  * locked.
9810  */
9811 static int
9812 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9813     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9814     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9815 {
9816 	int32_t ourfinisacked = 0;
9817 	int32_t ret_val;
9818 	struct tcp_bbr *bbr;
9819 
9820 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9821 	ctf_calc_rwin(so, tp);
9822 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9823 	if ((thflags & TH_RST) ||
9824 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9825 		return (ctf_process_rst(m, th, so, tp));
9826 
9827 	/*
9828 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9829 	 * synchronized state.
9830 	 */
9831 	if (thflags & TH_SYN) {
9832 		ctf_challenge_ack(m, th, tp, &ret_val);
9833 		return (ret_val);
9834 	}
9835 	INP_WLOCK_ASSERT(tp->t_inpcb);
9836 	/*
9837 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9838 	 * it's less than ts_recent, drop it.
9839 	 */
9840 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9841 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9842 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9843 			return (ret_val);
9844 	}
9845 	INP_WLOCK_ASSERT(tp->t_inpcb);
9846 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9847 		return (ret_val);
9848 	}
9849 	/*
9850 	 * If new data are received on a connection after the user processes
9851 	 * are gone, then we may RST the other end depending on the outcome
9852 	 * of bbr_check_data_after_close.
9853 	 */
9854 	if ((so->so_state & SS_NOFDREF) &&
9855 	    tlen) {
9856 		/*
9857 		 * We call a new function now so we might continue and setup
9858 		 * to reset at all data being ack'd.
9859 		 */
9860 		if (bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9861 			return (1);
9862 	}
9863 	INP_WLOCK_ASSERT(tp->t_inpcb);
9864 	/*
9865 	 * If last ACK falls within this segment's sequence numbers, record
9866 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9867 	 * from the latest proposal of the tcplw@cray.com list (Braden
9868 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9869 	 * with our earlier PAWS tests, so this check should be solely
9870 	 * predicated on the sequence space of this segment. 3) That we
9871 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9872 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9873 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9874 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9875 	 * p.869. In such cases, we can still calculate the RTT correctly
9876 	 * when RCV.NXT == Last.ACK.Sent.
9877 	 */
9878 	INP_WLOCK_ASSERT(tp->t_inpcb);
9879 	if ((to->to_flags & TOF_TS) != 0 &&
9880 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9881 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9882 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9883 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9884 		tp->ts_recent = to->to_tsval;
9885 	}
9886 	/*
9887 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9888 	 * is on (half-synchronized state), then queue data for later
9889 	 * processing; else drop segment and return.
9890 	 */
9891 	if ((thflags & TH_ACK) == 0) {
9892 		if (tp->t_flags & TF_NEEDSYN) {
9893 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9894 			    tiwin, thflags, nxt_pkt));
9895 		} else if (tp->t_flags & TF_ACKNOW) {
9896 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9897 			bbr->r_wanted_output = 1;
9898 			return (ret_val);
9899 		} else {
9900 			ctf_do_drop(m, NULL);
9901 			return (0);
9902 		}
9903 	}
9904 	/*
9905 	 * Ack processing.
9906 	 */
9907 	INP_WLOCK_ASSERT(tp->t_inpcb);
9908 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9909 		return (ret_val);
9910 	}
9911 	if (sbavail(&so->so_snd)) {
9912 		if (ctf_progress_timeout_check(tp, true)) {
9913 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9914 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9915 			return (1);
9916 		}
9917 	}
9918 	INP_WLOCK_ASSERT(tp->t_inpcb);
9919 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9920 	    tiwin, thflags, nxt_pkt));
9921 }
9922 
9923 static void
9924 bbr_stop_all_timers(struct tcpcb *tp)
9925 {
9926 	struct tcp_bbr *bbr;
9927 
9928 	/*
9929 	 * Assure no timers are running.
9930 	 */
9931 	if (tcp_timer_active(tp, TT_PERSIST)) {
9932 		/* We enter in persists, set the flag appropriately */
9933 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9934 		bbr->rc_in_persist = 1;
9935 	}
9936 	tcp_timer_suspend(tp, TT_PERSIST);
9937 	tcp_timer_suspend(tp, TT_REXMT);
9938 	tcp_timer_suspend(tp, TT_KEEP);
9939 	tcp_timer_suspend(tp, TT_DELACK);
9940 }
9941 
9942 static void
9943 bbr_google_mode_on(struct tcp_bbr *bbr)
9944 {
9945 	bbr->rc_use_google = 1;
9946 	bbr->rc_no_pacing = 0;
9947 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9948 	bbr->r_use_policer = bbr_policer_detection_enabled;
9949 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9950 	bbr->bbr_use_rack_cheat = 0;
9951 	bbr->r_ctl.rc_incr_tmrs = 0;
9952 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9953 	bbr->r_ctl.rc_inc_ip_oh = 0;
9954 	bbr->r_ctl.rc_inc_enet_oh = 0;
9955 	reset_time(&bbr->r_ctl.rc_delrate,
9956 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9957 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9958 			 (11 * USECS_IN_SECOND));
9959 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9960 }
9961 
9962 static void
9963 bbr_google_mode_off(struct tcp_bbr *bbr)
9964 {
9965 	bbr->rc_use_google = 0;
9966 	bbr->r_ctl.bbr_google_discount = 0;
9967 	bbr->no_pacing_until = bbr_no_pacing_until;
9968 	bbr->r_use_policer = 0;
9969 	if (bbr->no_pacing_until)
9970 		bbr->rc_no_pacing = 1;
9971 	else
9972 		bbr->rc_no_pacing = 0;
9973 	if (bbr_use_rack_resend_cheat)
9974 		bbr->bbr_use_rack_cheat = 1;
9975 	else
9976 		bbr->bbr_use_rack_cheat = 0;
9977 	if (bbr_incr_timers)
9978 		bbr->r_ctl.rc_incr_tmrs = 1;
9979 	else
9980 		bbr->r_ctl.rc_incr_tmrs = 0;
9981 	if (bbr_include_tcp_oh)
9982 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9983 	else
9984 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9985 	if (bbr_include_ip_oh)
9986 		bbr->r_ctl.rc_inc_ip_oh = 1;
9987 	else
9988 		bbr->r_ctl.rc_inc_ip_oh = 0;
9989 	if (bbr_include_enet_oh)
9990 		bbr->r_ctl.rc_inc_enet_oh = 1;
9991 	else
9992 		bbr->r_ctl.rc_inc_enet_oh = 0;
9993 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9994 	reset_time(&bbr->r_ctl.rc_delrate,
9995 		   bbr_num_pktepo_for_del_limit);
9996 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9997 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9998 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9999 }
10000 /*
10001  * Return 0 on success, non-zero on failure
10002  * which indicates the error (usually no memory).
10003  */
10004 static int
10005 bbr_init(struct tcpcb *tp)
10006 {
10007 	struct tcp_bbr *bbr = NULL;
10008 	struct inpcb *inp;
10009 	uint32_t cts;
10010 
10011 	tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
10012 	if (tp->t_fb_ptr == NULL) {
10013 		/*
10014 		 * We need to allocate memory but cant. The INP and INP_INFO
10015 		 * locks and they are recursive (happens during setup. So a
10016 		 * scheme to drop the locks fails :(
10017 		 *
10018 		 */
10019 		return (ENOMEM);
10020 	}
10021 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10022 	bbr->rtt_valid = 0;
10023 	inp = tp->t_inpcb;
10024 	inp->inp_flags2 |= INP_CANNOT_DO_ECN;
10025 	inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
10026 	TAILQ_INIT(&bbr->r_ctl.rc_map);
10027 	TAILQ_INIT(&bbr->r_ctl.rc_free);
10028 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
10029 	bbr->rc_tp = tp;
10030 	if (tp->t_inpcb) {
10031 		bbr->rc_inp = tp->t_inpcb;
10032 	}
10033 	cts = tcp_get_usecs(&bbr->rc_tv);
10034 	tp->t_acktime = 0;
10035 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
10036 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
10037 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
10038 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
10039 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
10040 	bbr->r_ctl.rc_min_to = bbr_min_to;
10041 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
10042 	bbr->r_ctl.bbr_lost_at_state = 0;
10043 	bbr->r_ctl.rc_lost_at_startup = 0;
10044 	bbr->rc_all_timers_stopped = 0;
10045 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10046 	bbr->r_ctl.rc_pkt_epoch_del = 0;
10047 	bbr->r_ctl.rc_pkt_epoch = 0;
10048 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10049 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10050 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10051 	bbr->r_ctl.rc_went_idle_time = cts;
10052 	bbr->rc_pacer_started = cts;
10053 	bbr->r_ctl.rc_pkt_epoch_time = cts;
10054 	bbr->r_ctl.rc_rcvtime = cts;
10055 	bbr->r_ctl.rc_bbr_state_time = cts;
10056 	bbr->r_ctl.rc_del_time = cts;
10057 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10058 	bbr->r_ctl.last_in_probertt = cts;
10059 	bbr->skip_gain = 0;
10060 	bbr->gain_is_limited = 0;
10061 	bbr->no_pacing_until = bbr_no_pacing_until;
10062 	if (bbr->no_pacing_until)
10063 		bbr->rc_no_pacing = 1;
10064 	if (bbr_use_google_algo) {
10065 		bbr->rc_no_pacing = 0;
10066 		bbr->rc_use_google = 1;
10067 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10068 		bbr->r_use_policer = bbr_policer_detection_enabled;
10069 	} else {
10070 		bbr->rc_use_google = 0;
10071 		bbr->r_ctl.bbr_google_discount = 0;
10072 		bbr->r_use_policer = 0;
10073 	}
10074 	if (bbr_ts_limiting)
10075 		bbr->rc_use_ts_limit = 1;
10076 	else
10077 		bbr->rc_use_ts_limit = 0;
10078 	if (bbr_ts_can_raise)
10079 		bbr->ts_can_raise = 1;
10080 	else
10081 		bbr->ts_can_raise = 0;
10082 	if (V_tcp_delack_enabled == 1)
10083 		tp->t_delayed_ack = 2;
10084 	else if (V_tcp_delack_enabled == 0)
10085 		tp->t_delayed_ack = 0;
10086 	else if (V_tcp_delack_enabled < 100)
10087 		tp->t_delayed_ack = V_tcp_delack_enabled;
10088 	else
10089 		tp->t_delayed_ack = 2;
10090 	if (bbr->rc_use_google == 0)
10091 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10092 	else
10093 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10094 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10095 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10096 	bbr->rc_init_win = bbr_def_init_win;
10097 	if (tp->t_flags & TF_REQ_TSTMP)
10098 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10099 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10100 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10101 	bbr->r_init_rtt = 1;
10102 
10103 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10104 	if (bbr_allow_hdwr_pacing)
10105 		bbr->bbr_hdw_pace_ena = 1;
10106 	else
10107 		bbr->bbr_hdw_pace_ena = 0;
10108 	if (bbr_sends_full_iwnd)
10109 		bbr->bbr_init_win_cheat = 1;
10110 	else
10111 		bbr->bbr_init_win_cheat = 0;
10112 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10113 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10114 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10115 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10116 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10117 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10118 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10119 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10120 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10121 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10122 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10123 	bbr->r_ctl.rc_rtt_shrinks = cts;
10124 	if (bbr->rc_use_google) {
10125 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10126 				  FILTER_TYPE_MAX,
10127 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10128 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10129 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10130 	} else {
10131 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10132 				  FILTER_TYPE_MAX,
10133 				  bbr_num_pktepo_for_del_limit);
10134 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10135 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10136 	}
10137 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10138 	if (bbr_uses_idle_restart)
10139 		bbr->rc_use_idle_restart = 1;
10140 	else
10141 		bbr->rc_use_idle_restart = 0;
10142 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10143 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10144 	if (bbr_resends_use_tso)
10145 		bbr->rc_resends_use_tso = 1;
10146 #ifdef NETFLIX_PEAKRATE
10147 	tp->t_peakrate_thr = tp->t_maxpeakrate;
10148 #endif
10149 	if (tp->snd_una != tp->snd_max) {
10150 		/* Create a send map for the current outstanding data */
10151 		struct bbr_sendmap *rsm;
10152 
10153 		rsm = bbr_alloc(bbr);
10154 		if (rsm == NULL) {
10155 			uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10156 			tp->t_fb_ptr = NULL;
10157 			return (ENOMEM);
10158 		}
10159 		rsm->r_rtt_not_allowed = 1;
10160 		rsm->r_tim_lastsent[0] = cts;
10161 		rsm->r_rtr_cnt = 1;
10162 		rsm->r_rtr_bytes = 0;
10163 		rsm->r_start = tp->snd_una;
10164 		rsm->r_end = tp->snd_max;
10165 		rsm->r_dupack = 0;
10166 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10167 		rsm->r_ts_valid = 0;
10168 		rsm->r_del_ack_ts = tp->ts_recent;
10169 		rsm->r_del_time = cts;
10170 		if (bbr->r_ctl.r_app_limited_until)
10171 			rsm->r_app_limited = 1;
10172 		else
10173 			rsm->r_app_limited = 0;
10174 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10175 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10176 		rsm->r_in_tmap = 1;
10177 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10178 			rsm->r_bbr_state = bbr_state_val(bbr);
10179 		else
10180 			rsm->r_bbr_state = 8;
10181 	}
10182 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10183 		bbr->bbr_use_rack_cheat = 1;
10184 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10185 		bbr->r_ctl.rc_incr_tmrs = 1;
10186 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10187 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10188 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10189 		bbr->r_ctl.rc_inc_ip_oh = 1;
10190 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10191 		bbr->r_ctl.rc_inc_enet_oh = 1;
10192 
10193 	bbr_log_type_statechange(bbr, cts, __LINE__);
10194 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10195 	    (tp->t_srtt)) {
10196 		uint32_t rtt;
10197 
10198 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10199 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10200 	}
10201 	/* announce the settings and state */
10202 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10203 	tcp_bbr_tso_size_check(bbr, cts);
10204 	/*
10205 	 * Now call the generic function to start a timer. This will place
10206 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10207 	 * flags.
10208 	 */
10209 	bbr_stop_all_timers(tp);
10210 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10211 	return (0);
10212 }
10213 
10214 /*
10215  * Return 0 if we can accept the connection. Return
10216  * non-zero if we can't handle the connection. A EAGAIN
10217  * means you need to wait until the connection is up.
10218  * a EADDRNOTAVAIL means we can never handle the connection
10219  * (no SACK).
10220  */
10221 static int
10222 bbr_handoff_ok(struct tcpcb *tp)
10223 {
10224 	if ((tp->t_state == TCPS_CLOSED) ||
10225 	    (tp->t_state == TCPS_LISTEN)) {
10226 		/* Sure no problem though it may not stick */
10227 		return (0);
10228 	}
10229 	if ((tp->t_state == TCPS_SYN_SENT) ||
10230 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10231 		/*
10232 		 * We really don't know you have to get to ESTAB or beyond
10233 		 * to tell.
10234 		 */
10235 		return (EAGAIN);
10236 	}
10237 	if (tp->t_flags & TF_SENTFIN)
10238 		return (EINVAL);
10239 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10240 		return (0);
10241 	}
10242 	/*
10243 	 * If we reach here we don't do SACK on this connection so we can
10244 	 * never do rack.
10245 	 */
10246 	return (EINVAL);
10247 }
10248 
10249 static void
10250 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10251 {
10252 	if (tp->t_fb_ptr) {
10253 		uint32_t calc;
10254 		struct tcp_bbr *bbr;
10255 		struct bbr_sendmap *rsm;
10256 
10257 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10258 		if (bbr->r_ctl.crte)
10259 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10260 		bbr_log_flowend(bbr);
10261 		bbr->rc_tp = NULL;
10262 		if (tp->t_inpcb) {
10263 			/* Backout any flags2 we applied */
10264 			tp->t_inpcb->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10265 			tp->t_inpcb->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10266 			tp->t_inpcb->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10267 		}
10268 		if (bbr->bbr_hdrw_pacing)
10269 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10270 		else
10271 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10272 		if (bbr->r_ctl.crte != NULL) {
10273 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10274 			bbr->r_ctl.crte = NULL;
10275 		}
10276 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10277 		while (rsm) {
10278 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10279 			uma_zfree(bbr_zone, rsm);
10280 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10281 		}
10282 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10283 		while (rsm) {
10284 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10285 			uma_zfree(bbr_zone, rsm);
10286 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10287 		}
10288 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10289 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10290 			BBR_STAT_INC(bbr_dynamic_rwnd);
10291 		else
10292 			BBR_STAT_INC(bbr_static_rwnd);
10293 		bbr->r_ctl.rc_free_cnt = 0;
10294 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10295 		tp->t_fb_ptr = NULL;
10296 	}
10297 	/* Make sure snd_nxt is correctly set */
10298 	tp->snd_nxt = tp->snd_max;
10299 }
10300 
10301 static void
10302 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10303 {
10304 	switch (tp->t_state) {
10305 	case TCPS_SYN_SENT:
10306 		bbr->r_state = TCPS_SYN_SENT;
10307 		bbr->r_substate = bbr_do_syn_sent;
10308 		break;
10309 	case TCPS_SYN_RECEIVED:
10310 		bbr->r_state = TCPS_SYN_RECEIVED;
10311 		bbr->r_substate = bbr_do_syn_recv;
10312 		break;
10313 	case TCPS_ESTABLISHED:
10314 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10315 		bbr->r_state = TCPS_ESTABLISHED;
10316 		bbr->r_substate = bbr_do_established;
10317 		break;
10318 	case TCPS_CLOSE_WAIT:
10319 		bbr->r_state = TCPS_CLOSE_WAIT;
10320 		bbr->r_substate = bbr_do_close_wait;
10321 		break;
10322 	case TCPS_FIN_WAIT_1:
10323 		bbr->r_state = TCPS_FIN_WAIT_1;
10324 		bbr->r_substate = bbr_do_fin_wait_1;
10325 		break;
10326 	case TCPS_CLOSING:
10327 		bbr->r_state = TCPS_CLOSING;
10328 		bbr->r_substate = bbr_do_closing;
10329 		break;
10330 	case TCPS_LAST_ACK:
10331 		bbr->r_state = TCPS_LAST_ACK;
10332 		bbr->r_substate = bbr_do_lastack;
10333 		break;
10334 	case TCPS_FIN_WAIT_2:
10335 		bbr->r_state = TCPS_FIN_WAIT_2;
10336 		bbr->r_substate = bbr_do_fin_wait_2;
10337 		break;
10338 	case TCPS_LISTEN:
10339 	case TCPS_CLOSED:
10340 	case TCPS_TIME_WAIT:
10341 	default:
10342 		break;
10343 	};
10344 }
10345 
10346 static void
10347 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10348 {
10349 	/*
10350 	 * Now what state are we going into now? Is there adjustments
10351 	 * needed?
10352 	 */
10353 	int32_t old_state;
10354 
10355 	old_state = bbr_state_val(bbr);
10356 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10357 		/* Save the lowest srtt we saw in our end of the sub-state */
10358 		bbr->rc_hit_state_1 = 0;
10359 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10360 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10361 	}
10362 	bbr->rc_bbr_substate++;
10363 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10364 		/* Cycle back to first state-> gain */
10365 		bbr->rc_bbr_substate = 0;
10366 	}
10367 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10368 		/*
10369 		 * We enter the gain(5/4) cycle (possibly less if
10370 		 * shallow buffer detection is enabled)
10371 		 */
10372 		if (bbr->skip_gain) {
10373 			/*
10374 			 * Hardware pacing has set our rate to
10375 			 * the max and limited our b/w just
10376 			 * do level i.e. no gain.
10377 			 */
10378 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10379 		} else if (bbr->gain_is_limited &&
10380 			   bbr->bbr_hdrw_pacing &&
10381 			   bbr->r_ctl.crte) {
10382 			/*
10383 			 * We can't gain above the hardware pacing
10384 			 * rate which is less than our rate + the gain
10385 			 * calculate the gain needed to reach the hardware
10386 			 * pacing rate..
10387 			 */
10388 			uint64_t bw, rate, gain_calc;
10389 
10390 			bw = bbr_get_bw(bbr);
10391 			rate = bbr->r_ctl.crte->rate;
10392 			if ((rate > bw) &&
10393 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10394 				gain_calc = (rate * BBR_UNIT) / bw;
10395 				if (gain_calc < BBR_UNIT)
10396 					gain_calc = BBR_UNIT;
10397 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10398 			} else {
10399 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10400 			}
10401 		} else
10402 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10403 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10404 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10405 		} else
10406 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10407 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10408 		bbr->rc_hit_state_1 = 1;
10409 		bbr->r_ctl.rc_exta_time_gd = 0;
10410 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10411 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10412 		if (bbr_state_drain_2_tar) {
10413 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10414 		} else
10415 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10416 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10417 	} else {
10418 		/* All other cycles hit here 2-7 */
10419 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10420 			if (bbr_sub_drain_slam_cwnd &&
10421 			    (bbr->rc_use_google == 0) &&
10422 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10423 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10424 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10425 			}
10426 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10427 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10428 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10429 			else
10430 				bbr->r_ctl.rc_exta_time_gd = 0;
10431 			if (bbr->r_ctl.rc_exta_time_gd) {
10432 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10433 				/* Now chop up the time for each state (div by 7) */
10434 				bbr->r_ctl.rc_level_state_extra /= 7;
10435 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10436 					/* Add a randomization */
10437 					bbr_randomize_extra_state_time(bbr);
10438 				}
10439 			}
10440 		}
10441 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10442 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10443 	}
10444 	if (bbr->rc_use_google) {
10445 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10446 	}
10447 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10448 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10449 	if (dolog)
10450 		bbr_log_type_statechange(bbr, cts, line);
10451 
10452 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10453 		uint32_t time_in;
10454 
10455 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10456 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10457 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10458 		} else {
10459 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10460 		}
10461 	}
10462 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10463 	bbr_set_state_target(bbr, __LINE__);
10464 	if (bbr_sub_drain_slam_cwnd &&
10465 	    (bbr->rc_use_google == 0) &&
10466 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10467 		/* Slam down the cwnd */
10468 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10469 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10470 		if (bbr_sub_drain_app_limit) {
10471 			/* Go app limited if we are on a long drain */
10472 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10473 							  ctf_flight_size(bbr->rc_tp,
10474 							      (bbr->r_ctl.rc_sacked +
10475 							       bbr->r_ctl.rc_lost_bytes)));
10476 		}
10477 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10478 	}
10479 	if (bbr->rc_lt_use_bw) {
10480 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10481 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10482 	}
10483 	/* Google changes TSO size every cycle */
10484 	if (bbr->rc_use_google)
10485 		tcp_bbr_tso_size_check(bbr, cts);
10486 	bbr->r_ctl.gain_epoch = cts;
10487 	bbr->r_ctl.rc_bbr_state_time = cts;
10488 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10489 }
10490 
10491 static void
10492 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10493 {
10494 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10495 	    (google_allow_early_out == 1) &&
10496 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10497 		/* We have reached out target flight size possibly early */
10498 		goto change_state;
10499 	}
10500 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10501 		return;
10502 	}
10503 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10504 		/*
10505 		 * Must be a rttProp movement forward before
10506 		 * we can change states.
10507 		 */
10508 		return;
10509 	}
10510 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10511 		/*
10512 		 * The needed time has passed but for
10513 		 * the gain cycle extra rules apply:
10514 		 * 1) If we have seen loss, we exit
10515 		 * 2) If we have not reached the target
10516 		 *    we stay in GAIN (gain-to-target).
10517 		 */
10518 		if (google_consider_lost && losses)
10519 			goto change_state;
10520 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10521 			return;
10522 		}
10523 	}
10524 change_state:
10525 	/* For gain we must reach our target, all others last 1 rttProp */
10526 	bbr_substate_change(bbr, cts, __LINE__, 1);
10527 }
10528 
10529 static void
10530 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10531 {
10532 	uint32_t flight, bbr_cur_cycle_time;
10533 
10534 	if (bbr->rc_use_google) {
10535 		bbr_set_probebw_google_gains(bbr, cts, losses);
10536 		return;
10537 	}
10538 	if (cts == 0) {
10539 		/*
10540 		 * Never alow cts to be 0 we
10541 		 * do this so we can judge if
10542 		 * we have set a timestamp.
10543 		 */
10544 		cts = 1;
10545 	}
10546 	if (bbr_state_is_pkt_epoch)
10547 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10548 	else
10549 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10550 
10551 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10552 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10553 			flight = ctf_flight_size(bbr->rc_tp,
10554 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10555 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10556 				/* Keep it slam down */
10557 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10558 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10559 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10560 				}
10561 				if (bbr_sub_drain_app_limit) {
10562 					/* Go app limited if we are on a long drain */
10563 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10564 				}
10565 			}
10566 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10567 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10568 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10569 				/*
10570 				 * Still here after the same time as
10571 				 * the gain. We need to drain harder
10572 				 * for the next srtt. Reduce by a set amount
10573 				 * the gain drop is capped at DRAIN states
10574 				 * value (88).
10575 				 */
10576 				bbr->r_ctl.flightsize_at_drain = flight;
10577 				if (bbr_drain_drop_mul &&
10578 				    bbr_drain_drop_div &&
10579 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10580 					/* Use your specific drop value (def 4/5 = 20%) */
10581 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10582 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10583 				} else {
10584 					/* You get drop of 20% */
10585 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10586 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10587 				}
10588 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10589 					/* Reduce our gain again to the bottom  */
10590 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10591 				}
10592 				bbr_log_exit_gain(bbr, cts, 4);
10593 				/*
10594 				 * Extend out so we wait another
10595 				 * epoch before dropping again.
10596 				 */
10597 				bbr->r_ctl.gain_epoch = cts;
10598 			}
10599 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10600 				if (bbr_sub_drain_slam_cwnd &&
10601 				    (bbr->rc_use_google == 0) &&
10602 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10603 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10604 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10605 				}
10606 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10607 				bbr_log_exit_gain(bbr, cts, 3);
10608 			}
10609 		} else {
10610 			/* Its a gain  */
10611 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10612 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10613 				goto change_state;
10614 			}
10615 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10616 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10617 			     bbr->rc_tp->snd_wnd)) {
10618 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10619 				bbr_log_exit_gain(bbr, cts, 2);
10620 			}
10621 		}
10622 		/**
10623 		 * We fall through and return always one of two things has
10624 		 * occurred.
10625 		 * 1) We are still not at target
10626 		 *    <or>
10627 		 * 2) We reached the target and set rc_bbr_state_atflight
10628 		 *    which means we no longer hit this block
10629 		 *    next time we are called.
10630 		 */
10631 		return;
10632 	}
10633 change_state:
10634 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10635 		return;
10636 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10637 		/* Less than a full time-period has passed */
10638 		return;
10639 	}
10640 	if (bbr->r_ctl.rc_level_state_extra &&
10641 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10642 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10643 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10644 		/* Less than a full time-period + extra has passed */
10645 		return;
10646 	}
10647 	if (bbr_gain_gets_extra_too &&
10648 	    bbr->r_ctl.rc_level_state_extra &&
10649 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10650 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10651 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10652 		/* Less than a full time-period + extra has passed */
10653 		return;
10654 	}
10655 	bbr_substate_change(bbr, cts, __LINE__, 1);
10656 }
10657 
10658 static uint32_t
10659 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10660 {
10661 	uint32_t mss, tar;
10662 
10663 	if (bbr->rc_use_google) {
10664 		/* Google just uses the cwnd target */
10665 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10666 	} else {
10667 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10668 			  bbr->r_ctl.rc_pace_max_segs);
10669 		/* Get the base cwnd with gain rounded to a mss */
10670 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10671 						      gain), mss);
10672 		/* Make sure it is within our min */
10673 		if (tar < get_min_cwnd(bbr))
10674 			return (get_min_cwnd(bbr));
10675 	}
10676 	return (tar);
10677 }
10678 
10679 static void
10680 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10681 {
10682 	uint32_t tar, meth;
10683 
10684 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10685 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10686 		/* Special case using old probe-rtt method */
10687 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10688 		meth = 1;
10689 	} else {
10690 		/* Non-probe-rtt case and reduced probe-rtt  */
10691 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10692 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10693 			/* For gain cycle we use the hptsi gain */
10694 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10695 			meth = 2;
10696 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10697 			/*
10698 			 * If configured, or for google all other states
10699 			 * get BBR_UNIT.
10700 			 */
10701 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10702 			meth = 3;
10703 		} else {
10704 			/*
10705 			 * Or we set a target based on the pacing gain
10706 			 * for non-google mode and default (non-configured).
10707 			 * Note we don't set a target goal below drain (192).
10708 			 */
10709 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10710 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10711 				meth = 4;
10712 			} else {
10713 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10714 				meth = 5;
10715 			}
10716 		}
10717 	}
10718 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10719 	bbr->r_ctl.rc_target_at_state = tar;
10720 }
10721 
10722 static void
10723 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10724 {
10725 	/* Change to probe_rtt */
10726 	uint32_t time_in;
10727 
10728 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10729 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10730 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10731 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10732 					  + bbr->r_ctl.rc_delivered);
10733 	/* Setup so we force feed the filter */
10734 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10735 		bbr->rc_prtt_set_ts = 1;
10736 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10737 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10738 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10739 	}
10740 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10741 	bbr->r_ctl.rc_rtt_shrinks = cts;
10742 	bbr->r_ctl.last_in_probertt = cts;
10743 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10744 	bbr->r_ctl.rc_bbr_state_time = cts;
10745 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10746 	/* We need to force the filter to update */
10747 
10748 	if ((bbr_sub_drain_slam_cwnd) &&
10749 	    bbr->rc_hit_state_1 &&
10750 	    (bbr->rc_use_google == 0) &&
10751 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10752 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10753 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10754 	} else
10755 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10756 	/* Update the lost */
10757 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10758 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10759 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10760 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10761 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10762 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10763 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10764 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10765 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10766 	} else {
10767 		/*
10768 		 * We bring it down slowly by using a hptsi gain that is
10769 		 * probably 75%. This will slowly float down our outstanding
10770 		 * without tampering with the cwnd.
10771 		 */
10772 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10773 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10774 		bbr_set_state_target(bbr, __LINE__);
10775 		if (bbr_prtt_slam_cwnd &&
10776 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10777 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10778 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10779 		}
10780 	}
10781 	if (ctf_flight_size(bbr->rc_tp,
10782 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10783 	    bbr->r_ctl.rc_target_at_state) {
10784 		/* We are at target */
10785 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10786 	} else {
10787 		/* We need to come down to reach target before our time begins */
10788 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10789 	}
10790 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10791 	BBR_STAT_INC(bbr_enter_probertt);
10792 	bbr_log_exit_gain(bbr, cts, 0);
10793 	bbr_log_type_statechange(bbr, cts, line);
10794 }
10795 
10796 static void
10797 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10798 {
10799 	/*
10800 	 * Sanity check on probe-rtt intervals.
10801 	 * In crazy situations where we are competing
10802 	 * against new-reno flows with huge buffers
10803 	 * our rtt-prop interval could come to dominate
10804 	 * things if we can't get through a full set
10805 	 * of cycles, we need to adjust it.
10806 	 */
10807 	if (bbr_can_adjust_probertt &&
10808 	    (bbr->rc_use_google == 0)) {
10809 		uint16_t val = 0;
10810 		uint32_t cur_rttp, fval, newval, baseval;
10811 
10812 		/* Are we to small and go into probe-rtt to often? */
10813 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10814 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10815 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10816 		if (bbr_is_ratio == 0) {
10817 			if (fval > bbr_rtt_probe_limit)
10818 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10819 			else
10820 				newval = cur_rttp;
10821 		} else {
10822 			int mul;
10823 
10824 			mul = fval / bbr_rtt_probe_limit;
10825 			newval = cur_rttp * mul;
10826 		}
10827 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10828 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10829 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10830 			val = 1;
10831 		} else {
10832 			/*
10833 			 * No adjustments were made
10834 			 * do we need to shrink it?
10835 			 */
10836 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10837 				if (cur_rttp <= bbr_rtt_probe_limit) {
10838 					/*
10839 					 * Things have calmed down lets
10840 					 * shrink all the way to default
10841 					 */
10842 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10843 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10844 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10845 					cur_rttp = bbr_rtt_probe_limit;
10846 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10847 					val = 2;
10848 				} else {
10849 					/*
10850 					 * Well does some adjustment make sense?
10851 					 */
10852 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10853 						/* We can reduce interval time some */
10854 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10855 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10856 						val = 3;
10857 					}
10858 				}
10859 			}
10860 		}
10861 		if (val)
10862 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10863 	}
10864 }
10865 
10866 static void
10867 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10868 {
10869 	/* Exit probe-rtt */
10870 
10871 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10872 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10873 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10874 	}
10875 	bbr_log_exit_gain(bbr, cts, 1);
10876 	bbr->rc_hit_state_1 = 0;
10877 	bbr->r_ctl.rc_rtt_shrinks = cts;
10878 	bbr->r_ctl.last_in_probertt = cts;
10879 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10880 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10881 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10882 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10883 					  bbr->r_ctl.rc_delivered);
10884 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10885 		uint32_t time_in;
10886 
10887 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10888 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10889 	}
10890 	if (bbr->rc_filled_pipe) {
10891 		/* Switch to probe_bw */
10892 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10893 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10894 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10895 		bbr_substate_change(bbr, cts, __LINE__, 0);
10896 		bbr_log_type_statechange(bbr, cts, __LINE__);
10897 	} else {
10898 		/* Back to startup */
10899 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10900 		bbr->r_ctl.rc_bbr_state_time = cts;
10901 		/*
10902 		 * We don't want to give a complete free 3
10903 		 * measurements until we exit, so we use
10904 		 * the number of pe's we were in probe-rtt
10905 		 * to add to the startup_epoch. That way
10906 		 * we will still retain the old state.
10907 		 */
10908 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10909 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10910 		/* Make sure to use the lower pg when shifting back in */
10911 		if (bbr->r_ctl.rc_lost &&
10912 		    bbr_use_lower_gain_in_startup &&
10913 		    (bbr->rc_use_google == 0))
10914 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10915 		else
10916 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10917 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10918 		/* Probably not needed but set it anyway */
10919 		bbr_set_state_target(bbr, __LINE__);
10920 		bbr_log_type_statechange(bbr, cts, __LINE__);
10921 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10922 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10923 	}
10924 	bbr_check_probe_rtt_limits(bbr, cts);
10925 }
10926 
10927 static int32_t inline
10928 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10929 {
10930 	if ((bbr->rc_past_init_win == 1) &&
10931 	    (bbr->rc_in_persist == 0) &&
10932 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10933 		return (1);
10934 	}
10935 	if (bbr_can_force_probertt &&
10936 	    (bbr->rc_in_persist == 0) &&
10937 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10938 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10939 		return (1);
10940 	}
10941 	return (0);
10942 }
10943 
10944 static int32_t
10945 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10946 {
10947 	uint64_t btlbw, gain;
10948 	if (pkt_epoch == 0) {
10949 		/*
10950 		 * Need to be on a pkt-epoch to continue.
10951 		 */
10952 		return (0);
10953 	}
10954 	btlbw = bbr_get_full_bw(bbr);
10955 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10956 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10957 	if (btlbw >= gain) {
10958 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10959 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10960 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10961 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10962 	}
10963 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10964 		return (1);
10965 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10966 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10967 	return(0);
10968 }
10969 
10970 static int32_t inline
10971 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10972 {
10973 	/* Have we gained 25% in the last 3 packet based epoch's? */
10974 	uint64_t btlbw, gain;
10975 	int do_exit;
10976 	int delta, rtt_gain;
10977 
10978 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10979 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10980 		/*
10981 		 * This qualifies as a RTT_PROBE session since we drop the
10982 		 * data outstanding to nothing and waited more than
10983 		 * bbr_rtt_probe_time.
10984 		 */
10985 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10986 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10987 	}
10988 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10989 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10990 		return (0);
10991 	}
10992 	if (bbr->rc_use_google)
10993 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10994 
10995 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10996 	    (bbr_use_lower_gain_in_startup)) {
10997 		/* Drop to a lower gain 1.5 x since we saw loss */
10998 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10999 	}
11000 	if (pkt_epoch == 0) {
11001 		/*
11002 		 * Need to be on a pkt-epoch to continue.
11003 		 */
11004 		return (0);
11005 	}
11006 	if (bbr_rtt_gain_thresh) {
11007 		/*
11008 		 * Do we allow a flow to stay
11009 		 * in startup with no loss and no
11010 		 * gain in rtt over a set threshold?
11011 		 */
11012 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
11013 		    bbr->r_ctl.startup_last_srtt &&
11014 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
11015 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
11016 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
11017 		} else
11018 			rtt_gain = 0;
11019 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
11020 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
11021 			/* First time or new lower value */
11022 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
11023 
11024 		if ((bbr->r_ctl.rc_lost == 0) &&
11025 		    (rtt_gain < bbr_rtt_gain_thresh)) {
11026 			/*
11027 			 * No loss, and we are under
11028 			 * our gain threhold for
11029 			 * increasing RTT.
11030 			 */
11031 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11032 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
11033 			bbr_log_startup_event(bbr, cts, rtt_gain,
11034 					      delta, bbr->r_ctl.startup_last_srtt, 10);
11035 			return (0);
11036 		}
11037 	}
11038 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
11039 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
11040 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
11041 		/*
11042 		 * We only assess if we have a new measurement when
11043 		 * we have no loss and are not in recovery.
11044 		 * Drag up by one our last_startup epoch so we will hold
11045 		 * the number of non-gain we have already accumulated.
11046 		 */
11047 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11048 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
11049 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11050 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11051 		return (0);
11052 	}
11053 	/* Case where we reduced the lost (bad retransmit) */
11054 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11055 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11056 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11057 	btlbw = bbr_get_full_bw(bbr);
11058 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11059 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11060 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11061 	else
11062 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11063 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11064 	do_exit = 0;
11065 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11066 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11067 	if (btlbw >= gain) {
11068 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11069 		/* Update the lost so we won't exit in next set of tests */
11070 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11071 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11072 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11073 	}
11074 	if ((bbr->rc_loss_exit &&
11075 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11076 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11077 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11078 		/*
11079 		 * If we had no gain,  we had loss and that loss was above
11080 		 * our threshould, the rwnd is not constrained, and we have
11081 		 * had at least 3 packet epochs exit. Note that this is
11082 		 * switched off by sysctl. Google does not do this by the
11083 		 * way.
11084 		 */
11085 		if ((ctf_flight_size(bbr->rc_tp,
11086 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11087 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11088 			do_exit = 1;
11089 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11090 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11091 		} else {
11092 			/* Just record an updated loss value */
11093 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11094 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11095 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11096 		}
11097 	} else
11098 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11099 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11100 	    do_exit) {
11101 		/* Return 1 to exit the startup state. */
11102 		return (1);
11103 	}
11104 	/* Stay in startup */
11105 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11106 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11107 	return (0);
11108 }
11109 
11110 static void
11111 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11112 {
11113 	/*
11114 	 * A tick occurred in the rtt epoch do we need to do anything?
11115 	 */
11116 #ifdef BBR_INVARIANTS
11117 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11118 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11119 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11120 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11121 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11122 		/* Debug code? */
11123 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11124 	}
11125 #endif
11126 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11127 		/* Do we exit the startup state? */
11128 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11129 			uint32_t time_in;
11130 
11131 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11132 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11133 			bbr->rc_filled_pipe = 1;
11134 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11135 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11136 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11137 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11138 			} else
11139 				time_in = 0;
11140 			if (bbr->rc_no_pacing)
11141 				bbr->rc_no_pacing = 0;
11142 			bbr->r_ctl.rc_bbr_state_time = cts;
11143 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11144 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11145 			bbr_set_state_target(bbr, __LINE__);
11146 			if ((bbr->rc_use_google == 0) &&
11147 			    bbr_slam_cwnd_in_main_drain) {
11148 				/* Here we don't have to worry about probe-rtt */
11149 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11150 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11151 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11152 			}
11153 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11154 			bbr_log_type_statechange(bbr, cts, __LINE__);
11155 			if (ctf_flight_size(bbr->rc_tp,
11156 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11157 			    bbr->r_ctl.rc_target_at_state) {
11158 				/*
11159 				 * Switch to probe_bw if we are already
11160 				 * there
11161 				 */
11162 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11163 				bbr_substate_change(bbr, cts, __LINE__, 0);
11164 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11165 				bbr_log_type_statechange(bbr, cts, __LINE__);
11166 			}
11167 		}
11168 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11169 		uint32_t inflight;
11170 		struct tcpcb *tp;
11171 
11172 		tp = bbr->rc_tp;
11173 		inflight = ctf_flight_size(tp,
11174 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11175 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11176 			/* We have reached a flight of the cwnd target */
11177 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11178 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11179 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11180 			bbr_set_state_target(bbr, __LINE__);
11181 			/*
11182 			 * Rig it so we don't do anything crazy and
11183 			 * start fresh with a new randomization.
11184 			 */
11185 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11186 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11187 			bbr_substate_change(bbr, cts, __LINE__, 1);
11188 		}
11189 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11190 		/* Has in-flight reached the bdp (or less)? */
11191 		uint32_t inflight;
11192 		struct tcpcb *tp;
11193 
11194 		tp = bbr->rc_tp;
11195 		inflight = ctf_flight_size(tp,
11196 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11197 		if ((bbr->rc_use_google == 0) &&
11198 		    bbr_slam_cwnd_in_main_drain &&
11199 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11200 			/*
11201 			 * Here we don't have to worry about probe-rtt
11202 			 * re-slam it, but keep it slammed down.
11203 			 */
11204 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11205 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11206 		}
11207 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11208 			/* We have drained */
11209 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11210 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11211 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11212 				uint32_t time_in;
11213 
11214 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11215 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11216 			}
11217 			if ((bbr->rc_use_google == 0) &&
11218 			    bbr_slam_cwnd_in_main_drain &&
11219 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11220 				/* Restore the cwnd */
11221 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11222 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11223 			}
11224 			/* Setup probe-rtt has being done now RRS-HERE */
11225 			bbr->r_ctl.rc_rtt_shrinks = cts;
11226 			bbr->r_ctl.last_in_probertt = cts;
11227 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11228 			/* Randomly pick a sub-state */
11229 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11230 			bbr_substate_change(bbr, cts, __LINE__, 0);
11231 			bbr_log_type_statechange(bbr, cts, __LINE__);
11232 		}
11233 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11234 		uint32_t flight;
11235 
11236 		flight = ctf_flight_size(bbr->rc_tp,
11237 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11238 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11239 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11240 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11241 			/*
11242 			 * We must keep cwnd at the desired MSS.
11243 			 */
11244 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11245 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11246 		} else if ((bbr_prtt_slam_cwnd) &&
11247 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11248 			/* Re-slam it */
11249 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11250 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11251 		}
11252 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11253 			/* Has outstanding reached our target? */
11254 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11255 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11256 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11257 				/* If time is exactly 0, be 1usec off */
11258 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11259 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11260 				if (bbr->rc_use_google == 0) {
11261 					/*
11262 					 * Restore any lowering that as occurred to
11263 					 * reach here
11264 					 */
11265 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11266 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11267 					else
11268 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11269 				}
11270 			}
11271 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11272 			    (bbr->rc_use_google == 0) &&
11273 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11274 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11275 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11276 				/*
11277 				 * We have doddled with our current hptsi
11278 				 * gain an srtt and have still not made it
11279 				 * to target, or we have increased our flight.
11280 				 * Lets reduce the gain by xx%
11281 				 * flooring the reduce at DRAIN (based on
11282 				 * mul/div)
11283 				 */
11284 				int red;
11285 
11286 				bbr->r_ctl.flightsize_at_drain = flight;
11287 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11288 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11289 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11290 					/* Reduce our gain again */
11291 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11292 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11293 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11294 					/* one more chance before we give up */
11295 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11296 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11297 				} else {
11298 					/* At the very bottom */
11299 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11300 				}
11301 			}
11302 		}
11303 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11304 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11305 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11306 			/* Time to exit probe RTT normally */
11307 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11308 		}
11309 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11310 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11311 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11312 			/*
11313 			 * This qualifies as a RTT_PROBE session since we
11314 			 * drop the data outstanding to nothing and waited
11315 			 * more than bbr_rtt_probe_time.
11316 			 */
11317 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11318 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11319 		}
11320 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11321 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11322 		} else {
11323 			bbr_set_probebw_gains(bbr, cts, losses);
11324 		}
11325 	}
11326 }
11327 
11328 static void
11329 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11330 {
11331 	int32_t epoch = 0;
11332 
11333 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11334 		bbr_set_epoch(bbr, cts, line);
11335 		/* At each epoch doe lt bw sampling */
11336 		epoch = 1;
11337 	}
11338 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11339 }
11340 
11341 static int
11342 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11343     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11344     int32_t nxt_pkt, struct timeval *tv)
11345 {
11346 	int32_t thflags, retval;
11347 	uint32_t cts, lcts;
11348 	uint32_t tiwin;
11349 	struct tcpopt to;
11350 	struct tcp_bbr *bbr;
11351 	struct bbr_sendmap *rsm;
11352 	struct timeval ltv;
11353 	int32_t did_out = 0;
11354 	uint16_t nsegs;
11355 	int32_t prev_state;
11356 	uint32_t lost;
11357 
11358 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11359 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11360 	/* add in our stats */
11361 	kern_prefetch(bbr, &prev_state);
11362 	prev_state = 0;
11363 	thflags = tcp_get_flags(th);
11364 	/*
11365 	 * If this is either a state-changing packet or current state isn't
11366 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11367 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11368 	 * caller may have unnecessarily acquired a write lock due to a
11369 	 * race.
11370 	 */
11371 	INP_WLOCK_ASSERT(tp->t_inpcb);
11372 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11373 	    __func__));
11374 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11375 	    __func__));
11376 
11377 	tp->t_rcvtime = ticks;
11378 	/*
11379 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11380 	 * the scale is zero.
11381 	 */
11382 	tiwin = th->th_win << tp->snd_scale;
11383 #ifdef STATS
11384 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11385 #endif
11386 
11387 	if (m->m_flags & M_TSTMP) {
11388 		/* Prefer the hardware timestamp if present */
11389 		struct timespec ts;
11390 
11391 		mbuf_tstmp2timespec(m, &ts);
11392 		bbr->rc_tv.tv_sec = ts.tv_sec;
11393 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11394 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11395 	} else if (m->m_flags & M_TSTMP_LRO) {
11396 		/* Next the arrival timestamp */
11397 		struct timespec ts;
11398 
11399 		mbuf_tstmp2timespec(m, &ts);
11400 		bbr->rc_tv.tv_sec = ts.tv_sec;
11401 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11402 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11403 	} else {
11404 		/*
11405 		 * Ok just get the current time.
11406 		 */
11407 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11408 	}
11409 	/*
11410 	 * Parse options on any incoming segment.
11411 	 */
11412 	tcp_dooptions(&to, (u_char *)(th + 1),
11413 	    (th->th_off << 2) - sizeof(struct tcphdr),
11414 	    (thflags & TH_SYN) ? TO_SYN : 0);
11415 
11416 	/*
11417 	 * If timestamps were negotiated during SYN/ACK and a
11418 	 * segment without a timestamp is received, silently drop
11419 	 * the segment, unless it is a RST segment or missing timestamps are
11420 	 * tolerated.
11421 	 * See section 3.2 of RFC 7323.
11422 	 */
11423 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11424 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11425 		retval = 0;
11426 		m_freem(m);
11427 		goto done_with_input;
11428 	}
11429 	/*
11430 	 * If echoed timestamp is later than the current time, fall back to
11431 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11432 	 * were used when this connection was established.
11433 	 */
11434 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11435 		to.to_tsecr -= tp->ts_offset;
11436 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11437 			to.to_tsecr = 0;
11438 	}
11439 	/*
11440 	 * If its the first time in we need to take care of options and
11441 	 * verify we can do SACK for rack!
11442 	 */
11443 	if (bbr->r_state == 0) {
11444 		/*
11445 		 * Process options only when we get SYN/ACK back. The SYN
11446 		 * case for incoming connections is handled in tcp_syncache.
11447 		 * According to RFC1323 the window field in a SYN (i.e., a
11448 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11449 		 * this is traditional behavior, may need to be cleaned up.
11450 		 */
11451 		if (bbr->rc_inp == NULL) {
11452 			bbr->rc_inp = tp->t_inpcb;
11453 		}
11454 		/*
11455 		 * We need to init rc_inp here since its not init'd when
11456 		 * bbr_init is called
11457 		 */
11458 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11459 			if ((to.to_flags & TOF_SCALE) &&
11460 			    (tp->t_flags & TF_REQ_SCALE)) {
11461 				tp->t_flags |= TF_RCVD_SCALE;
11462 				tp->snd_scale = to.to_wscale;
11463 			} else
11464 				tp->t_flags &= ~TF_REQ_SCALE;
11465 			/*
11466 			 * Initial send window.  It will be updated with the
11467 			 * next incoming segment to the scaled value.
11468 			 */
11469 			tp->snd_wnd = th->th_win;
11470 			if ((to.to_flags & TOF_TS) &&
11471 			    (tp->t_flags & TF_REQ_TSTMP)) {
11472 				tp->t_flags |= TF_RCVD_TSTMP;
11473 				tp->ts_recent = to.to_tsval;
11474 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11475 			} else
11476 			    tp->t_flags &= ~TF_REQ_TSTMP;
11477 			if (to.to_flags & TOF_MSS)
11478 				tcp_mss(tp, to.to_mss);
11479 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11480 			    (to.to_flags & TOF_SACKPERM) == 0)
11481 				tp->t_flags &= ~TF_SACK_PERMIT;
11482 			if (IS_FASTOPEN(tp->t_flags)) {
11483 				if (to.to_flags & TOF_FASTOPEN) {
11484 					uint16_t mss;
11485 
11486 					if (to.to_flags & TOF_MSS)
11487 						mss = to.to_mss;
11488 					else
11489 						if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0)
11490 							mss = TCP6_MSS;
11491 						else
11492 							mss = TCP_MSS;
11493 					tcp_fastopen_update_cache(tp, mss,
11494 					    to.to_tfo_len, to.to_tfo_cookie);
11495 				} else
11496 					tcp_fastopen_disable_path(tp);
11497 			}
11498 		}
11499 		/*
11500 		 * At this point we are at the initial call. Here we decide
11501 		 * if we are doing RACK or not. We do this by seeing if
11502 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11503 		 * we switch to the default code.
11504 		 */
11505 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11506 			/* Bail */
11507 			tcp_switch_back_to_default(tp);
11508 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11509 			    tlen, iptos);
11510 			return (1);
11511 		}
11512 		/* Set the flag */
11513 		bbr->r_is_v6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
11514 		tcp_set_hpts(tp->t_inpcb);
11515 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11516 	}
11517 	if (thflags & TH_ACK) {
11518 		/* Track ack types */
11519 		if (to.to_flags & TOF_SACK)
11520 			BBR_STAT_INC(bbr_acks_with_sacks);
11521 		else
11522 			BBR_STAT_INC(bbr_plain_acks);
11523 	}
11524 	/*
11525 	 * This is the one exception case where we set the rack state
11526 	 * always. All other times (timers etc) we must have a rack-state
11527 	 * set (so we assure we have done the checks above for SACK).
11528 	 */
11529 	if (thflags & TH_FIN)
11530 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11531 	if (bbr->r_state != tp->t_state)
11532 		bbr_set_state(tp, bbr, tiwin);
11533 
11534 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11535 		kern_prefetch(rsm, &prev_state);
11536 	prev_state = bbr->r_state;
11537 	bbr->rc_ack_was_delayed = 0;
11538 	lost = bbr->r_ctl.rc_lost;
11539 	bbr->rc_is_pkt_epoch_now = 0;
11540 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11541 		/* Get the real time into lcts and figure the real delay */
11542 		lcts = tcp_get_usecs(&ltv);
11543 		if (TSTMP_GT(lcts, cts)) {
11544 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11545 			bbr->rc_ack_was_delayed = 1;
11546 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11547 				     bbr->r_ctl.highest_hdwr_delay))
11548 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11549 		} else {
11550 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11551 			bbr->rc_ack_was_delayed = 0;
11552 		}
11553 	} else {
11554 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11555 		bbr->rc_ack_was_delayed = 0;
11556 	}
11557 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11558 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11559 		retval = 0;
11560 		m_freem(m);
11561 		goto done_with_input;
11562 	}
11563 	/*
11564 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11565 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11566 	 */
11567 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11568 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11569 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11570 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11571 		return (1);
11572 	}
11573 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11574 		bbr->r_ctl.rc_high_rwnd = tiwin;
11575 #ifdef BBR_INVARIANTS
11576 	if ((tp->t_inpcb->inp_flags & INP_DROPPED) ||
11577 	    (tp->t_inpcb->inp_flags2 & INP_FREED)) {
11578 		panic("tp:%p bbr:%p given a dropped inp:%p",
11579 		    tp, bbr, tp->t_inpcb);
11580 	}
11581 #endif
11582 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11583 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11584 	bbr->rtt_valid = 0;
11585 	if (to.to_flags & TOF_TS) {
11586 		bbr->rc_ts_valid = 1;
11587 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11588 	} else {
11589 		bbr->rc_ts_valid = 0;
11590 		bbr->r_ctl.last_inbound_ts = 0;
11591 	}
11592 	retval = (*bbr->r_substate) (m, th, so,
11593 	    tp, &to, drop_hdrlen,
11594 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11595 #ifdef BBR_INVARIANTS
11596 	if ((retval == 0) &&
11597 	    (tp->t_inpcb == NULL)) {
11598 		panic("retval:%d tp:%p t_inpcb:NULL state:%d",
11599 		    retval, tp, prev_state);
11600 	}
11601 #endif
11602 	if (nxt_pkt == 0)
11603 		BBR_STAT_INC(bbr_rlock_left_ret0);
11604 	else
11605 		BBR_STAT_INC(bbr_rlock_left_ret1);
11606 	if (retval == 0) {
11607 		/*
11608 		 * If retval is 1 the tcb is unlocked and most likely the tp
11609 		 * is gone.
11610 		 */
11611 		INP_WLOCK_ASSERT(tp->t_inpcb);
11612 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11613 		if (bbr->rc_is_pkt_epoch_now)
11614 			bbr_set_pktepoch(bbr, cts, __LINE__);
11615 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11616 		if (nxt_pkt == 0) {
11617 			if (bbr->r_wanted_output != 0) {
11618 				bbr->rc_output_starts_timer = 0;
11619 				did_out = 1;
11620 				if (tcp_output(tp) < 0)
11621 					return (1);
11622 			} else
11623 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11624 		}
11625 		if ((nxt_pkt == 0) &&
11626 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11627 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11628 		     (tp->t_flags & TF_DELACK) ||
11629 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11630 		      (tp->t_state <= TCPS_CLOSING)))) {
11631 			/*
11632 			 * We could not send (probably in the hpts but
11633 			 * stopped the timer)?
11634 			 */
11635 			if ((tp->snd_max == tp->snd_una) &&
11636 			    ((tp->t_flags & TF_DELACK) == 0) &&
11637 			    (tcp_in_hpts(bbr->rc_inp)) &&
11638 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11639 				/*
11640 				 * keep alive not needed if we are hptsi
11641 				 * output yet
11642 				 */
11643 				;
11644 			} else {
11645 				if (tcp_in_hpts(bbr->rc_inp)) {
11646 					tcp_hpts_remove(bbr->rc_inp);
11647 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11648 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11649 						uint32_t del;
11650 
11651 						del = lcts - bbr->rc_pacer_started;
11652 						if (bbr->r_ctl.rc_last_delay_val > del) {
11653 							BBR_STAT_INC(bbr_force_timer_start);
11654 							bbr->r_ctl.rc_last_delay_val -= del;
11655 							bbr->rc_pacer_started = lcts;
11656 						} else {
11657 							/* We are late */
11658 							bbr->r_ctl.rc_last_delay_val = 0;
11659 							BBR_STAT_INC(bbr_force_output);
11660 							if (tcp_output(tp) < 0)
11661 								return (1);
11662 						}
11663 					}
11664 				}
11665 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11666 				    0);
11667 			}
11668 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11669 			/* Do we have the correct timer running? */
11670 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11671 		}
11672 		/* Do we have a new state */
11673 		if (bbr->r_state != tp->t_state)
11674 			bbr_set_state(tp, bbr, tiwin);
11675 done_with_input:
11676 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11677 		if (did_out)
11678 			bbr->r_wanted_output = 0;
11679 #ifdef BBR_INVARIANTS
11680 		if (tp->t_inpcb == NULL) {
11681 			panic("OP:%d retval:%d tp:%p t_inpcb:NULL state:%d",
11682 			    did_out,
11683 			    retval, tp, prev_state);
11684 		}
11685 #endif
11686 	}
11687 	return (retval);
11688 }
11689 
11690 static void
11691 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11692     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11693 {
11694 	struct timeval tv;
11695 	int retval;
11696 
11697 	/* First lets see if we have old packets */
11698 	if (tp->t_in_pkt) {
11699 		if (ctf_do_queued_segments(so, tp, 1)) {
11700 			m_freem(m);
11701 			return;
11702 		}
11703 	}
11704 	if (m->m_flags & M_TSTMP_LRO) {
11705 		tv.tv_sec = m->m_pkthdr.rcv_tstmp /1000000000;
11706 		tv.tv_usec = (m->m_pkthdr.rcv_tstmp % 1000000000)/1000;
11707 	} else {
11708 		/* Should not be should we kassert instead? */
11709 		tcp_get_usecs(&tv);
11710 	}
11711 	retval = bbr_do_segment_nounlock(m, th, so, tp,
11712 					 drop_hdrlen, tlen, iptos, 0, &tv);
11713 	if (retval == 0) {
11714 		INP_WUNLOCK(tp->t_inpcb);
11715 	}
11716 }
11717 
11718 /*
11719  * Return how much data can be sent without violating the
11720  * cwnd or rwnd.
11721  */
11722 
11723 static inline uint32_t
11724 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11725     uint32_t avail, int32_t sb_offset, uint32_t cts)
11726 {
11727 	uint32_t len;
11728 
11729 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11730 		/* We never want to go over our peers rcv-window */
11731 		len = 0;
11732 	} else {
11733 		uint32_t flight;
11734 
11735 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11736 		if (flight >= sendwin) {
11737 			/*
11738 			 * We have in flight what we are allowed by cwnd (if
11739 			 * it was rwnd blocking it would have hit above out
11740 			 * >= tp->snd_wnd).
11741 			 */
11742 			return (0);
11743 		}
11744 		len = sendwin - flight;
11745 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11746 			/* We would send too much (beyond the rwnd) */
11747 			len = tp->snd_wnd - ctf_outstanding(tp);
11748 		}
11749 		if ((len + sb_offset) > avail) {
11750 			/*
11751 			 * We don't have that much in the SB, how much is
11752 			 * there?
11753 			 */
11754 			len = avail - sb_offset;
11755 		}
11756 	}
11757 	return (len);
11758 }
11759 
11760 static inline void
11761 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11762 {
11763 #ifdef NETFLIX_STATS
11764 	KMOD_TCPSTAT_INC(tcps_sndpack_error);
11765 	KMOD_TCPSTAT_ADD(tcps_sndbyte_error, len);
11766 #endif
11767 }
11768 
11769 static inline void
11770 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11771 {
11772 	if (error) {
11773 		bbr_do_error_accounting(tp, bbr, rsm, len, error);
11774 		return;
11775 	}
11776 	if (rsm) {
11777 		if (rsm->r_flags & BBR_TLP) {
11778 			/*
11779 			 * TLP should not count in retran count, but in its
11780 			 * own bin
11781 			 */
11782 #ifdef NETFLIX_STATS
11783 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11784 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11785 #endif
11786 		} else {
11787 			/* Retransmit */
11788 			tp->t_sndrexmitpack++;
11789 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11790 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11791 #ifdef STATS
11792 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11793 			    len);
11794 #endif
11795 		}
11796 		/*
11797 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11798 		 * sub-state
11799 		 */
11800 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11801 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11802 			/* Non probe_bw log in 1, 2, or 4. */
11803 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11804 		} else {
11805 			/*
11806 			 * Log our probe state 3, and log also 5-13 to show
11807 			 * us the recovery sub-state for the send. This
11808 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11809 			 */
11810 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11811 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11812 		}
11813 		/* Place in both 16's the totals of retransmitted */
11814 		counter_u64_add(bbr_state_lost[16], len);
11815 		counter_u64_add(bbr_state_resend[16], len);
11816 		/* Place in 17's the total sent */
11817 		counter_u64_add(bbr_state_resend[17], len);
11818 		counter_u64_add(bbr_state_lost[17], len);
11819 
11820 	} else {
11821 		/* New sends */
11822 		KMOD_TCPSTAT_INC(tcps_sndpack);
11823 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11824 		/* Place in 17's the total sent */
11825 		counter_u64_add(bbr_state_resend[17], len);
11826 		counter_u64_add(bbr_state_lost[17], len);
11827 #ifdef STATS
11828 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11829 		    len);
11830 #endif
11831 	}
11832 }
11833 
11834 static void
11835 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11836 {
11837 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11838 		/*
11839 		 * Limit the cwnd to not be above N x the target plus whats
11840 		 * is outstanding. The target is based on the current b/w
11841 		 * estimate.
11842 		 */
11843 		uint32_t target;
11844 
11845 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11846 		target += ctf_outstanding(tp);
11847 		target *= bbr_target_cwnd_mult_limit;
11848 		if (tp->snd_cwnd > target)
11849 			tp->snd_cwnd = target;
11850 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11851 	}
11852 }
11853 
11854 static int
11855 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11856 {
11857 	/*
11858 	 * "adv" is the amount we could increase the window, taking into
11859 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11860 	 */
11861 	int32_t adv;
11862 	int32_t oldwin;
11863 
11864 	adv = recwin;
11865 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11866 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11867 		if (adv > oldwin)
11868 			adv -= oldwin;
11869 		else {
11870 			/* We can't increase the window */
11871 			adv = 0;
11872 		}
11873 	} else
11874 		oldwin = 0;
11875 
11876 	/*
11877 	 * If the new window size ends up being the same as or less
11878 	 * than the old size when it is scaled, then don't force
11879 	 * a window update.
11880 	 */
11881 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11882 		return (0);
11883 
11884 	if (adv >= (2 * maxseg) &&
11885 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11886 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11887 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11888 		return (1);
11889 	}
11890 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11891 		return (1);
11892 	return (0);
11893 }
11894 
11895 /*
11896  * Return 0 on success and a errno on failure to send.
11897  * Note that a 0 return may not mean we sent anything
11898  * if the TCB was on the hpts. A non-zero return
11899  * does indicate the error we got from ip[6]_output.
11900  */
11901 static int
11902 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11903 {
11904 	struct socket *so;
11905 	int32_t len;
11906 	uint32_t cts;
11907 	uint32_t recwin, sendwin;
11908 	int32_t sb_offset;
11909 	int32_t flags, abandon, error = 0;
11910 	struct tcp_log_buffer *lgb = NULL;
11911 	struct mbuf *m;
11912 	struct mbuf *mb;
11913 	uint32_t if_hw_tsomaxsegcount = 0;
11914 	uint32_t if_hw_tsomaxsegsize = 0;
11915 	uint32_t if_hw_tsomax = 0;
11916 	struct ip *ip = NULL;
11917 #ifdef TCPDEBUG
11918 	struct ipovly *ipov = NULL;
11919 #endif
11920 	struct tcp_bbr *bbr;
11921 	struct tcphdr *th;
11922 	struct udphdr *udp = NULL;
11923 	u_char opt[TCP_MAXOLEN];
11924 	unsigned ipoptlen, optlen, hdrlen;
11925 	unsigned ulen;
11926 	uint32_t bbr_seq;
11927 	uint32_t delay_calc=0;
11928 	uint8_t doing_tlp = 0;
11929 	uint8_t local_options;
11930 #ifdef BBR_INVARIANTS
11931 	uint8_t doing_retran_from = 0;
11932 	uint8_t picked_up_retran = 0;
11933 #endif
11934 	uint8_t wanted_cookie = 0;
11935 	uint8_t more_to_rxt=0;
11936 	int32_t prefetch_so_done = 0;
11937 	int32_t prefetch_rsm = 0;
11938 	uint32_t tot_len = 0;
11939 	uint32_t rtr_cnt = 0;
11940 	uint32_t maxseg, pace_max_segs, p_maxseg;
11941 	int32_t csum_flags = 0;
11942  	int32_t hw_tls;
11943 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11944 	unsigned ipsec_optlen = 0;
11945 
11946 #endif
11947 	volatile int32_t sack_rxmit;
11948 	struct bbr_sendmap *rsm = NULL;
11949 	int32_t tso, mtu;
11950 	struct tcpopt to;
11951 	int32_t slot = 0;
11952 	struct inpcb *inp;
11953 	struct sockbuf *sb;
11954 	uint32_t hpts_calling;
11955 #ifdef INET6
11956 	struct ip6_hdr *ip6 = NULL;
11957 	int32_t isipv6;
11958 #endif
11959 	uint8_t app_limited = BBR_JR_SENT_DATA;
11960 	uint8_t filled_all = 0;
11961 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11962 	/* We take a cache hit here */
11963 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11964 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11965 	inp = bbr->rc_inp;
11966 	so = inp->inp_socket;
11967 	sb = &so->so_snd;
11968  	if (sb->sb_flags & SB_TLS_IFNET)
11969  		hw_tls = 1;
11970  	else
11971  		hw_tls = 0;
11972 	kern_prefetch(sb, &maxseg);
11973 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11974 	if (bbr_minseg(bbr) < maxseg) {
11975 		tcp_bbr_tso_size_check(bbr, cts);
11976 	}
11977 	/* Remove any flags that indicate we are pacing on the inp  */
11978 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11979 	p_maxseg = min(maxseg, pace_max_segs);
11980 	INP_WLOCK_ASSERT(inp);
11981 #ifdef TCP_OFFLOAD
11982 	if (tp->t_flags & TF_TOE)
11983 		return (tcp_offload_output(tp));
11984 #endif
11985 
11986 #ifdef INET6
11987 	if (bbr->r_state) {
11988 		/* Use the cache line loaded if possible */
11989 		isipv6 = bbr->r_is_v6;
11990 	} else {
11991 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11992 	}
11993 #endif
11994 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11995 	    tcp_in_hpts(inp)) {
11996 		/*
11997 		 * We are on the hpts for some timer but not hptsi output.
11998 		 * Possibly remove from the hpts so we can send/recv etc.
11999 		 */
12000 		if ((tp->t_flags & TF_ACKNOW) == 0) {
12001 			/*
12002 			 * No immediate demand right now to send an ack, but
12003 			 * the user may have read, making room for new data
12004 			 * (a window update). If so we may want to cancel
12005 			 * whatever timer is running (KEEP/DEL-ACK?) and
12006 			 * continue to send out a window update. Or we may
12007 			 * have gotten more data into the socket buffer to
12008 			 * send.
12009 			 */
12010 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12011 				      (long)TCP_MAXWIN << tp->rcv_scale);
12012 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
12013 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
12014 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
12015 			    (tp->snd_max - tp->snd_una))) {
12016 				/*
12017 				 * Nothing new to send and no window update
12018 				 * is needed to send. Lets just return and
12019 				 * let the timer-run off.
12020 				 */
12021 				return (0);
12022 			}
12023 		}
12024 		tcp_hpts_remove(inp);
12025 		bbr_timer_cancel(bbr, __LINE__, cts);
12026 	}
12027 	if (bbr->r_ctl.rc_last_delay_val) {
12028 		/* Calculate a rough delay for early escape to sending  */
12029 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12030 			delay_calc = cts - bbr->rc_pacer_started;
12031 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12032 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12033 		else
12034 			delay_calc = 0;
12035 	}
12036 	/* Mark that we have called bbr_output(). */
12037 	if ((bbr->r_timer_override) ||
12038 	    (tp->t_state < TCPS_ESTABLISHED)) {
12039 		/* Timeouts or early states are exempt */
12040 		if (tcp_in_hpts(inp))
12041 			tcp_hpts_remove(inp);
12042 	} else if (tcp_in_hpts(inp)) {
12043 		if ((bbr->r_ctl.rc_last_delay_val) &&
12044 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
12045 		    delay_calc) {
12046 			/*
12047 			 * We were being paced for output and the delay has
12048 			 * already exceeded when we were supposed to be
12049 			 * called, lets go ahead and pull out of the hpts
12050 			 * and call output.
12051 			 */
12052 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
12053 			bbr->r_ctl.rc_last_delay_val = 0;
12054 			tcp_hpts_remove(inp);
12055 		} else if (tp->t_state == TCPS_CLOSED) {
12056 			bbr->r_ctl.rc_last_delay_val = 0;
12057 			tcp_hpts_remove(inp);
12058 		} else {
12059 			/*
12060 			 * On the hpts, you shall not pass! even if ACKNOW
12061 			 * is on, we will when the hpts fires, unless of
12062 			 * course we are overdue.
12063 			 */
12064 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
12065 			return (0);
12066 		}
12067 	}
12068 	bbr->rc_cwnd_limited = 0;
12069 	if (bbr->r_ctl.rc_last_delay_val) {
12070 		/* recalculate the real delay and deal with over/under  */
12071 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12072 			delay_calc = cts - bbr->rc_pacer_started;
12073 		else
12074 			delay_calc = 0;
12075 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12076 			/* Setup the delay which will be added in */
12077 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12078 		else {
12079 			/*
12080 			 * We are early setup to adjust
12081 			 * our slot time.
12082 			 */
12083 			uint64_t merged_val;
12084 
12085 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12086 			bbr->r_agg_early_set = 1;
12087 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
12088 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12089 					/* Nope our previous late cancels out the early */
12090 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12091 					bbr->r_agg_early_set = 0;
12092 					bbr->r_ctl.rc_agg_early = 0;
12093 				} else {
12094 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12095 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
12096 				}
12097 			}
12098 			merged_val = bbr->rc_pacer_started;
12099 			merged_val <<= 32;
12100 			merged_val |= bbr->r_ctl.rc_last_delay_val;
12101 			bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
12102 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12103 						 bbr->r_agg_early_set, 3);
12104 			bbr->r_ctl.rc_last_delay_val = 0;
12105 			BBR_STAT_INC(bbr_early);
12106 			delay_calc = 0;
12107 		}
12108 	} else {
12109 		/* We were not delayed due to hptsi */
12110 		if (bbr->r_agg_early_set)
12111 			bbr->r_ctl.rc_agg_early = 0;
12112 		bbr->r_agg_early_set = 0;
12113 		delay_calc = 0;
12114 	}
12115 	if (delay_calc) {
12116 		/*
12117 		 * We had a hptsi delay which means we are falling behind on
12118 		 * sending at the expected rate. Calculate an extra amount
12119 		 * of data we can send, if any, to put us back on track.
12120 		 */
12121 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12122 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12123 		else
12124 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12125 	}
12126 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12127 	if ((tp->snd_una == tp->snd_max) &&
12128 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12129 	    (sbavail(sb))) {
12130 		/*
12131 		 * Ok we have been idle with nothing outstanding
12132 		 * we possibly need to start fresh with either a new
12133 		 * suite of states or a fast-ramp up.
12134 		 */
12135 		bbr_restart_after_idle(bbr,
12136 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12137 	}
12138 	/*
12139 	 * Now was there a hptsi delay where we are behind? We only count
12140 	 * being behind if: a) We are not in recovery. b) There was a delay.
12141 	 * <and> c) We had room to send something.
12142 	 *
12143 	 */
12144 	hpts_calling = inp->inp_hpts_calls;
12145 	inp->inp_hpts_calls = 0;
12146 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12147 		int retval;
12148 
12149 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12150 		if (retval != 0) {
12151 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12152 			/*
12153 			 * If timers want tcp_drop(), then pass error out,
12154 			 * otherwise suppress it.
12155 			 */
12156 			return (retval < 0 ? retval : 0);
12157 		}
12158 	}
12159 	bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12160 	if (hpts_calling &&
12161 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12162 		bbr->r_ctl.rc_last_delay_val = 0;
12163 	}
12164 	bbr->r_timer_override = 0;
12165 	bbr->r_wanted_output = 0;
12166 	/*
12167 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12168 	 * SYN|ACK and those sent by the retransmit timer.
12169 	 */
12170 	if (IS_FASTOPEN(tp->t_flags) &&
12171 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12172 	     (tp->t_state == TCPS_SYN_SENT)) &&
12173 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12174 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12175 		len = 0;
12176 		goto just_return_nolock;
12177 	}
12178 	/*
12179 	 * Before sending anything check for a state update. For hpts
12180 	 * calling without input this is important. If its input calling
12181 	 * then this was already done.
12182 	 */
12183 	if (bbr->rc_use_google == 0)
12184 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12185 again:
12186 	/*
12187 	 * If we've recently taken a timeout, snd_max will be greater than
12188 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12189 	 * for historic reasons the persist timer still uses it. This means
12190 	 * we have to look at it. All retransmissions that are not persits
12191 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12192 	 * end of this routine we pull snd_nxt always up to snd_max.
12193 	 */
12194 	doing_tlp = 0;
12195 #ifdef BBR_INVARIANTS
12196 	doing_retran_from = picked_up_retran = 0;
12197 #endif
12198 	error = 0;
12199 	tso = 0;
12200 	slot = 0;
12201 	mtu = 0;
12202 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12203 	sb_offset = tp->snd_max - tp->snd_una;
12204 	flags = tcp_outflags[tp->t_state];
12205 	sack_rxmit = 0;
12206 	len = 0;
12207 	rsm = NULL;
12208 	if (flags & TH_RST) {
12209 		SOCKBUF_LOCK(sb);
12210 		goto send;
12211 	}
12212 recheck_resend:
12213 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12214 		/* We need to always have one in reserve */
12215 		rsm = bbr_alloc(bbr);
12216 		if (rsm == NULL) {
12217 			error = ENOMEM;
12218 			/* Lie to get on the hpts */
12219 			tot_len = tp->t_maxseg;
12220 			if (hpts_calling)
12221 				/* Retry in a ms */
12222 				slot = 1001;
12223 			goto just_return_nolock;
12224 		}
12225 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12226 		bbr->r_ctl.rc_free_cnt++;
12227 		rsm = NULL;
12228 	}
12229 	/* What do we send, a resend? */
12230 	if (bbr->r_ctl.rc_resend == NULL) {
12231 		/* Check for rack timeout */
12232 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12233 		if (bbr->r_ctl.rc_resend) {
12234 #ifdef BBR_INVARIANTS
12235 			picked_up_retran = 1;
12236 #endif
12237 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12238 		}
12239 	}
12240 	if (bbr->r_ctl.rc_resend) {
12241 		rsm = bbr->r_ctl.rc_resend;
12242 #ifdef BBR_INVARIANTS
12243 		doing_retran_from = 1;
12244 #endif
12245 		/* Remove any TLP flags its a RACK or T-O */
12246 		rsm->r_flags &= ~BBR_TLP;
12247 		bbr->r_ctl.rc_resend = NULL;
12248 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12249 #ifdef BBR_INVARIANTS
12250 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12251 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12252 			goto recheck_resend;
12253 #else
12254 			/* TSNH */
12255 			rsm = NULL;
12256 			goto recheck_resend;
12257 #endif
12258 		}
12259 		rtr_cnt++;
12260 		if (rsm->r_flags & BBR_HAS_SYN) {
12261 			/* Only retransmit a SYN by itself */
12262 			len = 0;
12263 			if ((flags & TH_SYN) == 0) {
12264 				/* Huh something is wrong */
12265 				rsm->r_start++;
12266 				if (rsm->r_start == rsm->r_end) {
12267 					/* Clean it up, somehow we missed the ack? */
12268 					bbr_log_syn(tp, NULL);
12269 				} else {
12270 					/* TFO with data? */
12271 					rsm->r_flags &= ~BBR_HAS_SYN;
12272 					len = rsm->r_end - rsm->r_start;
12273 				}
12274 			} else {
12275 				/* Retransmitting SYN */
12276 				rsm = NULL;
12277 				SOCKBUF_LOCK(sb);
12278 				goto send;
12279 			}
12280 		} else
12281 			len = rsm->r_end - rsm->r_start;
12282 		if ((bbr->rc_resends_use_tso == 0) &&
12283 		    (len > maxseg)) {
12284 			len = maxseg;
12285 			more_to_rxt = 1;
12286 		}
12287 		sb_offset = rsm->r_start - tp->snd_una;
12288 		if (len > 0) {
12289 			sack_rxmit = 1;
12290 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12291 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12292 			    min(len, maxseg));
12293 		} else {
12294 			/* I dont think this can happen */
12295 			rsm = NULL;
12296 			goto recheck_resend;
12297 		}
12298 		BBR_STAT_INC(bbr_resends_set);
12299 	} else if (bbr->r_ctl.rc_tlp_send) {
12300 		/*
12301 		 * Tail loss probe
12302 		 */
12303 		doing_tlp = 1;
12304 		rsm = bbr->r_ctl.rc_tlp_send;
12305 		bbr->r_ctl.rc_tlp_send = NULL;
12306 		sack_rxmit = 1;
12307 		len = rsm->r_end - rsm->r_start;
12308 		rtr_cnt++;
12309 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12310 			len = maxseg;
12311 
12312 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12313 #ifdef BBR_INVARIANTS
12314 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12315 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12316 #else
12317 			/* TSNH */
12318 			rsm = NULL;
12319 			goto recheck_resend;
12320 #endif
12321 		}
12322 		sb_offset = rsm->r_start - tp->snd_una;
12323 		BBR_STAT_INC(bbr_tlp_set);
12324 	}
12325 	/*
12326 	 * Enforce a connection sendmap count limit if set
12327 	 * as long as we are not retransmiting.
12328 	 */
12329 	if ((rsm == NULL) &&
12330 	    (V_tcp_map_entries_limit > 0) &&
12331 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12332 		BBR_STAT_INC(bbr_alloc_limited);
12333 		if (!bbr->alloc_limit_reported) {
12334 			bbr->alloc_limit_reported = 1;
12335 			BBR_STAT_INC(bbr_alloc_limited_conns);
12336 		}
12337 		goto just_return_nolock;
12338 	}
12339 #ifdef BBR_INVARIANTS
12340 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12341 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12342 		    tp, bbr, rsm, sb_offset, len);
12343 	}
12344 #endif
12345 	/*
12346 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12347 	 * state flags.
12348 	 */
12349 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12350 		flags |= TH_FIN;
12351 	if (tp->t_flags & TF_NEEDSYN)
12352 		flags |= TH_SYN;
12353 
12354 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12355 		/* we are retransmitting the fin */
12356 		len--;
12357 		if (len) {
12358 			/*
12359 			 * When retransmitting data do *not* include the
12360 			 * FIN. This could happen from a TLP probe if we
12361 			 * allowed data with a FIN.
12362 			 */
12363 			flags &= ~TH_FIN;
12364 		}
12365 	} else if (rsm) {
12366 		if (flags & TH_FIN)
12367 			flags &= ~TH_FIN;
12368 	}
12369 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12370 		void *end_rsm;
12371 
12372 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12373 		if (end_rsm)
12374 			kern_prefetch(end_rsm, &prefetch_rsm);
12375 		prefetch_rsm = 1;
12376 	}
12377 	SOCKBUF_LOCK(sb);
12378 	/*
12379 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12380 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12381 	 * negative length.  This can also occur when TCP opens up its
12382 	 * congestion window while receiving additional duplicate acks after
12383 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12384 	 * the fast-retransmit.
12385 	 *
12386 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12387 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12388 	 * up 0.
12389 	 *
12390 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12391 	 * in which case len is already set.
12392 	 */
12393 	if (sack_rxmit == 0) {
12394 		uint32_t avail;
12395 
12396 		avail = sbavail(sb);
12397 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12398 			sb_offset = tp->snd_max - tp->snd_una;
12399 		else
12400 			sb_offset = 0;
12401 		if (bbr->rc_tlp_new_data) {
12402 			/* TLP is forcing out new data */
12403 			uint32_t tlplen;
12404 
12405 			doing_tlp = 1;
12406 			tlplen = maxseg;
12407 
12408 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12409 				tlplen = (uint32_t)(avail - sb_offset);
12410 			}
12411 			if (tlplen > tp->snd_wnd) {
12412 				len = tp->snd_wnd;
12413 			} else {
12414 				len = tlplen;
12415 			}
12416 			bbr->rc_tlp_new_data = 0;
12417 		} else {
12418 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12419 			if ((len < p_maxseg) &&
12420 			    (bbr->rc_in_persist == 0) &&
12421 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12422 			    ((avail - sb_offset) >= p_maxseg)) {
12423 				/*
12424 				 * We are not completing whats in the socket
12425 				 * buffer (i.e. there is at least a segment
12426 				 * waiting to send) and we have 2 or more
12427 				 * segments outstanding. There is no sense
12428 				 * of sending a little piece. Lets defer and
12429 				 * and wait until we can send a whole
12430 				 * segment.
12431 				 */
12432 				len = 0;
12433 			}
12434 			if (bbr->rc_in_persist) {
12435 				/*
12436 				 * We are in persists, figure out if
12437 				 * a retransmit is available (maybe the previous
12438 				 * persists we sent) or if we have to send new
12439 				 * data.
12440 				 */
12441 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12442 				if (rsm) {
12443 					len = rsm->r_end - rsm->r_start;
12444 					if (rsm->r_flags & BBR_HAS_FIN)
12445 						len--;
12446 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12447 						len = maxseg;
12448 					if (len > 1)
12449 						BBR_STAT_INC(bbr_persist_reneg);
12450 					/*
12451 					 * XXXrrs we could force the len to
12452 					 * 1 byte here to cause the chunk to
12453 					 * split apart.. but that would then
12454 					 * mean we always retransmit it as
12455 					 * one byte even after the window
12456 					 * opens.
12457 					 */
12458 					sack_rxmit = 1;
12459 					sb_offset = rsm->r_start - tp->snd_una;
12460 				} else {
12461 					/*
12462 					 * First time through in persists or peer
12463 					 * acked our one byte. Though we do have
12464 					 * to have something in the sb.
12465 					 */
12466 					len = 1;
12467 					sb_offset = 0;
12468 					if (avail == 0)
12469 					    len = 0;
12470 				}
12471 			}
12472 		}
12473 	}
12474 	if (prefetch_so_done == 0) {
12475 		kern_prefetch(so, &prefetch_so_done);
12476 		prefetch_so_done = 1;
12477 	}
12478 	/*
12479 	 * Lop off SYN bit if it has already been sent.  However, if this is
12480 	 * SYN-SENT state and if segment contains data and if we don't know
12481 	 * that foreign host supports TAO, suppress sending segment.
12482 	 */
12483 	if ((flags & TH_SYN) && (rsm == NULL) &&
12484 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12485 		if (tp->t_state != TCPS_SYN_RECEIVED)
12486 			flags &= ~TH_SYN;
12487 		/*
12488 		 * When sending additional segments following a TFO SYN|ACK,
12489 		 * do not include the SYN bit.
12490 		 */
12491 		if (IS_FASTOPEN(tp->t_flags) &&
12492 		    (tp->t_state == TCPS_SYN_RECEIVED))
12493 			flags &= ~TH_SYN;
12494 		sb_offset--, len++;
12495 		if (sbavail(sb) == 0)
12496 			len = 0;
12497 	} else if ((flags & TH_SYN) && rsm) {
12498 		/*
12499 		 * Subtract one from the len for the SYN being
12500 		 * retransmitted.
12501 		 */
12502 		len--;
12503 	}
12504 	/*
12505 	 * Be careful not to send data and/or FIN on SYN segments. This
12506 	 * measure is needed to prevent interoperability problems with not
12507 	 * fully conformant TCP implementations.
12508 	 */
12509 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12510 		len = 0;
12511 		flags &= ~TH_FIN;
12512 	}
12513 	/*
12514 	 * On TFO sockets, ensure no data is sent in the following cases:
12515 	 *
12516 	 *  - When retransmitting SYN|ACK on a passively-created socket
12517 	 *  - When retransmitting SYN on an actively created socket
12518 	 *  - When sending a zero-length cookie (cookie request) on an
12519 	 *    actively created socket
12520 	 *  - When the socket is in the CLOSED state (RST is being sent)
12521 	 */
12522 	if (IS_FASTOPEN(tp->t_flags) &&
12523 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12524 	     ((tp->t_state == TCPS_SYN_SENT) &&
12525 	      (tp->t_tfo_client_cookie_len == 0)) ||
12526 	     (flags & TH_RST))) {
12527 		len = 0;
12528 		sack_rxmit = 0;
12529 		rsm = NULL;
12530 	}
12531 	/* Without fast-open there should never be data sent on a SYN */
12532 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12533 		len = 0;
12534 	if (len <= 0) {
12535 		/*
12536 		 * If FIN has been sent but not acked, but we haven't been
12537 		 * called to retransmit, len will be < 0.  Otherwise, window
12538 		 * shrank after we sent into it.  If window shrank to 0,
12539 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12540 		 * window, and set the persist timer if it isn't already
12541 		 * going.  If the window didn't close completely, just wait
12542 		 * for an ACK.
12543 		 *
12544 		 * We also do a general check here to ensure that we will
12545 		 * set the persist timer when we have data to send, but a
12546 		 * 0-byte window. This makes sure the persist timer is set
12547 		 * even if the packet hits one of the "goto send" lines
12548 		 * below.
12549 		 */
12550 		len = 0;
12551 		if ((tp->snd_wnd == 0) &&
12552 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12553 		    (tp->snd_una == tp->snd_max) &&
12554 		    (sb_offset < (int)sbavail(sb))) {
12555 			/*
12556 			 * Not enough room in the rwnd to send
12557 			 * a paced segment out.
12558 			 */
12559 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12560 		}
12561 	} else if ((rsm == NULL) &&
12562 		   (doing_tlp == 0) &&
12563 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12564 		/*
12565 		 * We are not sending a full segment for
12566 		 * some reason. Should we not send anything (think
12567 		 * sws or persists)?
12568 		 */
12569 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12570 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12571 		    (len < (int)(sbavail(sb) - sb_offset))) {
12572 			/*
12573 			 * Here the rwnd is less than
12574 			 * the pacing size, this is not a retransmit,
12575 			 * we are established and
12576 			 * the send is not the last in the socket buffer
12577 			 * lets not send, and possibly enter persists.
12578 			 */
12579 			len = 0;
12580 			if (tp->snd_max == tp->snd_una)
12581 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12582 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12583 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12584 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12585 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12586 			   (len < bbr_minseg(bbr))) {
12587 			/*
12588 			 * Here we are not retransmitting, and
12589 			 * the cwnd is not so small that we could
12590 			 * not send at least a min size (rxt timer
12591 			 * not having gone off), We have 2 segments or
12592 			 * more already in flight, its not the tail end
12593 			 * of the socket buffer  and the cwnd is blocking
12594 			 * us from sending out minimum pacing segment size.
12595 			 * Lets not send anything.
12596 			 */
12597 			bbr->rc_cwnd_limited = 1;
12598 			len = 0;
12599 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12600 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12601 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12602 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12603 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12604 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12605 			/*
12606 			 * Here we have a send window but we have
12607 			 * filled it up and we can't send another pacing segment.
12608 			 * We also have in flight more than 2 segments
12609 			 * and we are not completing the sb i.e. we allow
12610 			 * the last bytes of the sb to go out even if
12611 			 * its not a full pacing segment.
12612 			 */
12613 			len = 0;
12614 		}
12615 	}
12616 	/* len will be >= 0 after this point. */
12617 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12618 	tcp_sndbuf_autoscale(tp, so, sendwin);
12619 	/*
12620 	 *
12621 	 */
12622 	if (bbr->rc_in_persist &&
12623 	    len &&
12624 	    (rsm == NULL) &&
12625 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12626 		/*
12627 		 * We are in persist, not doing a retransmit and don't have enough space
12628 		 * yet to send a full TSO. So is it at the end of the sb
12629 		 * if so we need to send else nuke to 0 and don't send.
12630 		 */
12631 		int sbleft;
12632 		if (sbavail(sb) > sb_offset)
12633 			sbleft = sbavail(sb) - sb_offset;
12634 		else
12635 			sbleft = 0;
12636 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12637 			/* not at end of sb lets not send */
12638 			len = 0;
12639 		}
12640 	}
12641 	/*
12642 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12643 	 * hardware).
12644 	 *
12645 	 * TSO may only be used if we are in a pure bulk sending state.  The
12646 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12647 	 * options prevent using TSO.  With TSO the TCP header is the same
12648 	 * (except for the sequence number) for all generated packets.  This
12649 	 * makes it impossible to transmit any options which vary per
12650 	 * generated segment or packet.
12651 	 *
12652 	 * IPv4 handling has a clear separation of ip options and ip header
12653 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12654 	 * does the right thing below to provide length of just ip options
12655 	 * and thus checking for ipoptlen is enough to decide if ip options
12656 	 * are present.
12657 	 */
12658 #ifdef INET6
12659 	if (isipv6)
12660 		ipoptlen = ip6_optlen(inp);
12661 	else
12662 #endif
12663 	if (inp->inp_options)
12664 		ipoptlen = inp->inp_options->m_len -
12665 		    offsetof(struct ipoption, ipopt_list);
12666 	else
12667 		ipoptlen = 0;
12668 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12669 	/*
12670 	 * Pre-calculate here as we save another lookup into the darknesses
12671 	 * of IPsec that way and can actually decide if TSO is ok.
12672 	 */
12673 #ifdef INET6
12674 	if (isipv6 && IPSEC_ENABLED(ipv6))
12675 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12676 #ifdef INET
12677 	else
12678 #endif
12679 #endif				/* INET6 */
12680 #ifdef INET
12681 	if (IPSEC_ENABLED(ipv4))
12682 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12683 #endif				/* INET */
12684 #endif				/* IPSEC */
12685 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12686 	ipoptlen += ipsec_optlen;
12687 #endif
12688 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12689 	    (len > maxseg) &&
12690 	    (tp->t_port == 0) &&
12691 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12692 	    tp->rcv_numsacks == 0 &&
12693 	    ipoptlen == 0)
12694 		tso = 1;
12695 
12696 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12697 	    (long)TCP_MAXWIN << tp->rcv_scale);
12698 	/*
12699 	 * Sender silly window avoidance.   We transmit under the following
12700 	 * conditions when len is non-zero:
12701 	 *
12702 	 * - We have a full segment (or more with TSO) - This is the last
12703 	 * buffer in a write()/send() and we are either idle or running
12704 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12705 	 * then 1/2 the maximum send window's worth of data (receiver may be
12706 	 * limited the window size) - we need to retransmit
12707 	 */
12708 	if (rsm)
12709 		goto send;
12710 	if (len) {
12711 		if (sack_rxmit)
12712 			goto send;
12713 		if (len >= p_maxseg)
12714 			goto send;
12715 		/*
12716 		 * NOTE! on localhost connections an 'ack' from the remote
12717 		 * end may occur synchronously with the output and cause us
12718 		 * to flush a buffer queued with moretocome.  XXX
12719 		 *
12720 		 */
12721 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12722 		    ((tp->t_flags & TF_NODELAY) ||
12723 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12724 		    (tp->t_flags & TF_NOPUSH) == 0) {
12725 			goto send;
12726 		}
12727 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12728 			goto send;
12729 		}
12730 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12731 			goto send;
12732 		}
12733 	}
12734 	/*
12735 	 * Sending of standalone window updates.
12736 	 *
12737 	 * Window updates are important when we close our window due to a
12738 	 * full socket buffer and are opening it again after the application
12739 	 * reads data from it.  Once the window has opened again and the
12740 	 * remote end starts to send again the ACK clock takes over and
12741 	 * provides the most current window information.
12742 	 *
12743 	 * We must avoid the silly window syndrome whereas every read from
12744 	 * the receive buffer, no matter how small, causes a window update
12745 	 * to be sent.  We also should avoid sending a flurry of window
12746 	 * updates when the socket buffer had queued a lot of data and the
12747 	 * application is doing small reads.
12748 	 *
12749 	 * Prevent a flurry of pointless window updates by only sending an
12750 	 * update when we can increase the advertized window by more than
12751 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12752 	 * full or is very small be more aggressive and send an update
12753 	 * whenever we can increase by two mss sized segments. In all other
12754 	 * situations the ACK's to new incoming data will carry further
12755 	 * window increases.
12756 	 *
12757 	 * Don't send an independent window update if a delayed ACK is
12758 	 * pending (it will get piggy-backed on it) or the remote side
12759 	 * already has done a half-close and won't send more data.  Skip
12760 	 * this if the connection is in T/TCP half-open state.
12761 	 */
12762 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12763 	    !(tp->t_flags & TF_DELACK) &&
12764 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12765 		/* Check to see if we should do a window update */
12766 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12767 			goto send;
12768 	}
12769 	/*
12770 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12771 	 * is also a catch-all for the retransmit timer timeout case.
12772 	 */
12773 	if (tp->t_flags & TF_ACKNOW) {
12774 		goto send;
12775 	}
12776 	if (flags & TH_RST) {
12777 		/* Always send a RST if one is due */
12778 		goto send;
12779 	}
12780 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12781 		goto send;
12782 	}
12783 	/*
12784 	 * If our state indicates that FIN should be sent and we have not
12785 	 * yet done so, then we need to send.
12786 	 */
12787 	if (flags & TH_FIN &&
12788 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12789 		goto send;
12790 	}
12791 	/*
12792 	 * No reason to send a segment, just return.
12793 	 */
12794 just_return:
12795 	SOCKBUF_UNLOCK(sb);
12796 just_return_nolock:
12797 	if (tot_len)
12798 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12799 	if (bbr->rc_no_pacing)
12800 		slot = 0;
12801 	if (tot_len == 0) {
12802 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12803 		    tp->snd_wnd) {
12804 			BBR_STAT_INC(bbr_rwnd_limited);
12805 			app_limited = BBR_JR_RWND_LIMITED;
12806 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12807 			if ((bbr->rc_in_persist == 0) &&
12808 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12809 			    (tp->snd_max == tp->snd_una) &&
12810 			    sbavail(&tp->t_inpcb->inp_socket->so_snd)) {
12811 				/* No send window.. we must enter persist */
12812 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12813 			}
12814 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12815 			BBR_STAT_INC(bbr_app_limited);
12816 			app_limited = BBR_JR_APP_LIMITED;
12817 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12818 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12819 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12820 			BBR_STAT_INC(bbr_cwnd_limited);
12821  			app_limited = BBR_JR_CWND_LIMITED;
12822 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12823 									bbr->r_ctl.rc_lost_bytes)));
12824 			bbr->rc_cwnd_limited = 1;
12825 		} else {
12826 			BBR_STAT_INC(bbr_app_limited);
12827 			app_limited = BBR_JR_APP_LIMITED;
12828 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12829 		}
12830 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12831 		bbr->r_agg_early_set = 0;
12832 		bbr->r_ctl.rc_agg_early = 0;
12833 		bbr->r_ctl.rc_last_delay_val = 0;
12834 	} else if (bbr->rc_use_google == 0)
12835 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12836 	/* Are we app limited? */
12837 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12838 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12839 		/**
12840 		 * We are application limited.
12841 		 */
12842 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12843 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12844 	}
12845 	if (tot_len == 0)
12846 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12847 	/* Dont update the time if we did not send */
12848 	bbr->r_ctl.rc_last_delay_val = 0;
12849 	bbr->rc_output_starts_timer = 1;
12850 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12851 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12852 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12853 		/* Make sure snd_nxt is drug up */
12854 		tp->snd_nxt = tp->snd_max;
12855 	}
12856 	return (error);
12857 
12858 send:
12859 	if (doing_tlp == 0) {
12860 		/*
12861 		 * Data not a TLP, and its not the rxt firing. If it is the
12862 		 * rxt firing, we want to leave the tlp_in_progress flag on
12863 		 * so we don't send another TLP. It has to be a rack timer
12864 		 * or normal send (response to acked data) to clear the tlp
12865 		 * in progress flag.
12866 		 */
12867 		bbr->rc_tlp_in_progress = 0;
12868 		bbr->rc_tlp_rtx_out = 0;
12869 	} else {
12870 		/*
12871 		 * Its a TLP.
12872 		 */
12873 		bbr->rc_tlp_in_progress = 1;
12874 	}
12875 	bbr_timer_cancel(bbr, __LINE__, cts);
12876 	if (rsm == NULL) {
12877 		if (sbused(sb) > 0) {
12878 			/*
12879 			 * This is sub-optimal. We only send a stand alone
12880 			 * FIN on its own segment.
12881 			 */
12882 			if (flags & TH_FIN) {
12883 				flags &= ~TH_FIN;
12884 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12885 					/* Lets not send this */
12886 					slot = 0;
12887 					goto just_return;
12888 				}
12889 			}
12890 		}
12891 	} else {
12892 		/*
12893 		 * We do *not* send a FIN on a retransmit if it has data.
12894 		 * The if clause here where len > 1 should never come true.
12895 		 */
12896 		if ((len > 0) &&
12897 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12898 		    (flags & TH_FIN))) {
12899 			flags &= ~TH_FIN;
12900 			len--;
12901 		}
12902 	}
12903 	SOCKBUF_LOCK_ASSERT(sb);
12904 	if (len > 0) {
12905 		if ((tp->snd_una == tp->snd_max) &&
12906 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12907 			/*
12908 			 * This qualifies as a RTT_PROBE session since we
12909 			 * drop the data outstanding to nothing and waited
12910 			 * more than bbr_rtt_probe_time.
12911 			 */
12912 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12913 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12914 		}
12915 		if (len >= maxseg)
12916 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12917 		else
12918 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12919 	}
12920 	/*
12921 	 * Before ESTABLISHED, force sending of initial options unless TCP
12922 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12923 	 * plus TCP options always fit in a single mbuf, leaving room for a
12924 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12925 	 * + optlen <= MCLBYTES
12926 	 */
12927 	optlen = 0;
12928 #ifdef INET6
12929 	if (isipv6)
12930 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12931 	else
12932 #endif
12933 		hdrlen = sizeof(struct tcpiphdr);
12934 
12935 	/*
12936 	 * Compute options for segment. We only have to care about SYN and
12937 	 * established connection segments.  Options for SYN-ACK segments
12938 	 * are handled in TCP syncache.
12939 	 */
12940 	to.to_flags = 0;
12941 	local_options = 0;
12942 	if ((tp->t_flags & TF_NOOPT) == 0) {
12943 		/* Maximum segment size. */
12944 		if (flags & TH_SYN) {
12945 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12946 			if (tp->t_port)
12947 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12948 			to.to_flags |= TOF_MSS;
12949 			/*
12950 			 * On SYN or SYN|ACK transmits on TFO connections,
12951 			 * only include the TFO option if it is not a
12952 			 * retransmit, as the presence of the TFO option may
12953 			 * have caused the original SYN or SYN|ACK to have
12954 			 * been dropped by a middlebox.
12955 			 */
12956 			if (IS_FASTOPEN(tp->t_flags) &&
12957 			    (tp->t_rxtshift == 0)) {
12958 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12959 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12960 					to.to_tfo_cookie =
12961 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12962 					to.to_flags |= TOF_FASTOPEN;
12963 					wanted_cookie = 1;
12964 				} else if (tp->t_state == TCPS_SYN_SENT) {
12965 					to.to_tfo_len =
12966 					    tp->t_tfo_client_cookie_len;
12967 					to.to_tfo_cookie =
12968 					    tp->t_tfo_cookie.client;
12969 					to.to_flags |= TOF_FASTOPEN;
12970 					wanted_cookie = 1;
12971 				}
12972 			}
12973 		}
12974 		/* Window scaling. */
12975 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12976 			to.to_wscale = tp->request_r_scale;
12977 			to.to_flags |= TOF_SCALE;
12978 		}
12979 		/* Timestamps. */
12980 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12981 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12982 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12983 			to.to_tsecr = tp->ts_recent;
12984 			to.to_flags |= TOF_TS;
12985 			local_options += TCPOLEN_TIMESTAMP + 2;
12986 		}
12987 		/* Set receive buffer autosizing timestamp. */
12988 		if (tp->rfbuf_ts == 0 &&
12989 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12990 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12991 		/* Selective ACK's. */
12992 		if (flags & TH_SYN)
12993 			to.to_flags |= TOF_SACKPERM;
12994 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12995 		    tp->rcv_numsacks > 0) {
12996 			to.to_flags |= TOF_SACK;
12997 			to.to_nsacks = tp->rcv_numsacks;
12998 			to.to_sacks = (u_char *)tp->sackblks;
12999 		}
13000 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13001 		/* TCP-MD5 (RFC2385). */
13002 		if (tp->t_flags & TF_SIGNATURE)
13003 			to.to_flags |= TOF_SIGNATURE;
13004 #endif				/* TCP_SIGNATURE */
13005 
13006 		/* Processing the options. */
13007 		hdrlen += (optlen = tcp_addoptions(&to, opt));
13008 		/*
13009 		 * If we wanted a TFO option to be added, but it was unable
13010 		 * to fit, ensure no data is sent.
13011 		 */
13012 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
13013 		    !(to.to_flags & TOF_FASTOPEN))
13014 			len = 0;
13015 	}
13016 	if (tp->t_port) {
13017 		if (V_tcp_udp_tunneling_port == 0) {
13018 			/* The port was removed?? */
13019 			SOCKBUF_UNLOCK(&so->so_snd);
13020 			return (EHOSTUNREACH);
13021 		}
13022 		hdrlen += sizeof(struct udphdr);
13023 	}
13024 #ifdef INET6
13025 	if (isipv6)
13026 		ipoptlen = ip6_optlen(tp->t_inpcb);
13027 	else
13028 #endif
13029 	if (tp->t_inpcb->inp_options)
13030 		ipoptlen = tp->t_inpcb->inp_options->m_len -
13031 		    offsetof(struct ipoption, ipopt_list);
13032 	else
13033 		ipoptlen = 0;
13034 	ipoptlen = 0;
13035 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
13036 	ipoptlen += ipsec_optlen;
13037 #endif
13038 	if (bbr->rc_last_options != local_options) {
13039 		/*
13040 		 * Cache the options length this generally does not change
13041 		 * on a connection. We use this to calculate TSO.
13042 		 */
13043 		bbr->rc_last_options = local_options;
13044 	}
13045 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
13046 	p_maxseg = min(maxseg, pace_max_segs);
13047 	/*
13048 	 * Adjust data length if insertion of options will bump the packet
13049 	 * length beyond the t_maxseg length. Clear the FIN bit because we
13050 	 * cut off the tail of the segment.
13051 	 */
13052 	if (len > maxseg) {
13053 		if (len != 0 && (flags & TH_FIN)) {
13054 			flags &= ~TH_FIN;
13055 		}
13056 		if (tso) {
13057 			uint32_t moff;
13058 			int32_t max_len;
13059 
13060 			/* extract TSO information */
13061 			if_hw_tsomax = tp->t_tsomax;
13062 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
13063 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
13064 			KASSERT(ipoptlen == 0,
13065 			    ("%s: TSO can't do IP options", __func__));
13066 
13067 			/*
13068 			 * Check if we should limit by maximum payload
13069 			 * length:
13070 			 */
13071 			if (if_hw_tsomax != 0) {
13072 				/* compute maximum TSO length */
13073 				max_len = (if_hw_tsomax - hdrlen -
13074 				    max_linkhdr);
13075 				if (max_len <= 0) {
13076 					len = 0;
13077 				} else if (len > max_len) {
13078 					len = max_len;
13079 				}
13080 			}
13081 			/*
13082 			 * Prevent the last segment from being fractional
13083 			 * unless the send sockbuf can be emptied:
13084 			 */
13085 			if ((sb_offset + len) < sbavail(sb)) {
13086 				moff = len % (uint32_t)maxseg;
13087 				if (moff != 0) {
13088 					len -= moff;
13089 				}
13090 			}
13091 			/*
13092 			 * In case there are too many small fragments don't
13093 			 * use TSO:
13094 			 */
13095 			if (len <= maxseg) {
13096 				len = maxseg;
13097 				tso = 0;
13098 			}
13099 		} else {
13100 			/* Not doing TSO */
13101 			if (optlen + ipoptlen >= tp->t_maxseg) {
13102 				/*
13103 				 * Since we don't have enough space to put
13104 				 * the IP header chain and the TCP header in
13105 				 * one packet as required by RFC 7112, don't
13106 				 * send it. Also ensure that at least one
13107 				 * byte of the payload can be put into the
13108 				 * TCP segment.
13109 				 */
13110 				SOCKBUF_UNLOCK(&so->so_snd);
13111 				error = EMSGSIZE;
13112 				sack_rxmit = 0;
13113 				goto out;
13114 			}
13115 			len = maxseg;
13116 		}
13117 	} else {
13118 		/* Not doing TSO */
13119 		if_hw_tsomaxsegcount = 0;
13120 		tso = 0;
13121 	}
13122 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13123 	    ("%s: len > IP_MAXPACKET", __func__));
13124 #ifdef DIAGNOSTIC
13125 #ifdef INET6
13126 	if (max_linkhdr + hdrlen > MCLBYTES)
13127 #else
13128 	if (max_linkhdr + hdrlen > MHLEN)
13129 #endif
13130 		panic("tcphdr too big");
13131 #endif
13132 	/*
13133 	 * This KASSERT is here to catch edge cases at a well defined place.
13134 	 * Before, those had triggered (random) panic conditions further
13135 	 * down.
13136 	 */
13137 #ifdef BBR_INVARIANTS
13138 	if (sack_rxmit) {
13139 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13140 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13141 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13142 		}
13143 	}
13144 #endif
13145 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13146 	if ((len == 0) &&
13147 	    (flags & TH_FIN) &&
13148 	    (sbused(sb))) {
13149 		/*
13150 		 * We have outstanding data, don't send a fin by itself!.
13151 		 */
13152 		slot = 0;
13153 		goto just_return;
13154 	}
13155 	/*
13156 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13157 	 * and initialize the header from the template for sends on this
13158 	 * connection.
13159 	 */
13160 	if (len) {
13161 		uint32_t moff;
13162 
13163 		/*
13164 		 * We place a limit on sending with hptsi.
13165 		 */
13166 		if ((rsm == NULL) && len > pace_max_segs)
13167 			len = pace_max_segs;
13168 		if (len <= maxseg)
13169 			tso = 0;
13170 #ifdef INET6
13171 		if (MHLEN < hdrlen + max_linkhdr)
13172 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13173 		else
13174 #endif
13175 			m = m_gethdr(M_NOWAIT, MT_DATA);
13176 
13177 		if (m == NULL) {
13178 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13179 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13180 			SOCKBUF_UNLOCK(sb);
13181 			error = ENOBUFS;
13182 			sack_rxmit = 0;
13183 			goto out;
13184 		}
13185 		m->m_data += max_linkhdr;
13186 		m->m_len = hdrlen;
13187 		/*
13188 		 * Start the m_copy functions from the closest mbuf to the
13189 		 * sb_offset in the socket buffer chain.
13190 		 */
13191 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13192 #ifdef BBR_INVARIANTS
13193 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13194 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13195 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13196 				    doing_retran_from,
13197 				    picked_up_retran,
13198 				    doing_tlp);
13199 
13200 #endif
13201 			/*
13202 			 * In this messed up situation we have two choices,
13203 			 * a) pretend the send worked, and just start timers
13204 			 * and what not (not good since that may lead us
13205 			 * back here a lot). <or> b) Send the lowest segment
13206 			 * in the map. <or> c) Drop the connection. Lets do
13207 			 * <b> which if it continues to happen will lead to
13208 			 * <c> via timeouts.
13209 			 */
13210 			BBR_STAT_INC(bbr_offset_recovery);
13211 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13212 			sb_offset = 0;
13213 			if (rsm == NULL) {
13214 				sack_rxmit = 0;
13215 				len = sbavail(sb);
13216 			} else {
13217 				sack_rxmit = 1;
13218 				if (rsm->r_start != tp->snd_una) {
13219 					/*
13220 					 * Things are really messed up, <c>
13221 					 * is the only thing to do.
13222 					 */
13223 					BBR_STAT_INC(bbr_offset_drop);
13224 					SOCKBUF_UNLOCK(sb);
13225 					(void)m_free(m);
13226 					return (-EFAULT); /* tcp_drop() */
13227 				}
13228 				len = rsm->r_end - rsm->r_start;
13229 			}
13230 			if (len > sbavail(sb))
13231 				len = sbavail(sb);
13232 			if (len > maxseg)
13233 				len = maxseg;
13234 		}
13235 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13236 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13237 			m_copydata(mb, moff, (int)len,
13238 			    mtod(m, caddr_t)+hdrlen);
13239 			if (rsm == NULL)
13240 				sbsndptr_adv(sb, mb, len);
13241 			m->m_len += len;
13242 		} else {
13243 			struct sockbuf *msb;
13244 
13245 			if (rsm)
13246 				msb = NULL;
13247 			else
13248 				msb = sb;
13249 #ifdef BBR_INVARIANTS
13250 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13251 				if (rsm) {
13252 					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 ",
13253 					    tp, bbr, len, moff,
13254 					    sbavail(sb), rsm,
13255 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13256 					    doing_retran_from,
13257 					    picked_up_retran,
13258 					    doing_tlp, sack_rxmit);
13259 				} else {
13260 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13261 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13262 				}
13263 			}
13264 #endif
13265 			m->m_next = tcp_m_copym(
13266 				mb, moff, &len,
13267 				if_hw_tsomaxsegcount,
13268 				if_hw_tsomaxsegsize, msb,
13269 				((rsm == NULL) ? hw_tls : 0)
13270 #ifdef NETFLIX_COPY_ARGS
13271 				, &filled_all
13272 #endif
13273 				);
13274 			if (len <= maxseg) {
13275 				/*
13276 				 * Must have ran out of mbufs for the copy
13277 				 * shorten it to no longer need tso. Lets
13278 				 * not put on sendalot since we are low on
13279 				 * mbufs.
13280 				 */
13281 				tso = 0;
13282 			}
13283 			if (m->m_next == NULL) {
13284 				SOCKBUF_UNLOCK(sb);
13285 				(void)m_free(m);
13286 				error = ENOBUFS;
13287 				sack_rxmit = 0;
13288 				goto out;
13289 			}
13290 		}
13291 #ifdef BBR_INVARIANTS
13292 		if (tso && len < maxseg) {
13293 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13294 			    tp, len, maxseg);
13295 		}
13296 		if (tso && if_hw_tsomaxsegcount) {
13297 			int32_t seg_cnt = 0;
13298 			struct mbuf *foo;
13299 
13300 			foo = m;
13301 			while (foo) {
13302 				seg_cnt++;
13303 				foo = foo->m_next;
13304 			}
13305 			if (seg_cnt > if_hw_tsomaxsegcount) {
13306 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13307 			}
13308 		}
13309 #endif
13310 		/*
13311 		 * If we're sending everything we've got, set PUSH. (This
13312 		 * will keep happy those implementations which only give
13313 		 * data to the user when a buffer fills or a PUSH comes in.)
13314 		 */
13315 		if (sb_offset + len == sbused(sb) &&
13316 		    sbused(sb) &&
13317 		    !(flags & TH_SYN)) {
13318 			flags |= TH_PUSH;
13319 		}
13320 		SOCKBUF_UNLOCK(sb);
13321 	} else {
13322 		SOCKBUF_UNLOCK(sb);
13323 		if (tp->t_flags & TF_ACKNOW)
13324 			KMOD_TCPSTAT_INC(tcps_sndacks);
13325 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13326 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13327 		else
13328 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13329 
13330 		m = m_gethdr(M_NOWAIT, MT_DATA);
13331 		if (m == NULL) {
13332 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13333 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13334 			error = ENOBUFS;
13335 			/* Fudge the send time since we could not send */
13336 			sack_rxmit = 0;
13337 			goto out;
13338 		}
13339 #ifdef INET6
13340 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13341 		    MHLEN >= hdrlen) {
13342 			M_ALIGN(m, hdrlen);
13343 		} else
13344 #endif
13345 			m->m_data += max_linkhdr;
13346 		m->m_len = hdrlen;
13347 	}
13348 	SOCKBUF_UNLOCK_ASSERT(sb);
13349 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13350 #ifdef MAC
13351 	mac_inpcb_create_mbuf(inp, m);
13352 #endif
13353 #ifdef INET6
13354 	if (isipv6) {
13355 		ip6 = mtod(m, struct ip6_hdr *);
13356 		if (tp->t_port) {
13357 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13358 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13359 			udp->uh_dport = tp->t_port;
13360 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13361 			udp->uh_ulen = htons(ulen);
13362 			th = (struct tcphdr *)(udp + 1);
13363 		} else {
13364 			th = (struct tcphdr *)(ip6 + 1);
13365 		}
13366 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13367 	} else
13368 #endif				/* INET6 */
13369 	{
13370 		ip = mtod(m, struct ip *);
13371 #ifdef TCPDEBUG
13372 		ipov = (struct ipovly *)ip;
13373 #endif
13374 		if (tp->t_port) {
13375 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13376 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13377 			udp->uh_dport = tp->t_port;
13378 			ulen = hdrlen + len - sizeof(struct ip);
13379 			udp->uh_ulen = htons(ulen);
13380 			th = (struct tcphdr *)(udp + 1);
13381 		} else {
13382 			th = (struct tcphdr *)(ip + 1);
13383 		}
13384 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13385 	}
13386 	/*
13387 	 * If we are doing retransmissions, then snd_nxt will not reflect
13388 	 * the first unsent octet.  For ACK only packets, we do not want the
13389 	 * sequence number of the retransmitted packet, we want the sequence
13390 	 * number of the next unsent octet.  So, if there is no data (and no
13391 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13392 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13393 	 * one byte beyond the right edge of the window, so use snd_nxt in
13394 	 * that case, since we know we aren't doing a retransmission.
13395 	 * (retransmit and persist are mutually exclusive...)
13396 	 */
13397 	if (sack_rxmit == 0) {
13398 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13399 			/* New data (including new persists) */
13400 			th->th_seq = htonl(tp->snd_max);
13401 			bbr_seq = tp->snd_max;
13402 		} else if (flags & TH_SYN) {
13403 			/* Syn's always send from iss */
13404 			th->th_seq = htonl(tp->iss);
13405 			bbr_seq = tp->iss;
13406 		} else if (flags & TH_FIN) {
13407 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13408 				/*
13409 				 * If we sent the fin already its 1 minus
13410 				 * snd_max
13411 				 */
13412 				th->th_seq = (htonl(tp->snd_max - 1));
13413 				bbr_seq = (tp->snd_max - 1);
13414 			} else {
13415 				/* First time FIN use snd_max */
13416 				th->th_seq = htonl(tp->snd_max);
13417 				bbr_seq = tp->snd_max;
13418 			}
13419 		} else {
13420 			/*
13421 			 * len == 0 and not persist we use snd_max, sending
13422 			 * an ack unless we have sent the fin then its 1
13423 			 * minus.
13424 			 */
13425 			/*
13426 			 * XXXRRS Question if we are in persists and we have
13427 			 * nothing outstanding to send and we have not sent
13428 			 * a FIN, we will send an ACK. In such a case it
13429 			 * might be better to send (tp->snd_una - 1) which
13430 			 * would force the peer to ack.
13431 			 */
13432 			if (tp->t_flags & TF_SENTFIN) {
13433 				th->th_seq = htonl(tp->snd_max - 1);
13434 				bbr_seq = (tp->snd_max - 1);
13435 			} else {
13436 				th->th_seq = htonl(tp->snd_max);
13437 				bbr_seq = tp->snd_max;
13438 			}
13439 		}
13440 	} else {
13441 		/* All retransmits use the rsm to guide the send */
13442 		th->th_seq = htonl(rsm->r_start);
13443 		bbr_seq = rsm->r_start;
13444 	}
13445 	th->th_ack = htonl(tp->rcv_nxt);
13446 	if (optlen) {
13447 		bcopy(opt, th + 1, optlen);
13448 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13449 	}
13450 	tcp_set_flags(th, flags);
13451 	/*
13452 	 * Calculate receive window.  Don't shrink window, but avoid silly
13453 	 * window syndrome.
13454 	 */
13455 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13456 				  recwin < maxseg)))
13457 		recwin = 0;
13458 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13459 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13460 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13461 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13462 		recwin = TCP_MAXWIN << tp->rcv_scale;
13463 
13464 	/*
13465 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13466 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13467 	 * handled in syncache.
13468 	 */
13469 	if (flags & TH_SYN)
13470 		th->th_win = htons((u_short)
13471 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13472 	else {
13473 		/* Avoid shrinking window with window scaling. */
13474 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13475 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13476 	}
13477 	/*
13478 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13479 	 * window.  This may cause the remote transmitter to stall.  This
13480 	 * flag tells soreceive() to disable delayed acknowledgements when
13481 	 * draining the buffer.  This can occur if the receiver is
13482 	 * attempting to read more data than can be buffered prior to
13483 	 * transmitting on the connection.
13484 	 */
13485 	if (th->th_win == 0) {
13486 		tp->t_sndzerowin++;
13487 		tp->t_flags |= TF_RXWIN0SENT;
13488 	} else
13489 		tp->t_flags &= ~TF_RXWIN0SENT;
13490 	/*
13491 	 * We don't support urgent data, but drag along
13492 	 * the pointer in case of a stack switch.
13493 	 */
13494 	tp->snd_up = tp->snd_una;
13495 
13496 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13497 	if (to.to_flags & TOF_SIGNATURE) {
13498 		/*
13499 		 * Calculate MD5 signature and put it into the place
13500 		 * determined before. NOTE: since TCP options buffer doesn't
13501 		 * point into mbuf's data, calculate offset and use it.
13502 		 */
13503 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13504 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13505 			/*
13506 			 * Do not send segment if the calculation of MD5
13507 			 * digest has failed.
13508 			 */
13509 			goto out;
13510 		}
13511 	}
13512 #endif
13513 
13514 	/*
13515 	 * Put TCP length in extended header, and then checksum extended
13516 	 * header and data.
13517 	 */
13518 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13519 #ifdef INET6
13520 	if (isipv6) {
13521 		/*
13522 		 * ip6_plen is not need to be filled now, and will be filled
13523 		 * in ip6_output.
13524 		 */
13525 		if (tp->t_port) {
13526 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13527 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13528 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13529 			th->th_sum = htons(0);
13530 			UDPSTAT_INC(udps_opackets);
13531 		} else {
13532 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13533 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13534 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13535 			    optlen + len, IPPROTO_TCP, 0);
13536 		}
13537 	}
13538 #endif
13539 #if defined(INET6) && defined(INET)
13540 	else
13541 #endif
13542 #ifdef INET
13543 	{
13544 		if (tp->t_port) {
13545 			m->m_pkthdr.csum_flags = CSUM_UDP;
13546 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13547 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13548 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13549 			th->th_sum = htons(0);
13550 			UDPSTAT_INC(udps_opackets);
13551 		} else {
13552 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13553 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13554 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13555 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13556 			    IPPROTO_TCP + len + optlen));
13557 		}
13558 		/* IP version must be set here for ipv4/ipv6 checking later */
13559 		KASSERT(ip->ip_v == IPVERSION,
13560 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13561 	}
13562 #endif
13563 
13564 	/*
13565 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13566 	 * header checksum is always provided. XXX: Fixme: This is currently
13567 	 * not the case for IPv6.
13568 	 */
13569 	if (tso) {
13570 		KASSERT(len > maxseg,
13571 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13572 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13573 		csum_flags |= CSUM_TSO;
13574 		m->m_pkthdr.tso_segsz = maxseg;
13575 	}
13576 	KASSERT(len + hdrlen == m_length(m, NULL),
13577 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13578 	    __func__, len, hdrlen, m_length(m, NULL)));
13579 
13580 #ifdef TCP_HHOOK
13581 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13582 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13583 #endif
13584 #ifdef TCPDEBUG
13585 	/*
13586 	 * Trace.
13587 	 */
13588 	if (so->so_options & SO_DEBUG) {
13589 		u_short save = 0;
13590 
13591 #ifdef INET6
13592 		if (!isipv6)
13593 #endif
13594 		{
13595 			save = ipov->ih_len;
13596 			ipov->ih_len = htons(m->m_pkthdr.len	/* - hdrlen +
13597 			      * (th->th_off << 2) */ );
13598 		}
13599 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13600 #ifdef INET6
13601 		if (!isipv6)
13602 #endif
13603 			ipov->ih_len = save;
13604 	}
13605 #endif				/* TCPDEBUG */
13606 
13607 	/* Log to the black box */
13608 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13609 		union tcp_log_stackspecific log;
13610 
13611 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13612 		/* Record info on type of transmission */
13613 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13614 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13615 		log.u_bbr.flex3 = maxseg;
13616 		log.u_bbr.flex4 = delay_calc;
13617 		/* Encode filled_all into the upper flex5 bit */
13618 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13619 		log.u_bbr.flex5 <<= 1;
13620 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13621 		log.u_bbr.flex5 <<= 29;
13622 		if (filled_all)
13623 			log.u_bbr.flex5 |= 0x80000000;
13624 		log.u_bbr.flex5 |= tp->t_maxseg;
13625 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13626 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13627 		/* lets poke in the low and the high here for debugging */
13628 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13629 		if (rsm || sack_rxmit) {
13630 			if (doing_tlp)
13631 				log.u_bbr.flex8 = 2;
13632 			else
13633 				log.u_bbr.flex8 = 1;
13634 		} else {
13635 			log.u_bbr.flex8 = 0;
13636 		}
13637 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13638 		    len, &log, false, NULL, NULL, 0, tv);
13639 	} else {
13640 		lgb = NULL;
13641 	}
13642 	/*
13643 	 * Fill in IP length and desired time to live and send to IP level.
13644 	 * There should be a better way to handle ttl and tos; we could keep
13645 	 * them in the template, but need a way to checksum without them.
13646 	 */
13647 	/*
13648 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13649 	 * because in6_cksum() need it.
13650 	 */
13651 #ifdef INET6
13652 	if (isipv6) {
13653 		/*
13654 		 * we separately set hoplimit for every segment, since the
13655 		 * user might want to change the value via setsockopt. Also,
13656 		 * desired default hop limit might be changed via Neighbor
13657 		 * Discovery.
13658 		 */
13659 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13660 
13661 		/*
13662 		 * Set the packet size here for the benefit of DTrace
13663 		 * probes. ip6_output() will set it properly; it's supposed
13664 		 * to include the option header lengths as well.
13665 		 */
13666 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13667 
13668 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13669 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13670 		else
13671 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13672 
13673 		if (tp->t_state == TCPS_SYN_SENT)
13674 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13675 
13676 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13677 		/* TODO: IPv6 IP6TOS_ECT bit on */
13678 		error = ip6_output(m, inp->in6p_outputopts,
13679 		    &inp->inp_route6,
13680 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13681 		    NULL, NULL, inp);
13682 
13683 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13684 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13685 	}
13686 #endif				/* INET6 */
13687 #if defined(INET) && defined(INET6)
13688 	else
13689 #endif
13690 #ifdef INET
13691 	{
13692 		ip->ip_len = htons(m->m_pkthdr.len);
13693 #ifdef INET6
13694 		if (isipv6)
13695 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13696 #endif				/* INET6 */
13697 		/*
13698 		 * If we do path MTU discovery, then we set DF on every
13699 		 * packet. This might not be the best thing to do according
13700 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13701 		 * the problem so it affects only the first tcp connection
13702 		 * with a host.
13703 		 *
13704 		 * NB: Don't set DF on small MTU/MSS to have a safe
13705 		 * fallback.
13706 		 */
13707 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13708 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13709 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13710 				ip->ip_off |= htons(IP_DF);
13711 			}
13712 		} else {
13713 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13714 		}
13715 
13716 		if (tp->t_state == TCPS_SYN_SENT)
13717 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13718 
13719 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13720 
13721 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13722 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13723 		    inp);
13724 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13725 			mtu = inp->inp_route.ro_nh->nh_mtu;
13726 	}
13727 #endif				/* INET */
13728 out:
13729 
13730 	if (lgb) {
13731 		lgb->tlb_errno = error;
13732 		lgb = NULL;
13733 	}
13734 	/*
13735 	 * In transmit state, time the transmission and arrange for the
13736 	 * retransmit.  In persist state, just set snd_max.
13737 	 */
13738 	if (error == 0) {
13739 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13740 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13741 		    (tp->t_flags & TF_SACK_PERMIT) &&
13742 		    tp->rcv_numsacks > 0)
13743 			tcp_clean_dsack_blocks(tp);
13744 		/* We sent an ack clear the bbr_segs_rcvd count */
13745 		bbr->output_error_seen = 0;
13746 		bbr->oerror_cnt = 0;
13747 		bbr->bbr_segs_rcvd = 0;
13748 		if (len == 0)
13749 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13750 		/* Do accounting for new sends */
13751 		if ((len > 0) && (rsm == NULL)) {
13752 			int idx;
13753 			if (tp->snd_una == tp->snd_max) {
13754 				/*
13755 				 * Special case to match google, when
13756 				 * nothing is in flight the delivered
13757 				 * time does get updated to the current
13758 				 * time (see tcp_rate_bsd.c).
13759 				 */
13760 				bbr->r_ctl.rc_del_time = cts;
13761 			}
13762 			if (len >= maxseg) {
13763 				idx = (len / maxseg) + 3;
13764 				if (idx >= TCP_MSS_ACCT_ATIMER)
13765 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13766 				else
13767 					counter_u64_add(bbr_out_size[idx], 1);
13768 			} else {
13769 				/* smaller than a MSS */
13770 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13771 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13772 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13773 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13774 			}
13775 		}
13776 	}
13777 	abandon = 0;
13778 	/*
13779 	 * We must do the send accounting before we log the output,
13780 	 * otherwise the state of the rsm could change and we account to the
13781 	 * wrong bucket.
13782 	 */
13783 	if (len > 0) {
13784 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13785 		if (error == 0) {
13786 			if (tp->snd_una == tp->snd_max)
13787 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13788 		}
13789 	}
13790 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13791 	    cts, mb, &abandon, rsm, 0, sb);
13792 	if (abandon) {
13793 		/*
13794 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13795 		 * sent we should hit this condition.
13796 		 */
13797 		return (0);
13798 	}
13799 	if (bbr->rc_in_persist == 0) {
13800 		/*
13801 		 * Advance snd_nxt over sequence space of this segment.
13802 		 */
13803 		if (error)
13804 			/* We don't log or do anything with errors */
13805 			goto skip_upd;
13806 
13807 		if (tp->snd_una == tp->snd_max &&
13808 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13809 			/*
13810 			 * Update the time we just added data since none was
13811 			 * outstanding.
13812 			 */
13813 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13814 			bbr->rc_tp->t_acktime  = ticks;
13815 		}
13816 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13817 			if (flags & TH_SYN) {
13818 				/*
13819 				 * Smack the snd_max to iss + 1
13820 				 * if its a FO we will add len below.
13821 				 */
13822 				tp->snd_max = tp->iss + 1;
13823 			}
13824 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13825 				tp->snd_max++;
13826 				tp->t_flags |= TF_SENTFIN;
13827 			}
13828 		}
13829 		if (sack_rxmit == 0)
13830 			tp->snd_max += len;
13831 skip_upd:
13832 		if ((error == 0) && len)
13833 			tot_len += len;
13834 	} else {
13835 		/* Persists case */
13836 		int32_t xlen = len;
13837 
13838 		if (error)
13839 			goto nomore;
13840 
13841 		if (flags & TH_SYN)
13842 			++xlen;
13843 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13844 			++xlen;
13845 			tp->t_flags |= TF_SENTFIN;
13846 		}
13847 		if (xlen && (tp->snd_una == tp->snd_max)) {
13848 			/*
13849 			 * Update the time we just added data since none was
13850 			 * outstanding.
13851 			 */
13852 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13853 			bbr->rc_tp->t_acktime = ticks;
13854 		}
13855 		if (sack_rxmit == 0)
13856 			tp->snd_max += xlen;
13857 		tot_len += (len + optlen + ipoptlen);
13858 	}
13859 nomore:
13860 	if (error) {
13861 		/*
13862 		 * Failures do not advance the seq counter above. For the
13863 		 * case of ENOBUFS we will fall out and become ack-clocked.
13864 		 * capping the cwnd at the current flight.
13865 		 * Everything else will just have to retransmit with the timer
13866 		 * (no pacer).
13867 		 */
13868 		SOCKBUF_UNLOCK_ASSERT(sb);
13869 		BBR_STAT_INC(bbr_saw_oerr);
13870 		/* Clear all delay/early tracks */
13871 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13872 		bbr->r_ctl.rc_agg_early = 0;
13873 		bbr->r_agg_early_set = 0;
13874 		bbr->output_error_seen = 1;
13875 		if (bbr->oerror_cnt < 0xf)
13876 			bbr->oerror_cnt++;
13877 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13878 			/* drop the session */
13879 			return (-ENETDOWN);
13880 		}
13881 		switch (error) {
13882 		case ENOBUFS:
13883 			/*
13884 			 * Make this guy have to get ack's to send
13885 			 * more but lets make sure we don't
13886 			 * slam him below a T-O (1MSS).
13887 			 */
13888 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13889 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13890 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13891 				if (tp->snd_cwnd < maxseg)
13892 					tp->snd_cwnd = maxseg;
13893 			}
13894 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13895 			BBR_STAT_INC(bbr_saw_enobuf);
13896 			if (bbr->bbr_hdrw_pacing)
13897 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13898 			else
13899 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13900 			/*
13901 			 * Here even in the enobuf's case we want to do our
13902 			 * state update. The reason being we may have been
13903 			 * called by the input function. If so we have had
13904 			 * things change.
13905 			 */
13906 			error = 0;
13907 			goto enobufs;
13908 		case EMSGSIZE:
13909 			/*
13910 			 * For some reason the interface we used initially
13911 			 * to send segments changed to another or lowered
13912 			 * its MTU. If TSO was active we either got an
13913 			 * interface without TSO capabilits or TSO was
13914 			 * turned off. If we obtained mtu from ip_output()
13915 			 * then update it and try again.
13916 			 */
13917 			/* Turn on tracing (or try to) */
13918 			{
13919 				int old_maxseg;
13920 
13921 				old_maxseg = tp->t_maxseg;
13922 				BBR_STAT_INC(bbr_saw_emsgsiz);
13923 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13924 				if (mtu != 0)
13925 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13926 				if (old_maxseg <= tp->t_maxseg) {
13927 					/* Huh it did not shrink? */
13928 					tp->t_maxseg = old_maxseg - 40;
13929 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13930 				}
13931 				/*
13932 				 * Nuke all other things that can interfere
13933 				 * with slot
13934 				 */
13935 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13936 					slot = bbr_get_pacing_delay(bbr,
13937 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13938 					    (tot_len + len), cts, 0);
13939 					if (slot < bbr_error_base_paceout)
13940 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13941 				} else
13942 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13943 				bbr->rc_output_starts_timer = 1;
13944 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13945 				    tot_len);
13946 				return (error);
13947 			}
13948 		case EPERM:
13949 			tp->t_softerror = error;
13950 			/* Fall through */
13951 		case EHOSTDOWN:
13952 		case EHOSTUNREACH:
13953 		case ENETDOWN:
13954 		case ENETUNREACH:
13955 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13956 				tp->t_softerror = error;
13957 			}
13958 			/* FALLTHROUGH */
13959 		default:
13960 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13961 			bbr->rc_output_starts_timer = 1;
13962 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13963 			return (error);
13964 		}
13965 #ifdef STATS
13966 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13967 		    len &&
13968 		    (rsm == NULL) &&
13969 	    (bbr->rc_in_persist == 0)) {
13970 		tp->gput_seq = bbr_seq;
13971 		tp->gput_ack = bbr_seq +
13972 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13973 		tp->gput_ts = cts;
13974 		tp->t_flags |= TF_GPUTINPROG;
13975 #endif
13976 	}
13977 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13978 	if ((bbr->bbr_hdw_pace_ena) &&
13979 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13980 	    (bbr->rc_past_init_win) &&
13981 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13982 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13983 	    (inp->inp_route.ro_nh &&
13984 	     inp->inp_route.ro_nh->nh_ifp)) {
13985 		/*
13986 		 * We are past the initial window and
13987 		 * have at least one measurement so we
13988 		 * could use hardware pacing if its available.
13989 		 * We have an interface and we have not attempted
13990 		 * to setup hardware pacing, lets try to now.
13991 		 */
13992 		uint64_t rate_wanted;
13993 		int err = 0;
13994 
13995 		rate_wanted = bbr_get_hardware_rate(bbr);
13996 		bbr->bbr_attempt_hdwr_pace = 1;
13997 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13998 						      inp->inp_route.ro_nh->nh_ifp,
13999 						      rate_wanted,
14000 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
14001 						      &err, NULL);
14002 		if (bbr->r_ctl.crte) {
14003 			bbr_type_log_hdwr_pacing(bbr,
14004 						 bbr->r_ctl.crte->ptbl->rs_ifp,
14005 						 rate_wanted,
14006 						 bbr->r_ctl.crte->rate,
14007 						 __LINE__, cts, err);
14008 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
14009 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
14010 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
14011 			bbr->bbr_hdrw_pacing = 1;
14012 			/* Now what is our gain status? */
14013 			if (bbr->r_ctl.crte->rate < rate_wanted) {
14014 				/* We have a problem */
14015 				bbr_setup_less_of_rate(bbr, cts,
14016 						       bbr->r_ctl.crte->rate, rate_wanted);
14017 			} else {
14018 				/* We are good */
14019 				bbr->gain_is_limited = 0;
14020 				bbr->skip_gain = 0;
14021 			}
14022 			tcp_bbr_tso_size_check(bbr, cts);
14023 		} else {
14024 			bbr_type_log_hdwr_pacing(bbr,
14025 						 inp->inp_route.ro_nh->nh_ifp,
14026 						 rate_wanted,
14027 						 0,
14028 						 __LINE__, cts, err);
14029 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
14030 		}
14031 	}
14032 	if (bbr->bbr_hdrw_pacing) {
14033 		/*
14034 		 * Worry about cases where the route
14035 		 * changes or something happened that we
14036 		 * lost our hardware pacing possibly during
14037 		 * the last ip_output call.
14038 		 */
14039 		if (inp->inp_snd_tag == NULL) {
14040 			/* A change during ip output disabled hw pacing? */
14041 			bbr->bbr_hdrw_pacing = 0;
14042 		} else if ((inp->inp_route.ro_nh == NULL) ||
14043 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
14044 			/*
14045 			 * We had an interface or route change,
14046 			 * detach from the current hdwr pacing
14047 			 * and setup to re-attempt next go
14048 			 * round.
14049 			 */
14050 			bbr->bbr_hdrw_pacing = 0;
14051 			bbr->bbr_attempt_hdwr_pace = 0;
14052 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
14053 			tcp_bbr_tso_size_check(bbr, cts);
14054 		}
14055 	}
14056 	/*
14057 	 * Data sent (as far as we can tell). If this advertises a larger
14058 	 * window than any other segment, then remember the size of the
14059 	 * advertised window. Any pending ACK has now been sent.
14060 	 */
14061 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
14062 		tp->rcv_adv = tp->rcv_nxt + recwin;
14063 
14064 	tp->last_ack_sent = tp->rcv_nxt;
14065 	if ((error == 0) &&
14066 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
14067 	    (doing_tlp == 0) &&
14068 	    (tso == 0) &&
14069 	    (len > 0) &&
14070 	    ((flags & TH_RST) == 0) &&
14071 	    ((flags & TH_SYN) == 0) &&
14072 	    (IN_RECOVERY(tp->t_flags) == 0) &&
14073 	    (bbr->rc_in_persist == 0) &&
14074 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
14075 		/*
14076 		 * For non-tso we need to goto again until we have sent out
14077 		 * enough data to match what we are hptsi out every hptsi
14078 		 * interval.
14079 		 */
14080 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14081 			/* Make sure snd_nxt is drug up */
14082 			tp->snd_nxt = tp->snd_max;
14083 		}
14084 		if (rsm != NULL) {
14085 			rsm = NULL;
14086 			goto skip_again;
14087 		}
14088 		rsm = NULL;
14089 		sack_rxmit = 0;
14090 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14091 		goto again;
14092 	}
14093 skip_again:
14094 	if ((error == 0) && (flags & TH_FIN))
14095 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
14096 	if ((error == 0) && (flags & TH_RST))
14097 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
14098 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14099 		/*
14100 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
14101 		 * what we have sent so far
14102 		 */
14103 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14104 		if (bbr->rc_no_pacing)
14105 			slot = 0;
14106 	}
14107 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14108 enobufs:
14109 	if (bbr->rc_use_google == 0)
14110 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14111 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14112 							bbr->r_ctl.rc_lost_bytes)));
14113 	bbr->rc_output_starts_timer = 1;
14114 	if (bbr->bbr_use_rack_cheat &&
14115 	    (more_to_rxt ||
14116 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14117 		/* Rack cheats and shotguns out all rxt's 1ms apart */
14118 		if (slot > 1000)
14119 			slot = 1000;
14120 	}
14121 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14122 		/*
14123 		 * We don't change the tso size until some number of sends
14124 		 * to give the hardware commands time to get down
14125 		 * to the interface.
14126 		 */
14127 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14128 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14129 			bbr->hw_pacing_set = 1;
14130 			tcp_bbr_tso_size_check(bbr, cts);
14131 		}
14132 	}
14133 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14134 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14135 		/* Make sure snd_nxt is drug up */
14136 		tp->snd_nxt = tp->snd_max;
14137 	}
14138 	return (error);
14139 
14140 }
14141 
14142 /*
14143  * See bbr_output_wtime() for return values.
14144  */
14145 static int
14146 bbr_output(struct tcpcb *tp)
14147 {
14148 	int32_t ret;
14149 	struct timeval tv;
14150 
14151 	NET_EPOCH_ASSERT();
14152 
14153 	INP_WLOCK_ASSERT(tp->t_inpcb);
14154 	(void)tcp_get_usecs(&tv);
14155 	ret = bbr_output_wtime(tp, &tv);
14156 	return (ret);
14157 }
14158 
14159 static void
14160 bbr_mtu_chg(struct tcpcb *tp)
14161 {
14162 	struct tcp_bbr *bbr;
14163 	struct bbr_sendmap *rsm, *frsm = NULL;
14164 	uint32_t maxseg;
14165 
14166 	/*
14167 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14168 	 * over the current size as SACK_PASS so a retransmit will occur.
14169 	 */
14170 
14171 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14172 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14173 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14174 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14175 		/* Don't mess with ones acked (by sack?) */
14176 		if (rsm->r_flags & BBR_ACKED)
14177 			continue;
14178 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14179 			/*
14180 			 * We mark sack-passed on all the previous large
14181 			 * sends we did. This will force them to retransmit.
14182 			 */
14183 			rsm->r_flags |= BBR_SACK_PASSED;
14184 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14185 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14186 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14187 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14188 				rsm->r_flags |= BBR_MARKED_LOST;
14189 			}
14190 			if (frsm == NULL)
14191 				frsm = rsm;
14192 		}
14193 	}
14194 	if (frsm) {
14195 		bbr->r_ctl.rc_resend = frsm;
14196 	}
14197 }
14198 
14199 static int
14200 bbr_pru_options(struct tcpcb *tp, int flags)
14201 {
14202 	if (flags & PRUS_OOB)
14203 		return (EOPNOTSUPP);
14204 	return (0);
14205 }
14206 
14207 struct tcp_function_block __tcp_bbr = {
14208 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14209 	.tfb_tcp_output = bbr_output,
14210 	.tfb_do_queued_segments = ctf_do_queued_segments,
14211 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14212 	.tfb_tcp_do_segment = bbr_do_segment,
14213 	.tfb_tcp_ctloutput = bbr_ctloutput,
14214 	.tfb_tcp_fb_init = bbr_init,
14215 	.tfb_tcp_fb_fini = bbr_fini,
14216 	.tfb_tcp_timer_stop_all = bbr_stopall,
14217 	.tfb_tcp_timer_activate = bbr_timer_activate,
14218 	.tfb_tcp_timer_active = bbr_timer_active,
14219 	.tfb_tcp_timer_stop = bbr_timer_stop,
14220 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14221 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14222 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14223 	.tfb_pru_options = bbr_pru_options,
14224 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14225 };
14226 
14227 /*
14228  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14229  * socket option arguments.  When it re-acquires the lock after the copy, it
14230  * has to revalidate that the connection is still valid for the socket
14231  * option.
14232  */
14233 static int
14234 bbr_set_sockopt(struct inpcb *inp, struct sockopt *sopt)
14235 {
14236 	struct epoch_tracker et;
14237 	struct tcpcb *tp;
14238 	struct tcp_bbr *bbr;
14239 	int32_t error = 0, optval;
14240 
14241 	switch (sopt->sopt_level) {
14242 	case IPPROTO_IPV6:
14243 	case IPPROTO_IP:
14244 		return (tcp_default_ctloutput(inp, sopt));
14245 	}
14246 
14247 	switch (sopt->sopt_name) {
14248 	case TCP_RACK_PACE_MAX_SEG:
14249 	case TCP_RACK_MIN_TO:
14250 	case TCP_RACK_REORD_THRESH:
14251 	case TCP_RACK_REORD_FADE:
14252 	case TCP_RACK_TLP_THRESH:
14253 	case TCP_RACK_PKT_DELAY:
14254 	case TCP_BBR_ALGORITHM:
14255 	case TCP_BBR_TSLIMITS:
14256 	case TCP_BBR_IWINTSO:
14257 	case TCP_BBR_RECFORCE:
14258 	case TCP_BBR_STARTUP_PG:
14259 	case TCP_BBR_DRAIN_PG:
14260 	case TCP_BBR_RWND_IS_APP:
14261 	case TCP_BBR_PROBE_RTT_INT:
14262 	case TCP_BBR_PROBE_RTT_GAIN:
14263 	case TCP_BBR_PROBE_RTT_LEN:
14264 	case TCP_BBR_STARTUP_LOSS_EXIT:
14265 	case TCP_BBR_USEDEL_RATE:
14266 	case TCP_BBR_MIN_RTO:
14267 	case TCP_BBR_MAX_RTO:
14268 	case TCP_BBR_PACE_PER_SEC:
14269 	case TCP_DELACK:
14270 	case TCP_BBR_PACE_DEL_TAR:
14271 	case TCP_BBR_SEND_IWND_IN_TSO:
14272 	case TCP_BBR_EXTRA_STATE:
14273 	case TCP_BBR_UTTER_MAX_TSO:
14274 	case TCP_BBR_MIN_TOPACEOUT:
14275 	case TCP_BBR_FLOOR_MIN_TSO:
14276 	case TCP_BBR_TSTMP_RAISES:
14277 	case TCP_BBR_POLICER_DETECT:
14278 	case TCP_BBR_USE_RACK_CHEAT:
14279 	case TCP_DATA_AFTER_CLOSE:
14280 	case TCP_BBR_HDWR_PACE:
14281 	case TCP_BBR_PACE_SEG_MAX:
14282 	case TCP_BBR_PACE_SEG_MIN:
14283 	case TCP_BBR_PACE_CROSS:
14284 	case TCP_BBR_PACE_OH:
14285 #ifdef NETFLIX_PEAKRATE
14286 	case TCP_MAXPEAKRATE:
14287 #endif
14288 	case TCP_BBR_TMR_PACE_OH:
14289 	case TCP_BBR_RACK_RTT_USE:
14290 	case TCP_BBR_RETRAN_WTSO:
14291 		break;
14292 	default:
14293 		return (tcp_default_ctloutput(inp, sopt));
14294 		break;
14295 	}
14296 	INP_WUNLOCK(inp);
14297 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14298 	if (error)
14299 		return (error);
14300 	INP_WLOCK(inp);
14301 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
14302 		INP_WUNLOCK(inp);
14303 		return (ECONNRESET);
14304 	}
14305 	tp = intotcpcb(inp);
14306 	if (tp->t_fb != &__tcp_bbr) {
14307 		INP_WUNLOCK(inp);
14308 		return (ENOPROTOOPT);
14309 	}
14310 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14311 	switch (sopt->sopt_name) {
14312 	case TCP_BBR_PACE_PER_SEC:
14313 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14314 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14315 		break;
14316 	case TCP_BBR_PACE_DEL_TAR:
14317 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14318 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14319 		break;
14320 	case TCP_BBR_PACE_SEG_MAX:
14321 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14322 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14323 		break;
14324 	case TCP_BBR_PACE_SEG_MIN:
14325 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14326 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14327 		break;
14328 	case TCP_BBR_PACE_CROSS:
14329 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14330 		bbr->r_ctl.bbr_cross_over = optval;
14331 		break;
14332 	case TCP_BBR_ALGORITHM:
14333 		BBR_OPTS_INC(tcp_bbr_algorithm);
14334 		if (optval && (bbr->rc_use_google == 0)) {
14335 			/* Turn on the google mode */
14336 			bbr_google_mode_on(bbr);
14337 			if ((optval > 3) && (optval < 500)) {
14338 				/*
14339 				 * Must be at least greater than .3%
14340 				 * and must be less than 50.0%.
14341 				 */
14342 				bbr->r_ctl.bbr_google_discount = optval;
14343 			}
14344 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14345 			/* Turn off the google mode */
14346 			bbr_google_mode_off(bbr);
14347 		}
14348 		break;
14349 	case TCP_BBR_TSLIMITS:
14350 		BBR_OPTS_INC(tcp_bbr_tslimits);
14351 		if (optval == 1)
14352 			bbr->rc_use_ts_limit = 1;
14353 		else if (optval == 0)
14354 			bbr->rc_use_ts_limit = 0;
14355 		else
14356 			error = EINVAL;
14357 		break;
14358 
14359 	case TCP_BBR_IWINTSO:
14360 		BBR_OPTS_INC(tcp_bbr_iwintso);
14361 		if ((optval >= 0) && (optval < 128)) {
14362 			uint32_t twin;
14363 
14364 			bbr->rc_init_win = optval;
14365 			twin = bbr_initial_cwnd(bbr, tp);
14366 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14367 				tp->snd_cwnd = twin;
14368 			else
14369 				error = EBUSY;
14370 		} else
14371 			error = EINVAL;
14372 		break;
14373 	case TCP_BBR_STARTUP_PG:
14374 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14375 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14376 			bbr->r_ctl.rc_startup_pg = optval;
14377 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14378 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14379 			}
14380 		} else
14381 			error = EINVAL;
14382 		break;
14383 	case TCP_BBR_DRAIN_PG:
14384 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14385 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14386 			bbr->r_ctl.rc_drain_pg = optval;
14387 		else
14388 			error = EINVAL;
14389 		break;
14390 	case TCP_BBR_PROBE_RTT_LEN:
14391 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14392 		if (optval <= 1)
14393 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14394 		else
14395 			error = EINVAL;
14396 		break;
14397 	case TCP_BBR_PROBE_RTT_GAIN:
14398 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14399 		if (optval <= BBR_UNIT)
14400 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14401 		else
14402 			error = EINVAL;
14403 		break;
14404 	case TCP_BBR_PROBE_RTT_INT:
14405 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14406 		if (optval > 1000)
14407 			bbr->r_ctl.rc_probertt_int = optval;
14408 		else
14409 			error = EINVAL;
14410 		break;
14411 	case TCP_BBR_MIN_TOPACEOUT:
14412 		BBR_OPTS_INC(tcp_bbr_topaceout);
14413 		if (optval == 0) {
14414 			bbr->no_pacing_until = 0;
14415 			bbr->rc_no_pacing = 0;
14416 		} else if (optval <= 0x00ff) {
14417 			bbr->no_pacing_until = optval;
14418 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14419 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14420 				/* Turn on no pacing */
14421 				bbr->rc_no_pacing = 1;
14422 			}
14423 		} else
14424 			error = EINVAL;
14425 		break;
14426 	case TCP_BBR_STARTUP_LOSS_EXIT:
14427 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14428 		bbr->rc_loss_exit = optval;
14429 		break;
14430 	case TCP_BBR_USEDEL_RATE:
14431 		error = EINVAL;
14432 		break;
14433 	case TCP_BBR_MIN_RTO:
14434 		BBR_OPTS_INC(tcp_bbr_min_rto);
14435 		bbr->r_ctl.rc_min_rto_ms = optval;
14436 		break;
14437 	case TCP_BBR_MAX_RTO:
14438 		BBR_OPTS_INC(tcp_bbr_max_rto);
14439 		bbr->rc_max_rto_sec = optval;
14440 		break;
14441 	case TCP_RACK_MIN_TO:
14442 		/* Minimum time between rack t-o's in ms */
14443 		BBR_OPTS_INC(tcp_rack_min_to);
14444 		bbr->r_ctl.rc_min_to = optval;
14445 		break;
14446 	case TCP_RACK_REORD_THRESH:
14447 		/* RACK reorder threshold (shift amount) */
14448 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14449 		if ((optval > 0) && (optval < 31))
14450 			bbr->r_ctl.rc_reorder_shift = optval;
14451 		else
14452 			error = EINVAL;
14453 		break;
14454 	case TCP_RACK_REORD_FADE:
14455 		/* Does reordering fade after ms time */
14456 		BBR_OPTS_INC(tcp_rack_reord_fade);
14457 		bbr->r_ctl.rc_reorder_fade = optval;
14458 		break;
14459 	case TCP_RACK_TLP_THRESH:
14460 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14461 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14462 		if (optval)
14463 			bbr->rc_tlp_threshold = optval;
14464 		else
14465 			error = EINVAL;
14466 		break;
14467 	case TCP_BBR_USE_RACK_CHEAT:
14468 		BBR_OPTS_INC(tcp_use_rackcheat);
14469 		if (bbr->rc_use_google) {
14470 			error = EINVAL;
14471 			break;
14472 		}
14473 		BBR_OPTS_INC(tcp_rack_cheat);
14474 		if (optval)
14475 			bbr->bbr_use_rack_cheat = 1;
14476 		else
14477 			bbr->bbr_use_rack_cheat = 0;
14478 		break;
14479 	case TCP_BBR_FLOOR_MIN_TSO:
14480 		BBR_OPTS_INC(tcp_utter_max_tso);
14481 		if ((optval >= 0) && (optval < 40))
14482 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14483 		else
14484 			error = EINVAL;
14485 		break;
14486 	case TCP_BBR_UTTER_MAX_TSO:
14487 		BBR_OPTS_INC(tcp_utter_max_tso);
14488 		if ((optval >= 0) && (optval < 0xffff))
14489 			bbr->r_ctl.bbr_utter_max = optval;
14490 		else
14491 			error = EINVAL;
14492 		break;
14493 
14494 	case TCP_BBR_EXTRA_STATE:
14495 		BBR_OPTS_INC(tcp_extra_state);
14496 		if (optval)
14497 			bbr->rc_use_idle_restart = 1;
14498 		else
14499 			bbr->rc_use_idle_restart = 0;
14500 		break;
14501 	case TCP_BBR_SEND_IWND_IN_TSO:
14502 		BBR_OPTS_INC(tcp_iwnd_tso);
14503 		if (optval) {
14504 			bbr->bbr_init_win_cheat = 1;
14505 			if (bbr->rc_past_init_win == 0) {
14506 				uint32_t cts;
14507 				cts = tcp_get_usecs(&bbr->rc_tv);
14508 				tcp_bbr_tso_size_check(bbr, cts);
14509 			}
14510 		} else
14511 			bbr->bbr_init_win_cheat = 0;
14512 		break;
14513 	case TCP_BBR_HDWR_PACE:
14514 		BBR_OPTS_INC(tcp_hdwr_pacing);
14515 		if (optval){
14516 			bbr->bbr_hdw_pace_ena = 1;
14517 			bbr->bbr_attempt_hdwr_pace = 0;
14518 		} else {
14519 			bbr->bbr_hdw_pace_ena = 0;
14520 #ifdef RATELIMIT
14521 			if (bbr->r_ctl.crte != NULL) {
14522 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14523 				bbr->r_ctl.crte = NULL;
14524 			}
14525 #endif
14526 		}
14527 		break;
14528 
14529 	case TCP_DELACK:
14530 		BBR_OPTS_INC(tcp_delack);
14531 		if (optval < 100) {
14532 			if (optval == 0) /* off */
14533 				tp->t_delayed_ack = 0;
14534 			else if (optval == 1) /* on which is 2 */
14535 				tp->t_delayed_ack = 2;
14536 			else /* higher than 2 and less than 100 */
14537 				tp->t_delayed_ack = optval;
14538 			if (tp->t_flags & TF_DELACK) {
14539 				tp->t_flags &= ~TF_DELACK;
14540 				tp->t_flags |= TF_ACKNOW;
14541 				NET_EPOCH_ENTER(et);
14542 				bbr_output(tp);
14543 				NET_EPOCH_EXIT(et);
14544 			}
14545 		} else
14546 			error = EINVAL;
14547 		break;
14548 	case TCP_RACK_PKT_DELAY:
14549 		/* RACK added ms i.e. rack-rtt + reord + N */
14550 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14551 		bbr->r_ctl.rc_pkt_delay = optval;
14552 		break;
14553 #ifdef NETFLIX_PEAKRATE
14554 	case TCP_MAXPEAKRATE:
14555 		BBR_OPTS_INC(tcp_maxpeak);
14556 		error = tcp_set_maxpeakrate(tp, optval);
14557 		if (!error)
14558 			tp->t_peakrate_thr = tp->t_maxpeakrate;
14559 		break;
14560 #endif
14561 	case TCP_BBR_RETRAN_WTSO:
14562 		BBR_OPTS_INC(tcp_retran_wtso);
14563 		if (optval)
14564 			bbr->rc_resends_use_tso = 1;
14565 		else
14566 			bbr->rc_resends_use_tso = 0;
14567 		break;
14568 	case TCP_DATA_AFTER_CLOSE:
14569 		BBR_OPTS_INC(tcp_data_ac);
14570 		if (optval)
14571 			bbr->rc_allow_data_af_clo = 1;
14572 		else
14573 			bbr->rc_allow_data_af_clo = 0;
14574 		break;
14575 	case TCP_BBR_POLICER_DETECT:
14576 		BBR_OPTS_INC(tcp_policer_det);
14577 		if (bbr->rc_use_google == 0)
14578 			error = EINVAL;
14579 		else if (optval)
14580 			bbr->r_use_policer = 1;
14581 		else
14582 			bbr->r_use_policer = 0;
14583 		break;
14584 
14585 	case TCP_BBR_TSTMP_RAISES:
14586 		BBR_OPTS_INC(tcp_ts_raises);
14587 		if (optval)
14588 			bbr->ts_can_raise = 1;
14589 		else
14590 			bbr->ts_can_raise = 0;
14591 		break;
14592 	case TCP_BBR_TMR_PACE_OH:
14593 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14594 		if (bbr->rc_use_google) {
14595 			error = EINVAL;
14596 		} else {
14597 			if (optval)
14598 				bbr->r_ctl.rc_incr_tmrs = 1;
14599 			else
14600 				bbr->r_ctl.rc_incr_tmrs = 0;
14601 		}
14602 		break;
14603 	case TCP_BBR_PACE_OH:
14604 		BBR_OPTS_INC(tcp_pacing_oh);
14605 		if (bbr->rc_use_google) {
14606 			error = EINVAL;
14607 		} else {
14608 			if (optval > (BBR_INCL_TCP_OH|
14609 				      BBR_INCL_IP_OH|
14610 				      BBR_INCL_ENET_OH)) {
14611 				error = EINVAL;
14612 				break;
14613 			}
14614 			if (optval & BBR_INCL_TCP_OH)
14615 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14616 			else
14617 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14618 			if (optval & BBR_INCL_IP_OH)
14619 				bbr->r_ctl.rc_inc_ip_oh = 1;
14620 			else
14621 				bbr->r_ctl.rc_inc_ip_oh = 0;
14622 			if (optval & BBR_INCL_ENET_OH)
14623 				bbr->r_ctl.rc_inc_enet_oh = 1;
14624 			else
14625 				bbr->r_ctl.rc_inc_enet_oh = 0;
14626 		}
14627 		break;
14628 	default:
14629 		return (tcp_default_ctloutput(inp, sopt));
14630 		break;
14631 	}
14632 #ifdef NETFLIX_STATS
14633 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14634 #endif
14635 	INP_WUNLOCK(inp);
14636 	return (error);
14637 }
14638 
14639 /*
14640  * return 0 on success, error-num on failure
14641  */
14642 static int
14643 bbr_get_sockopt(struct inpcb *inp, struct sockopt *sopt)
14644 {
14645 	struct tcpcb *tp;
14646 	struct tcp_bbr *bbr;
14647 	int32_t error, optval;
14648 
14649 	tp = intotcpcb(inp);
14650 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14651 	if (bbr == NULL) {
14652 		INP_WUNLOCK(inp);
14653 		return (EINVAL);
14654 	}
14655 	/*
14656 	 * Because all our options are either boolean or an int, we can just
14657 	 * pull everything into optval and then unlock and copy. If we ever
14658 	 * add a option that is not a int, then this will have quite an
14659 	 * impact to this routine.
14660 	 */
14661 	switch (sopt->sopt_name) {
14662 	case TCP_BBR_PACE_PER_SEC:
14663 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14664 		break;
14665 	case TCP_BBR_PACE_DEL_TAR:
14666 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14667 		break;
14668 	case TCP_BBR_PACE_SEG_MAX:
14669 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14670 		break;
14671 	case TCP_BBR_MIN_TOPACEOUT:
14672 		optval = bbr->no_pacing_until;
14673 		break;
14674 	case TCP_BBR_PACE_SEG_MIN:
14675 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14676 		break;
14677 	case TCP_BBR_PACE_CROSS:
14678 		optval = bbr->r_ctl.bbr_cross_over;
14679 		break;
14680 	case TCP_BBR_ALGORITHM:
14681 		optval = bbr->rc_use_google;
14682 		break;
14683 	case TCP_BBR_TSLIMITS:
14684 		optval = bbr->rc_use_ts_limit;
14685 		break;
14686 	case TCP_BBR_IWINTSO:
14687 		optval = bbr->rc_init_win;
14688 		break;
14689 	case TCP_BBR_STARTUP_PG:
14690 		optval = bbr->r_ctl.rc_startup_pg;
14691 		break;
14692 	case TCP_BBR_DRAIN_PG:
14693 		optval = bbr->r_ctl.rc_drain_pg;
14694 		break;
14695 	case TCP_BBR_PROBE_RTT_INT:
14696 		optval = bbr->r_ctl.rc_probertt_int;
14697 		break;
14698 	case TCP_BBR_PROBE_RTT_LEN:
14699 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14700 		break;
14701 	case TCP_BBR_PROBE_RTT_GAIN:
14702 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14703 		break;
14704 	case TCP_BBR_STARTUP_LOSS_EXIT:
14705 		optval = bbr->rc_loss_exit;
14706 		break;
14707 	case TCP_BBR_USEDEL_RATE:
14708 		error = EINVAL;
14709 		break;
14710 	case TCP_BBR_MIN_RTO:
14711 		optval = bbr->r_ctl.rc_min_rto_ms;
14712 		break;
14713 	case TCP_BBR_MAX_RTO:
14714 		optval = bbr->rc_max_rto_sec;
14715 		break;
14716 	case TCP_RACK_PACE_MAX_SEG:
14717 		/* Max segments in a pace */
14718 		optval = bbr->r_ctl.rc_pace_max_segs;
14719 		break;
14720 	case TCP_RACK_MIN_TO:
14721 		/* Minimum time between rack t-o's in ms */
14722 		optval = bbr->r_ctl.rc_min_to;
14723 		break;
14724 	case TCP_RACK_REORD_THRESH:
14725 		/* RACK reorder threshold (shift amount) */
14726 		optval = bbr->r_ctl.rc_reorder_shift;
14727 		break;
14728 	case TCP_RACK_REORD_FADE:
14729 		/* Does reordering fade after ms time */
14730 		optval = bbr->r_ctl.rc_reorder_fade;
14731 		break;
14732 	case TCP_BBR_USE_RACK_CHEAT:
14733 		/* Do we use the rack cheat for rxt */
14734 		optval = bbr->bbr_use_rack_cheat;
14735 		break;
14736 	case TCP_BBR_FLOOR_MIN_TSO:
14737 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14738 		break;
14739 	case TCP_BBR_UTTER_MAX_TSO:
14740 		optval = bbr->r_ctl.bbr_utter_max;
14741 		break;
14742 	case TCP_BBR_SEND_IWND_IN_TSO:
14743 		/* Do we send TSO size segments initially */
14744 		optval = bbr->bbr_init_win_cheat;
14745 		break;
14746 	case TCP_BBR_EXTRA_STATE:
14747 		optval = bbr->rc_use_idle_restart;
14748 		break;
14749 	case TCP_RACK_TLP_THRESH:
14750 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14751 		optval = bbr->rc_tlp_threshold;
14752 		break;
14753 	case TCP_RACK_PKT_DELAY:
14754 		/* RACK added ms i.e. rack-rtt + reord + N */
14755 		optval = bbr->r_ctl.rc_pkt_delay;
14756 		break;
14757 	case TCP_BBR_RETRAN_WTSO:
14758 		optval = bbr->rc_resends_use_tso;
14759 		break;
14760 	case TCP_DATA_AFTER_CLOSE:
14761 		optval = bbr->rc_allow_data_af_clo;
14762 		break;
14763 	case TCP_DELACK:
14764 		optval = tp->t_delayed_ack;
14765 		break;
14766 	case TCP_BBR_HDWR_PACE:
14767 		optval = bbr->bbr_hdw_pace_ena;
14768 		break;
14769 	case TCP_BBR_POLICER_DETECT:
14770 		optval = bbr->r_use_policer;
14771 		break;
14772 	case TCP_BBR_TSTMP_RAISES:
14773 		optval = bbr->ts_can_raise;
14774 		break;
14775 	case TCP_BBR_TMR_PACE_OH:
14776 		optval = bbr->r_ctl.rc_incr_tmrs;
14777 		break;
14778 	case TCP_BBR_PACE_OH:
14779 		optval = 0;
14780 		if (bbr->r_ctl.rc_inc_tcp_oh)
14781 			optval |= BBR_INCL_TCP_OH;
14782 		if (bbr->r_ctl.rc_inc_ip_oh)
14783 			optval |= BBR_INCL_IP_OH;
14784 		if (bbr->r_ctl.rc_inc_enet_oh)
14785 			optval |= BBR_INCL_ENET_OH;
14786 		break;
14787 	default:
14788 		return (tcp_default_ctloutput(inp, sopt));
14789 		break;
14790 	}
14791 	INP_WUNLOCK(inp);
14792 	error = sooptcopyout(sopt, &optval, sizeof optval);
14793 	return (error);
14794 }
14795 
14796 /*
14797  * return 0 on success, error-num on failure
14798  */
14799 static int
14800 bbr_ctloutput(struct inpcb *inp, struct sockopt *sopt)
14801 {
14802 	if (sopt->sopt_dir == SOPT_SET) {
14803 		return (bbr_set_sockopt(inp, sopt));
14804 	} else if (sopt->sopt_dir == SOPT_GET) {
14805 		return (bbr_get_sockopt(inp, sopt));
14806 	} else {
14807 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14808 	}
14809 }
14810 
14811 static const char *bbr_stack_names[] = {
14812 	__XSTRING(STACKNAME),
14813 #ifdef STACKALIAS
14814 	__XSTRING(STACKALIAS),
14815 #endif
14816 };
14817 
14818 static bool bbr_mod_inited = false;
14819 
14820 static int
14821 tcp_addbbr(module_t mod, int32_t type, void *data)
14822 {
14823 	int32_t err = 0;
14824 	int num_stacks;
14825 
14826 	switch (type) {
14827 	case MOD_LOAD:
14828 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14829 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14830 		    sizeof(struct bbr_sendmap),
14831 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14832 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14833 		    sizeof(struct tcp_bbr),
14834 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14835 		sysctl_ctx_init(&bbr_sysctl_ctx);
14836 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14837 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14838 		    OID_AUTO,
14839 #ifdef STACKALIAS
14840 		    __XSTRING(STACKALIAS),
14841 #else
14842 		    __XSTRING(STACKNAME),
14843 #endif
14844 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14845 		    "");
14846 		if (bbr_sysctl_root == NULL) {
14847 			printf("Failed to add sysctl node\n");
14848 			err = EFAULT;
14849 			goto free_uma;
14850 		}
14851 		bbr_init_sysctls();
14852 		num_stacks = nitems(bbr_stack_names);
14853 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14854 		    bbr_stack_names, &num_stacks);
14855 		if (err) {
14856 			printf("Failed to register %s stack name for "
14857 			    "%s module\n", bbr_stack_names[num_stacks],
14858 			    __XSTRING(MODNAME));
14859 			sysctl_ctx_free(&bbr_sysctl_ctx);
14860 	free_uma:
14861 			uma_zdestroy(bbr_zone);
14862 			uma_zdestroy(bbr_pcb_zone);
14863 			bbr_counter_destroy();
14864 			printf("Failed to register " __XSTRING(MODNAME)
14865 			    " module err:%d\n", err);
14866 			return (err);
14867 		}
14868 		tcp_lro_reg_mbufq();
14869 		bbr_mod_inited = true;
14870 		printf(__XSTRING(MODNAME) " is now available\n");
14871 		break;
14872 	case MOD_QUIESCE:
14873 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14874 		break;
14875 	case MOD_UNLOAD:
14876 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14877 		if (err == EBUSY)
14878 			break;
14879 		if (bbr_mod_inited) {
14880 			uma_zdestroy(bbr_zone);
14881 			uma_zdestroy(bbr_pcb_zone);
14882 			sysctl_ctx_free(&bbr_sysctl_ctx);
14883 			bbr_counter_destroy();
14884 			printf(__XSTRING(MODNAME)
14885 			    " is now no longer available\n");
14886 			bbr_mod_inited = false;
14887 		}
14888 		tcp_lro_dereg_mbufq();
14889 		err = 0;
14890 		break;
14891 	default:
14892 		return (EOPNOTSUPP);
14893 	}
14894 	return (err);
14895 }
14896 
14897 static moduledata_t tcp_bbr = {
14898 	.name = __XSTRING(MODNAME),
14899 	    .evhand = tcp_addbbr,
14900 	    .priv = 0
14901 };
14902 
14903 MODULE_VERSION(MODNAME, 1);
14904 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14905 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14906