xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision fa4d25f5b4573a54eebeb7f254b52153b8d3811e)
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) ||
588 		    sbavail(&tptosocket(tp)->so_snd)) {
589 			uint64_t tov;
590 
591 			time_since_sent = 0;
592 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
593 			if (rsm) {
594 				idx = rsm->r_rtr_cnt - 1;
595 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
596 					tstmp_touse = rsm->r_tim_lastsent[idx];
597 				else
598 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
599 				if (TSTMP_GT(tstmp_touse, cts))
600 				    time_since_sent = cts - tstmp_touse;
601 			}
602 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
603 			if (tp->t_srtt == 0)
604 				tov = BBR_INITIAL_RTO;
605 			else
606 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
607 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
608 			if (tp->t_rxtshift)
609 				tov *= tcp_backoff[tp->t_rxtshift];
610 			if (tov > time_since_sent)
611 				tov -= time_since_sent;
612 			else
613 				tov = bbr->r_ctl.rc_min_to;
614 			TCPT_RANGESET_NOSLOP(to, tov,
615 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
616 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
617 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
618 			return (to);
619 		}
620 		return (0);
621 	}
622 	if (rsm->r_flags & BBR_ACKED) {
623 		rsm = bbr_find_lowest_rsm(bbr);
624 		if (rsm == NULL) {
625 			/* No lowest? */
626 			goto activate_rxt;
627 		}
628 	}
629 	/* Convert from ms to usecs */
630 	if (rsm->r_flags & BBR_SACK_PASSED) {
631 		if ((tp->t_flags & TF_SENTFIN) &&
632 		    ((tp->snd_max - tp->snd_una) == 1) &&
633 		    (rsm->r_flags & BBR_HAS_FIN)) {
634 			/*
635 			 * We don't start a bbr rack timer if all we have is
636 			 * a FIN outstanding.
637 			 */
638 			goto activate_rxt;
639 		}
640 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
641 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
642 		idx = rsm->r_rtr_cnt - 1;
643 		exp = rsm->r_tim_lastsent[idx] + thresh;
644 		if (SEQ_GEQ(exp, cts)) {
645 			to = exp - cts;
646 			if (to < bbr->r_ctl.rc_min_to) {
647 				to = bbr->r_ctl.rc_min_to;
648 			}
649 		} else {
650 			to = bbr->r_ctl.rc_min_to;
651 		}
652 	} else {
653 		/* Ok we need to do a TLP not RACK */
654 		if (bbr->rc_tlp_in_progress != 0) {
655 			/*
656 			 * The previous send was a TLP.
657 			 */
658 			goto activate_rxt;
659 		}
660 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
661 		if (rsm == NULL) {
662 			/* We found no rsm to TLP with. */
663 			goto activate_rxt;
664 		}
665 		if (rsm->r_flags & BBR_HAS_FIN) {
666 			/* If its a FIN we don't do TLP */
667 			rsm = NULL;
668 			goto activate_rxt;
669 		}
670 		time_since_sent = 0;
671 		idx = rsm->r_rtr_cnt - 1;
672 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
673 			tstmp_touse = rsm->r_tim_lastsent[idx];
674 		else
675 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
676 		if (TSTMP_GT(tstmp_touse, cts))
677 		    time_since_sent = cts - tstmp_touse;
678 		is_tlp_timer = 1;
679 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
680 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
681 		if (thresh > time_since_sent)
682 			to = thresh - time_since_sent;
683 		else
684 			to = bbr->r_ctl.rc_min_to;
685 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
686 			/*
687 			 * If the TLP time works out to larger than the max
688 			 * RTO lets not do TLP.. just RTO.
689 			 */
690 			goto activate_rxt;
691 		}
692 		if ((bbr->rc_tlp_rtx_out == 1) &&
693 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
694 			/*
695 			 * Second retransmit of the same TLP
696 			 * lets not.
697 			 */
698 			bbr->rc_tlp_rtx_out = 0;
699 			goto activate_rxt;
700 		}
701 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
702 			/*
703 			 * The tail is no longer the last one I did a probe
704 			 * on
705 			 */
706 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
707 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
708 		}
709 	}
710 	if (is_tlp_timer == 0) {
711 		BBR_STAT_INC(bbr_to_arm_rack);
712 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
713 	} else {
714 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
715 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
716 			/*
717 			 * We have exceeded how many times we can retran the
718 			 * current TLP timer, switch to the RTO timer.
719 			 */
720 			goto activate_rxt;
721 		} else {
722 			BBR_STAT_INC(bbr_to_arm_tlp);
723 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
724 		}
725 	}
726 	return (to);
727 }
728 
729 static inline int32_t
730 bbr_minseg(struct tcp_bbr *bbr)
731 {
732 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
733 }
734 
735 static void
736 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
737 {
738 	struct inpcb *inp = tptoinpcb(tp);
739 	struct hpts_diag diag;
740 	uint32_t delayed_ack = 0;
741 	uint32_t left = 0;
742 	uint32_t hpts_timeout;
743 	uint8_t stopped;
744 	int32_t delay_calc = 0;
745 	uint32_t prev_delay = 0;
746 
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(inp, 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(inp, 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 				mbuf_tstmp2timeval(m, &tv);
2265 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2266 			} else {
2267 				/* No arrival timestamp */
2268 				log.u_bbr.flex5 = 0;
2269 			}
2270 
2271 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2272 		} else {
2273 			log.u_bbr.flex3 = 0;
2274 			log.u_bbr.flex5 = 0;
2275 			log.u_bbr.flex6 = 0;
2276 			log.u_bbr.pkts_out = 0;
2277 		}
2278 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2279 		log.u_bbr.flex7 = bbr->r_wanted_output;
2280 		log.u_bbr.flex8 = bbr->rc_in_persist;
2281 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2282 		    &bbr->rc_inp->inp_socket->so_rcv,
2283 		    &bbr->rc_inp->inp_socket->so_snd,
2284 		    TCP_LOG_IN, 0,
2285 		    tlen, &log, true, &bbr->rc_tv);
2286 	}
2287 }
2288 
2289 static void
2290 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2291 {
2292 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2293 		union tcp_log_stackspecific log;
2294 
2295 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2296 		log.u_bbr.flex1 = did_out;
2297 		log.u_bbr.flex2 = nxt_pkt;
2298 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2299 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2300 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2301 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2302 		log.u_bbr.flex7 = bbr->r_wanted_output;
2303 		log.u_bbr.flex8 = bbr->rc_in_persist;
2304 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2305 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2306 		    &bbr->rc_inp->inp_socket->so_rcv,
2307 		    &bbr->rc_inp->inp_socket->so_snd,
2308 		    BBR_LOG_DOSEG_DONE, 0,
2309 		    0, &log, true, &bbr->rc_tv);
2310 	}
2311 }
2312 
2313 static void
2314 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2315     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2316 {
2317 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2318 		union tcp_log_stackspecific log;
2319 
2320 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2321 		log.u_bbr.flex1 = line;
2322 		log.u_bbr.flex2 = o_len;
2323 		log.u_bbr.flex3 = segcnt;
2324 		log.u_bbr.flex4 = segsiz;
2325 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2326 		    &bbr->rc_inp->inp_socket->so_rcv,
2327 		    &bbr->rc_inp->inp_socket->so_snd,
2328 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2329 		    len, &log, true, &bbr->rc_tv);
2330 	}
2331 }
2332 
2333 static void
2334 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2335 {
2336 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2337 		union tcp_log_stackspecific log;
2338 
2339 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2340 		log.u_bbr.flex1 = timers;
2341 		log.u_bbr.flex2 = ret;
2342 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2343 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2344 		log.u_bbr.flex5 = cts;
2345 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2346 		log.u_bbr.flex8 = hpts_calling;
2347 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2348 		    &bbr->rc_inp->inp_socket->so_rcv,
2349 		    &bbr->rc_inp->inp_socket->so_snd,
2350 		    BBR_LOG_TO_PROCESS, 0,
2351 		    0, &log, false, &bbr->rc_tv);
2352 	}
2353 }
2354 
2355 static void
2356 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2357 {
2358 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2359 		union tcp_log_stackspecific log;
2360 		uint64_t ar;
2361 
2362 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2363 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2364 		log.u_bbr.flex2 = 0;
2365 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2366 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2367 		ar >>= 32;
2368 		ar &= 0x00000000ffffffff;
2369 		log.u_bbr.flex4 = (uint32_t)ar;
2370 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2371 		ar &= 0x00000000ffffffff;
2372 		log.u_bbr.flex5 = (uint32_t)ar;
2373 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2374 		log.u_bbr.flex8 = to_num;
2375 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2376 		    &bbr->rc_inp->inp_socket->so_rcv,
2377 		    &bbr->rc_inp->inp_socket->so_snd,
2378 		    BBR_LOG_RTO, 0,
2379 		    0, &log, false, &bbr->rc_tv);
2380 	}
2381 }
2382 
2383 static void
2384 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2385 {
2386 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2387 		union tcp_log_stackspecific log;
2388 
2389 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2390 		log.u_bbr.flex1 = flex1;
2391 		log.u_bbr.flex2 = flex2;
2392 		log.u_bbr.flex3 = flex3;
2393 		log.u_bbr.flex4 = 0;
2394 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2395 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2396 		log.u_bbr.flex8 = reason;
2397 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2398 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2399 		    &bbr->rc_inp->inp_socket->so_rcv,
2400 		    &bbr->rc_inp->inp_socket->so_snd,
2401 		    BBR_LOG_REDUCE, 0,
2402 		    0, &log, false, &bbr->rc_tv);
2403 	}
2404 }
2405 
2406 static void
2407 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2408 {
2409 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2410 		union tcp_log_stackspecific log;
2411 
2412 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2413 		log.u_bbr.flex1 = diag->p_nxt_slot;
2414 		log.u_bbr.flex2 = diag->p_cur_slot;
2415 		log.u_bbr.flex3 = diag->slot_req;
2416 		log.u_bbr.flex4 = diag->inp_hptsslot;
2417 		log.u_bbr.flex5 = diag->slot_remaining;
2418 		log.u_bbr.flex6 = diag->need_new_to;
2419 		log.u_bbr.flex7 = diag->p_hpts_active;
2420 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2421 		/* Hijack other fields as needed  */
2422 		log.u_bbr.epoch = diag->have_slept;
2423 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2424 		log.u_bbr.pkts_out = diag->co_ret;
2425 		log.u_bbr.applimited = diag->hpts_sleep_time;
2426 		log.u_bbr.delivered = diag->p_prev_slot;
2427 		log.u_bbr.inflight = diag->p_runningslot;
2428 		log.u_bbr.bw_inuse = diag->wheel_slot;
2429 		log.u_bbr.rttProp = diag->wheel_cts;
2430 		log.u_bbr.delRate = diag->maxslots;
2431 		log.u_bbr.cur_del_rate = diag->p_curtick;
2432 		log.u_bbr.cur_del_rate <<= 32;
2433 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2434 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2435 		    &bbr->rc_inp->inp_socket->so_rcv,
2436 		    &bbr->rc_inp->inp_socket->so_snd,
2437 		    BBR_LOG_HPTSDIAG, 0,
2438 		    0, &log, false, &bbr->rc_tv);
2439 	}
2440 }
2441 
2442 static void
2443 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2444     uint32_t thresh, uint32_t to)
2445 {
2446 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2447 		union tcp_log_stackspecific log;
2448 
2449 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2450 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2451 		log.u_bbr.flex2 = time_since_sent;
2452 		log.u_bbr.flex3 = srtt;
2453 		log.u_bbr.flex4 = thresh;
2454 		log.u_bbr.flex5 = to;
2455 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2456 		log.u_bbr.flex8 = mode;
2457 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2458 		    &bbr->rc_inp->inp_socket->so_rcv,
2459 		    &bbr->rc_inp->inp_socket->so_snd,
2460 		    BBR_LOG_TIMERPREP, 0,
2461 		    0, &log, false, &bbr->rc_tv);
2462 	}
2463 }
2464 
2465 static void
2466 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2467     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2468 {
2469 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2470 		union tcp_log_stackspecific log;
2471 
2472 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2473 		log.u_bbr.flex1 = usecs;
2474 		log.u_bbr.flex2 = len;
2475 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2476 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2477 		if (override)
2478 			log.u_bbr.flex5 = (1 << 2);
2479 		else
2480 			log.u_bbr.flex5 = 0;
2481 		log.u_bbr.flex6 = override;
2482 		log.u_bbr.flex7 = gain;
2483 		log.u_bbr.flex8 = mod;
2484 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2485 		    &bbr->rc_inp->inp_socket->so_rcv,
2486 		    &bbr->rc_inp->inp_socket->so_snd,
2487 		    BBR_LOG_HPTSI_CALC, 0,
2488 		    len, &log, false, &bbr->rc_tv);
2489 	}
2490 }
2491 
2492 static void
2493 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2494 {
2495 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2496 		union tcp_log_stackspecific log;
2497 
2498 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2499 
2500 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2501 		log.u_bbr.flex2 = to;
2502 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2503 		log.u_bbr.flex4 = slot;
2504 		log.u_bbr.flex5 = bbr->rc_inp->inp_hptsslot;
2505 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2506 		log.u_bbr.pkts_out = bbr->rc_inp->inp_flags2;
2507 		log.u_bbr.flex8 = which;
2508 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2509 		    &bbr->rc_inp->inp_socket->so_rcv,
2510 		    &bbr->rc_inp->inp_socket->so_snd,
2511 		    BBR_LOG_TIMERSTAR, 0,
2512 		    0, &log, false, &bbr->rc_tv);
2513 	}
2514 }
2515 
2516 static void
2517 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)
2518 {
2519 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2520 		union tcp_log_stackspecific log;
2521 
2522 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2523 		log.u_bbr.flex1 = thresh;
2524 		log.u_bbr.flex2 = lro;
2525 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2526 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2527 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2528 		log.u_bbr.flex6 = srtt;
2529 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2530 		log.u_bbr.flex8 = frm;
2531 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2532 		    &bbr->rc_inp->inp_socket->so_rcv,
2533 		    &bbr->rc_inp->inp_socket->so_snd,
2534 		    BBR_LOG_THRESH_CALC, 0,
2535 		    0, &log, false, &bbr->rc_tv);
2536 	}
2537 }
2538 
2539 static void
2540 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2541 {
2542 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2543 		union tcp_log_stackspecific log;
2544 
2545 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2546 		log.u_bbr.flex1 = line;
2547 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2548 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2549 		log.u_bbr.flex4 = bbr->rc_in_persist;
2550 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2551 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2552 		log.u_bbr.flex8 = hpts_removed;
2553 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2554 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2555 		    &bbr->rc_inp->inp_socket->so_rcv,
2556 		    &bbr->rc_inp->inp_socket->so_snd,
2557 		    BBR_LOG_TIMERCANC, 0,
2558 		    0, &log, false, &bbr->rc_tv);
2559 	}
2560 }
2561 
2562 static void
2563 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2564 {
2565 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2566 		union tcp_log_stackspecific log;
2567 
2568 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2569 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2570 		log.u_bbr.flex2 = (peer_delta >> 32);
2571 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2572 		log.u_bbr.flex4 = (delta >> 32);
2573 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2574 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2575 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2576 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2577 		    &bbr->rc_inp->inp_socket->so_rcv,
2578 		    &bbr->rc_inp->inp_socket->so_snd,
2579 		    BBR_LOG_TSTMP_VAL, 0,
2580 		    0, &log, false, &bbr->rc_tv);
2581 	}
2582 }
2583 
2584 static void
2585 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)
2586 {
2587 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2588 		union tcp_log_stackspecific log;
2589 
2590 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2591 		log.u_bbr.flex1 = tsosz;
2592 		log.u_bbr.flex2 = tls;
2593 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2594 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2595 		log.u_bbr.flex5 = old_val;
2596 		log.u_bbr.flex6 = maxseg;
2597 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2598 		log.u_bbr.flex7 <<= 1;
2599 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2600 		if (hdwr)
2601 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2602 		else
2603 			log.u_bbr.flex8 = bbr->rc_use_google;
2604 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2605 		    &bbr->rc_inp->inp_socket->so_rcv,
2606 		    &bbr->rc_inp->inp_socket->so_snd,
2607 		    BBR_LOG_BBRTSO, 0,
2608 		    0, &log, false, &bbr->rc_tv);
2609 	}
2610 }
2611 
2612 static void
2613 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2614 		      uint32_t flags, uint32_t line)
2615 {
2616 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2617 		union tcp_log_stackspecific log;
2618 
2619 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2620 		log.u_bbr.flex1 = line;
2621 		log.u_bbr.flex2 = rsm->r_start;
2622 		log.u_bbr.flex3 = rsm->r_end;
2623 		log.u_bbr.flex4 = rsm->r_delivered;
2624 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2625 		log.u_bbr.flex6 = rsm->r_dupack;
2626 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2627 		log.u_bbr.flex8 = rsm->r_flags;
2628 		/* Hijack the pkts_out fids */
2629 		log.u_bbr.applimited = flags;
2630 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2631 		    &bbr->rc_inp->inp_socket->so_rcv,
2632 		    &bbr->rc_inp->inp_socket->so_snd,
2633 		    BBR_RSM_CLEARED, 0,
2634 		    0, &log, false, &bbr->rc_tv);
2635 	}
2636 }
2637 
2638 static void
2639 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2640     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2641     uint32_t flex6, uint32_t pkts_out, int flex7,
2642     uint32_t flex4, uint32_t flex1)
2643 {
2644 
2645 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2646 		union tcp_log_stackspecific log;
2647 
2648 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2649 		log.u_bbr.flex1 = flex1;
2650 		log.u_bbr.flex2 = flex2;
2651 		log.u_bbr.flex3 = flex3;
2652 		log.u_bbr.flex4 = flex4;
2653 		log.u_bbr.flex5 = flex5;
2654 		log.u_bbr.flex6 = flex6;
2655 		log.u_bbr.flex7 = flex7;
2656 		/* Hijack the pkts_out fids */
2657 		log.u_bbr.pkts_out = pkts_out;
2658 		log.u_bbr.flex8 = flex8;
2659 		if (bbr->rc_ack_was_delayed)
2660 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2661 		else
2662 			log.u_bbr.epoch = 0;
2663 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2664 		    &bbr->rc_inp->inp_socket->so_rcv,
2665 		    &bbr->rc_inp->inp_socket->so_snd,
2666 		    BBR_LOG_BBRUPD, 0,
2667 		    flex2, &log, false, &bbr->rc_tv);
2668 	}
2669 }
2670 
2671 static void
2672 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2673 	uint32_t newbw, uint32_t obw, uint32_t diff,
2674 	uint32_t tim)
2675 {
2676 	if (/*bbr_verbose_logging && */(bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2677 		union tcp_log_stackspecific log;
2678 
2679 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2680 		log.u_bbr.flex1 = reason;
2681 		log.u_bbr.flex2 = newbw;
2682 		log.u_bbr.flex3 = obw;
2683 		log.u_bbr.flex4 = diff;
2684 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2685 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2686 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2687 		log.u_bbr.pkts_out = tim;
2688 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2689 		if (bbr->rc_lt_use_bw == 0)
2690 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2691 		else
2692 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2693 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2694 		    &bbr->rc_inp->inp_socket->so_rcv,
2695 		    &bbr->rc_inp->inp_socket->so_snd,
2696 		    BBR_LOG_BWSAMP, 0,
2697 		    0, &log, false, &bbr->rc_tv);
2698 	}
2699 }
2700 
2701 static inline void
2702 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2703 {
2704 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2705 		union tcp_log_stackspecific log;
2706 
2707 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2708 		log.u_bbr.flex1 = line;
2709 		log.u_bbr.flex2 = tick;
2710 		log.u_bbr.flex3 = tp->t_maxunacktime;
2711 		log.u_bbr.flex4 = tp->t_acktime;
2712 		log.u_bbr.flex8 = event;
2713 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2714 		    &bbr->rc_inp->inp_socket->so_rcv,
2715 		    &bbr->rc_inp->inp_socket->so_snd,
2716 		    BBR_LOG_PROGRESS, 0,
2717 		    0, &log, false, &bbr->rc_tv);
2718 	}
2719 }
2720 
2721 static void
2722 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2723 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2724 			 int error)
2725 {
2726 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2727 		union tcp_log_stackspecific log;
2728 
2729 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2730 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2731 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2732 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2733 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2734 		log.u_bbr.bw_inuse = rate;
2735 		log.u_bbr.flex5 = line;
2736 		log.u_bbr.flex6 = error;
2737 		log.u_bbr.flex8 = bbr->skip_gain;
2738 		log.u_bbr.flex8 <<= 1;
2739 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2740 		log.u_bbr.flex8 <<= 1;
2741 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2742 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2743 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2744 		    &bbr->rc_inp->inp_socket->so_rcv,
2745 		    &bbr->rc_inp->inp_socket->so_snd,
2746 		    BBR_LOG_HDWR_PACE, 0,
2747 		    0, &log, false, &bbr->rc_tv);
2748 	}
2749 }
2750 
2751 static void
2752 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)
2753 {
2754 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2755 		union tcp_log_stackspecific log;
2756 
2757 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2758 		log.u_bbr.flex1 = slot;
2759 		log.u_bbr.flex2 = del_by;
2760 		log.u_bbr.flex3 = prev_delay;
2761 		log.u_bbr.flex4 = line;
2762 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2763 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2764 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2765 		log.u_bbr.flex8 = bbr->rc_in_persist;
2766 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2767 		    &bbr->rc_inp->inp_socket->so_rcv,
2768 		    &bbr->rc_inp->inp_socket->so_snd,
2769 		    BBR_LOG_BBRSND, 0,
2770 		    len, &log, false, &bbr->rc_tv);
2771 	}
2772 }
2773 
2774 static void
2775 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)
2776 {
2777 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2778 		union tcp_log_stackspecific log;
2779 
2780 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2781 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2782 		log.u_bbr.flex2 = 0;
2783 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2784 		log.u_bbr.flex4 = end;
2785 		log.u_bbr.flex5 = seq;
2786 		log.u_bbr.flex6 = t;
2787 		log.u_bbr.flex7 = match;
2788 		log.u_bbr.flex8 = flags;
2789 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2790 		    &bbr->rc_inp->inp_socket->so_rcv,
2791 		    &bbr->rc_inp->inp_socket->so_snd,
2792 		    BBR_LOG_BBRRTT, 0,
2793 		    0, &log, false, &bbr->rc_tv);
2794 	}
2795 }
2796 
2797 static void
2798 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2799 {
2800 	if (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF) {
2801 		union tcp_log_stackspecific log;
2802 
2803 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2804 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2805 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2806 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2807 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2808 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2809 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2810 		log.u_bbr.flex7 = 0;
2811 		log.u_bbr.flex8 = entry_method;
2812 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2813 		    &bbr->rc_inp->inp_socket->so_rcv,
2814 		    &bbr->rc_inp->inp_socket->so_snd,
2815 		    BBR_LOG_EXIT_GAIN, 0,
2816 		    0, &log, false, &bbr->rc_tv);
2817 	}
2818 }
2819 
2820 static void
2821 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2822 {
2823 	if (bbr_verbose_logging && (bbr->rc_tp->t_logstate != TCP_LOG_STATE_OFF)) {
2824 		union tcp_log_stackspecific log;
2825 
2826 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2827 		/* R-HU */
2828 		log.u_bbr.flex1 = 0;
2829 		log.u_bbr.flex2 = 0;
2830 		log.u_bbr.flex3 = 0;
2831 		log.u_bbr.flex4 = 0;
2832 		log.u_bbr.flex7 = 0;
2833 		log.u_bbr.flex8 = settings_desired;
2834 
2835 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2836 		    &bbr->rc_inp->inp_socket->so_rcv,
2837 		    &bbr->rc_inp->inp_socket->so_snd,
2838 		    BBR_LOG_SETTINGS_CHG, 0,
2839 		    0, &log, false, &bbr->rc_tv);
2840 	}
2841 }
2842 
2843 /*
2844  * Returns the bw from the our filter.
2845  */
2846 static inline uint64_t
2847 bbr_get_full_bw(struct tcp_bbr *bbr)
2848 {
2849 	uint64_t bw;
2850 
2851 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2852 
2853 	return (bw);
2854 }
2855 
2856 static inline void
2857 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2858 {
2859 	uint64_t calclr;
2860 	uint32_t lost, del;
2861 
2862 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2863 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2864 	else
2865 		lost = 0;
2866 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2867 	if (lost == 0)  {
2868 		calclr = 0;
2869 	} else if (del) {
2870 		calclr = lost;
2871 		calclr *= (uint64_t)1000;
2872 		calclr /= (uint64_t)del;
2873 	} else {
2874 		/* Nothing delivered? 100.0% loss */
2875 		calclr = 1000;
2876 	}
2877 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2878 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2879 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2880 	bbr->r_ctl.rc_pkt_epoch++;
2881 	if (bbr->rc_no_pacing &&
2882 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2883 		bbr->rc_no_pacing = 0;
2884 		tcp_bbr_tso_size_check(bbr, cts);
2885 	}
2886 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2887 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2888 	/* What was our loss rate */
2889 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2890 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2891 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2892 }
2893 
2894 static inline void
2895 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2896 {
2897 	uint32_t epoch_time;
2898 
2899 	/* Tick the RTT clock */
2900 	bbr->r_ctl.rc_rtt_epoch++;
2901 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2902 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2903 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2904 }
2905 
2906 static inline void
2907 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2908 {
2909 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2910 		bbr->rc_is_pkt_epoch_now = 1;
2911 	}
2912 }
2913 
2914 /*
2915  * Returns the bw from either the b/w filter
2916  * or from the lt_bw (if the connection is being
2917  * policed).
2918  */
2919 static inline uint64_t
2920 __bbr_get_bw(struct tcp_bbr *bbr)
2921 {
2922 	uint64_t bw, min_bw;
2923 	uint64_t rtt;
2924 	int gm_measure_cnt = 1;
2925 
2926 	/*
2927 	 * For startup we make, like google, a
2928 	 * minimum b/w. This is generated from the
2929 	 * IW and the rttProp. We do fall back to srtt
2930 	 * if for some reason (initial handshake) we don't
2931 	 * have a rttProp. We, in the worst case, fall back
2932 	 * to the configured min_bw (rc_initial_hptsi_bw).
2933 	 */
2934 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2935 		/* Attempt first to use rttProp */
2936 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2937 		if (rtt && (rtt < 0xffffffff)) {
2938 measure:
2939 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2940 				((uint64_t)1000000);
2941 			min_bw /= rtt;
2942 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2943 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2944 			}
2945 
2946 		} else if (bbr->rc_tp->t_srtt != 0) {
2947 			/* No rttProp, use srtt? */
2948 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2949 			goto measure;
2950 		} else {
2951 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2952 		}
2953 	} else
2954 		min_bw = 0;
2955 
2956 	if ((bbr->rc_past_init_win == 0) &&
2957 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2958 		bbr->rc_past_init_win = 1;
2959 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2960 		gm_measure_cnt = 0;
2961 	if (gm_measure_cnt &&
2962 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2963 	     (bbr->rc_past_init_win == 0))) {
2964 		/* For google we use our guess rate until we get 1 measurement */
2965 
2966 use_initial_window:
2967 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2968 		if (rtt && (rtt < 0xffffffff)) {
2969 			/*
2970 			 * We have an RTT measurement. Use that in
2971 			 * combination with our initial window to calculate
2972 			 * a b/w.
2973 			 */
2974 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2975 				((uint64_t)1000000);
2976 			bw /= rtt;
2977 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2978 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2979 			}
2980 		} else {
2981 			/* Drop back to the 40 and punt to a default */
2982 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2983 		}
2984 		if (bw < 1)
2985 			/* Probably should panic */
2986 			bw = 1;
2987 		if (bw > min_bw)
2988 			return (bw);
2989 		else
2990 			return (min_bw);
2991 	}
2992 	if (bbr->rc_lt_use_bw)
2993 		bw = bbr->r_ctl.rc_lt_bw;
2994 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2995 		bw = bbr->r_ctl.red_bw;
2996 	else
2997 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2998 	if (bbr->rc_tp->t_peakrate_thr && (bbr->rc_use_google == 0)) {
2999 		/*
3000 		 * Enforce user set rate limit, keep in mind that
3001 		 * t_peakrate_thr is in B/s already
3002 		 */
3003 		bw = uqmin((uint64_t)bbr->rc_tp->t_peakrate_thr, bw);
3004 	}
3005 	if (bw == 0) {
3006 		/* We should not be at 0, go to the initial window then  */
3007 		goto use_initial_window;
3008 	}
3009 	if (bw < 1)
3010 		/* Probably should panic */
3011 		bw = 1;
3012 	if (bw < min_bw)
3013 		bw = min_bw;
3014 	return (bw);
3015 }
3016 
3017 static inline uint64_t
3018 bbr_get_bw(struct tcp_bbr *bbr)
3019 {
3020 	uint64_t bw;
3021 
3022 	bw = __bbr_get_bw(bbr);
3023 	return (bw);
3024 }
3025 
3026 static inline void
3027 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3028 {
3029 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3030 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3031 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3032 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3033 }
3034 
3035 static inline void
3036 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3037 {
3038 	bbr->rc_lt_is_sampling = 0;
3039 	bbr->rc_lt_use_bw = 0;
3040 	bbr->r_ctl.rc_lt_bw = 0;
3041 	bbr_reset_lt_bw_interval(bbr, cts);
3042 }
3043 
3044 static inline void
3045 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3046 {
3047 	uint64_t diff;
3048 
3049 	/* Do we have a previous sample? */
3050 	if (bbr->r_ctl.rc_lt_bw) {
3051 		/* Get the diff in bytes per second */
3052 		if (bbr->r_ctl.rc_lt_bw > bw)
3053 			diff = bbr->r_ctl.rc_lt_bw - bw;
3054 		else
3055 			diff = bw - bbr->r_ctl.rc_lt_bw;
3056 		if ((diff <= bbr_lt_bw_diff) ||
3057 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3058 			/* Consider us policed */
3059 			uint32_t saved_bw;
3060 
3061 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3062 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3063 			bbr->rc_lt_use_bw = 1;
3064 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3065 			/*
3066 			 * Use pkt based epoch for measuring length of
3067 			 * policer up
3068 			 */
3069 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3070 			/*
3071 			 * reason 4 is we need to start consider being
3072 			 * policed
3073 			 */
3074 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3075 			return;
3076 		}
3077 	}
3078 	bbr->r_ctl.rc_lt_bw = bw;
3079 	bbr_reset_lt_bw_interval(bbr, cts);
3080 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3081 }
3082 
3083 static void
3084 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3085 {
3086 	uint32_t ran, deduct;
3087 
3088 	ran = arc4random_uniform(bbr_rand_ot);
3089 	if (ran) {
3090 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3091 		bbr->r_ctl.rc_level_state_extra -= deduct;
3092 	}
3093 }
3094 /*
3095  * Return randomly the starting state
3096  * to use in probebw.
3097  */
3098 static uint8_t
3099 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3100 {
3101 	uint32_t ran;
3102 	uint8_t ret_val;
3103 
3104 	/* Initialize the offset to 0 */
3105 	bbr->r_ctl.rc_exta_time_gd = 0;
3106 	bbr->rc_hit_state_1 = 0;
3107 	bbr->r_ctl.rc_level_state_extra = 0;
3108 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3109 	/*
3110 	 * The math works funny here :) the return value is used to set the
3111 	 * substate and then the state change is called which increments by
3112 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3113 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3114 	 * we return 1 - 7, so we dont return 0 and end up starting in
3115 	 * state 1 (DRAIN).
3116 	 */
3117 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3118 	/* Set an epoch */
3119 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3120 		bbr_set_epoch(bbr, cts, __LINE__);
3121 
3122 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3123 	return (ret_val);
3124 }
3125 
3126 static void
3127 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3128 {
3129 	uint32_t diff, d_time;
3130 	uint64_t del_time, bw, lost, delivered;
3131 
3132 	if (bbr->r_use_policer == 0)
3133 		return;
3134 	if (bbr->rc_lt_use_bw) {
3135 		/* We are using lt bw do we stop yet? */
3136 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3137 		if (diff > bbr_lt_bw_max_rtts) {
3138 			/* Reset it all */
3139 reset_all:
3140 			bbr_reset_lt_bw_sampling(bbr, cts);
3141 			if (bbr->rc_filled_pipe) {
3142 				bbr_set_epoch(bbr, cts, __LINE__);
3143 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3144 				bbr_substate_change(bbr, cts, __LINE__, 0);
3145 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3146 				bbr_log_type_statechange(bbr, cts, __LINE__);
3147 			} else {
3148 				/*
3149 				 * This should not happen really
3150 				 * unless we remove the startup/drain
3151 				 * restrictions above.
3152 				 */
3153 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3154 				bbr_set_epoch(bbr, cts, __LINE__);
3155 				bbr->r_ctl.rc_bbr_state_time = cts;
3156 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3157 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3158 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3159 				bbr_set_state_target(bbr, __LINE__);
3160 				bbr_log_type_statechange(bbr, cts, __LINE__);
3161 			}
3162 			/* reason 0 is to stop using lt-bw */
3163 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3164 			return;
3165 		}
3166 		if (bbr_lt_intvl_fp == 0) {
3167 			/* Not doing false-positive detection */
3168 			return;
3169 		}
3170 		/* False positive detection */
3171 		if (diff == bbr_lt_intvl_fp) {
3172 			/* At bbr_lt_intvl_fp we record the lost */
3173 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3174 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3175 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3176 			/* Now is our loss rate still high? */
3177 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3178 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3179 			if ((delivered == 0) ||
3180 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3181 				/* No still below our threshold */
3182 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3183 			} else {
3184 				/* Yikes its still high, it must be a false positive */
3185 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3186 				goto reset_all;
3187 			}
3188 		}
3189 		return;
3190 	}
3191 	/*
3192 	 * Wait for the first loss before sampling, to let the policer
3193 	 * exhaust its tokens and estimate the steady-state rate allowed by
3194 	 * the policer. Starting samples earlier includes bursts that
3195 	 * over-estimate the bw.
3196 	 */
3197 	if (bbr->rc_lt_is_sampling == 0) {
3198 		/* reason 1 is to begin doing the sampling  */
3199 		if (loss_detected == 0)
3200 			return;
3201 		bbr_reset_lt_bw_interval(bbr, cts);
3202 		bbr->rc_lt_is_sampling = 1;
3203 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3204 		return;
3205 	}
3206 	/* Now how long were we delivering long term last> */
3207 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3208 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3209 	else
3210 		d_time = 0;
3211 
3212 	/* To avoid underestimates, reset sampling if we run out of data. */
3213 	if (bbr->r_ctl.r_app_limited_until) {
3214 		/* Can not measure in app-limited state */
3215 		bbr_reset_lt_bw_sampling(bbr, cts);
3216 		/* reason 2 is to reset sampling due to app limits  */
3217 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3218 		return;
3219 	}
3220 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3221 	if (diff < bbr_lt_intvl_min_rtts) {
3222 		/*
3223 		 * need more samples (we don't
3224 		 * start on a round like linux so
3225 		 * we need 1 more).
3226 		 */
3227 		/* 6 is not_enough time or no-loss */
3228 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3229 		return;
3230 	}
3231 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3232 		/*
3233 		 * For now if we wait too long, reset all sampling. We need
3234 		 * to do some research here, its possible that we should
3235 		 * base this on how much loss as occurred.. something like
3236 		 * if its under 10% (or some thresh) reset all otherwise
3237 		 * don't.  Thats for phase II I guess.
3238 		 */
3239 		bbr_reset_lt_bw_sampling(bbr, cts);
3240  		/* reason 3 is to reset sampling due too long of sampling */
3241 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3242 		return;
3243 	}
3244 	/*
3245 	 * End sampling interval when a packet is lost, so we estimate the
3246 	 * policer tokens were exhausted. Stopping the sampling before the
3247 	 * tokens are exhausted under-estimates the policed rate.
3248 	 */
3249 	if (loss_detected == 0) {
3250 		/* 6 is not_enough time or no-loss */
3251 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3252 		return;
3253 	}
3254 	/* Calculate packets lost and delivered in sampling interval. */
3255 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3256 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3257 	if ((delivered == 0) ||
3258 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3259 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3260 		return;
3261 	}
3262 	if (d_time < 1000) {
3263 		/* Not enough time. wait */
3264 		/* 6 is not_enough time or no-loss */
3265 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3266 		return;
3267 	}
3268 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3269 		/* Too long */
3270 		bbr_reset_lt_bw_sampling(bbr, cts);
3271  		/* reason 3 is to reset sampling due too long of sampling */
3272 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3273 		return;
3274 	}
3275 	del_time = d_time;
3276 	bw = delivered;
3277 	bw *= (uint64_t)USECS_IN_SECOND;
3278 	bw /= del_time;
3279 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3280 }
3281 
3282 /*
3283  * Allocate a sendmap from our zone.
3284  */
3285 static struct bbr_sendmap *
3286 bbr_alloc(struct tcp_bbr *bbr)
3287 {
3288 	struct bbr_sendmap *rsm;
3289 
3290 	BBR_STAT_INC(bbr_to_alloc);
3291 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3292 	if (rsm) {
3293 		bbr->r_ctl.rc_num_maps_alloced++;
3294 		return (rsm);
3295 	}
3296 	if (bbr->r_ctl.rc_free_cnt) {
3297 		BBR_STAT_INC(bbr_to_alloc_emerg);
3298 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3299 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3300 		bbr->r_ctl.rc_free_cnt--;
3301 		return (rsm);
3302 	}
3303 	BBR_STAT_INC(bbr_to_alloc_failed);
3304 	return (NULL);
3305 }
3306 
3307 static struct bbr_sendmap *
3308 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3309 {
3310 	if ((V_tcp_map_entries_limit > 0) &&
3311 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3312 		BBR_STAT_INC(bbr_alloc_limited);
3313 		if (!bbr->alloc_limit_reported) {
3314 			bbr->alloc_limit_reported = 1;
3315 			BBR_STAT_INC(bbr_alloc_limited_conns);
3316 		}
3317 		return (NULL);
3318 	}
3319 	return (bbr_alloc(bbr));
3320 }
3321 
3322 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3323 static struct bbr_sendmap *
3324 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3325 {
3326 	struct bbr_sendmap *rsm;
3327 
3328 	if (limit_type) {
3329 		/* currently there is only one limit type */
3330 		if (V_tcp_map_split_limit > 0 &&
3331 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3332 			BBR_STAT_INC(bbr_split_limited);
3333 			if (!bbr->alloc_limit_reported) {
3334 				bbr->alloc_limit_reported = 1;
3335 				BBR_STAT_INC(bbr_alloc_limited_conns);
3336 			}
3337 			return (NULL);
3338 		}
3339 	}
3340 
3341 	/* allocate and mark in the limit type, if set */
3342 	rsm = bbr_alloc(bbr);
3343 	if (rsm != NULL && limit_type) {
3344 		rsm->r_limit_type = limit_type;
3345 		bbr->r_ctl.rc_num_split_allocs++;
3346 	}
3347 	return (rsm);
3348 }
3349 
3350 static void
3351 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3352 {
3353 	if (rsm->r_limit_type) {
3354 		/* currently there is only one limit type */
3355 		bbr->r_ctl.rc_num_split_allocs--;
3356 	}
3357 	if (rsm->r_is_smallmap)
3358 		bbr->r_ctl.rc_num_small_maps_alloced--;
3359 	if (bbr->r_ctl.rc_tlp_send == rsm)
3360 		bbr->r_ctl.rc_tlp_send = NULL;
3361 	if (bbr->r_ctl.rc_resend == rsm) {
3362 		bbr->r_ctl.rc_resend = NULL;
3363 	}
3364 	if (bbr->r_ctl.rc_next == rsm)
3365 		bbr->r_ctl.rc_next = NULL;
3366 	if (bbr->r_ctl.rc_sacklast == rsm)
3367 		bbr->r_ctl.rc_sacklast = NULL;
3368 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3369 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3370 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3371 		rsm->r_limit_type = 0;
3372 		bbr->r_ctl.rc_free_cnt++;
3373 		return;
3374 	}
3375 	bbr->r_ctl.rc_num_maps_alloced--;
3376 	uma_zfree(bbr_zone, rsm);
3377 }
3378 
3379 /*
3380  * Returns the BDP.
3381  */
3382 static uint64_t
3383 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3384 	/*
3385 	 * Calculate the bytes in flight needed given the bw (in bytes per
3386 	 * second) and the specifyed rtt in useconds. We need to put out the
3387 	 * returned value per RTT to match that rate. Gain will normally
3388 	 * raise it up from there.
3389 	 *
3390 	 * This should not overflow as long as the bandwidth is below 1
3391 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3392 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3393 	 */
3394 	uint64_t usec_per_sec;
3395 
3396 	usec_per_sec = USECS_IN_SECOND;
3397 	return ((rtt * bw) / usec_per_sec);
3398 }
3399 
3400 /*
3401  * Return the initial cwnd.
3402  */
3403 static uint32_t
3404 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3405 {
3406 	uint32_t i_cwnd;
3407 
3408 	if (bbr->rc_init_win) {
3409 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3410 	} else if (V_tcp_initcwnd_segments)
3411 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3412 		    max(2 * tp->t_maxseg, 14600));
3413 	else if (V_tcp_do_rfc3390)
3414 		i_cwnd = min(4 * tp->t_maxseg,
3415 		    max(2 * tp->t_maxseg, 4380));
3416 	else {
3417 		/* Per RFC5681 Section 3.1 */
3418 		if (tp->t_maxseg > 2190)
3419 			i_cwnd = 2 * tp->t_maxseg;
3420 		else if (tp->t_maxseg > 1095)
3421 			i_cwnd = 3 * tp->t_maxseg;
3422 		else
3423 			i_cwnd = 4 * tp->t_maxseg;
3424 	}
3425 	return (i_cwnd);
3426 }
3427 
3428 /*
3429  * Given a specified gain, return the target
3430  * cwnd based on that gain.
3431  */
3432 static uint32_t
3433 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3434 {
3435 	uint64_t bdp, rtt;
3436 	uint32_t cwnd;
3437 
3438 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3439 	    (bbr_get_full_bw(bbr) == 0)) {
3440 		/* No measurements yet */
3441 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3442 	}
3443 	/*
3444 	 * Get bytes per RTT needed (rttProp is normally in
3445 	 * bbr_cwndtarget_rtt_touse)
3446 	 */
3447 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3448 	/* Get the bdp from the two values */
3449 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3450 	/* Now apply the gain */
3451 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3452 
3453 	return (cwnd);
3454 }
3455 
3456 static uint32_t
3457 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3458 {
3459 	uint32_t cwnd, mss;
3460 
3461 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3462 	/* Get the base cwnd with gain rounded to a mss */
3463 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3464 	/*
3465 	 * Add in N (2 default since we do not have a
3466 	 * fq layer to trap packets in) quanta's per the I-D
3467 	 * section 4.2.3.2 quanta adjust.
3468 	 */
3469 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3470 	if (bbr->rc_use_google) {
3471 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3472 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3473 			/*
3474 			 * The linux implementation adds
3475 			 * an extra 2 x mss in gain cycle which
3476 			 * is documented no-where except in the code.
3477 			 * so we add more for Neal undocumented feature
3478 			 */
3479 			cwnd += 2 * mss;
3480 		}
3481  		if ((cwnd / mss) & 0x1) {
3482 			/* Round up for odd num mss */
3483 			cwnd += mss;
3484 		}
3485 	}
3486 	/* Are we below the min cwnd? */
3487 	if (cwnd < get_min_cwnd(bbr))
3488 		return (get_min_cwnd(bbr));
3489 	return (cwnd);
3490 }
3491 
3492 static uint16_t
3493 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3494 {
3495 	if (gain < 1)
3496 		gain = 1;
3497 	return (gain);
3498 }
3499 
3500 static uint32_t
3501 bbr_get_header_oh(struct tcp_bbr *bbr)
3502 {
3503 	int seg_oh;
3504 
3505 	seg_oh = 0;
3506 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3507 		/* Do we include TCP overhead? */
3508 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3509 	}
3510 	if (bbr->r_ctl.rc_inc_ip_oh) {
3511 		/* Do we include IP overhead? */
3512 #ifdef INET6
3513 		if (bbr->r_is_v6) {
3514 			seg_oh += sizeof(struct ip6_hdr);
3515 		} else
3516 #endif
3517 		{
3518 
3519 #ifdef INET
3520 			seg_oh += sizeof(struct ip);
3521 #endif
3522 		}
3523 	}
3524 	if (bbr->r_ctl.rc_inc_enet_oh) {
3525 		/* Do we include the ethernet overhead?  */
3526 		seg_oh += sizeof(struct ether_header);
3527 	}
3528 	return(seg_oh);
3529 }
3530 
3531 static uint32_t
3532 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3533 {
3534 	uint64_t divor, res, tim;
3535 
3536 	if (useconds_time == 0)
3537 		return (0);
3538 	gain = bbr_gain_adjust(bbr, gain);
3539 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3540 	tim = useconds_time;
3541 	res = (tim * bw * gain) / divor;
3542 	if (res == 0)
3543 		res = 1;
3544 	return ((uint32_t)res);
3545 }
3546 
3547 /*
3548  * Given a gain and a length return the delay in useconds that
3549  * should be used to evenly space out packets
3550  * on the connection (based on the gain factor).
3551  */
3552 static uint32_t
3553 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3554 {
3555 	uint64_t bw, lentim, res;
3556 	uint32_t usecs, srtt, over = 0;
3557 	uint32_t seg_oh, num_segs, maxseg;
3558 
3559 	if (len == 0)
3560 		return (0);
3561 
3562 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3563 	num_segs = (len + maxseg - 1) / maxseg;
3564 	if (bbr->rc_use_google == 0) {
3565 		seg_oh = bbr_get_header_oh(bbr);
3566 		len += (num_segs * seg_oh);
3567 	}
3568 	gain = bbr_gain_adjust(bbr, gain);
3569 	bw = bbr_get_bw(bbr);
3570 	if (bbr->rc_use_google) {
3571 		uint64_t cbw;
3572 
3573 		/*
3574 		 * Reduce the b/w by the google discount
3575 		 * factor 10 = 1%.
3576 		 */
3577 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3578 		cbw /= (uint64_t)1000;
3579 		/* We don't apply a discount if it results in 0 */
3580 		if (cbw > 0)
3581 			bw = cbw;
3582 	}
3583 	lentim = ((uint64_t)len *
3584 		  (uint64_t)USECS_IN_SECOND *
3585 		  (uint64_t)BBR_UNIT);
3586 	res = lentim / ((uint64_t)gain * bw);
3587 	if (res == 0)
3588 		res = 1;
3589 	usecs = (uint32_t)res;
3590 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3591 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3592 	    (bbr->rc_use_google == 0) &&
3593 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3594 		/*
3595 		 * We cannot let the delay be more than 1/2 the srtt time.
3596 		 * Otherwise we cannot pace out or send properly.
3597 		 */
3598 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3599 		BBR_STAT_INC(bbr_hpts_min_time);
3600 	}
3601 	if (!nolog)
3602 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3603 	return (usecs);
3604 }
3605 
3606 static void
3607 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3608 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3609 {
3610 	uint64_t bw;
3611 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3612 	int32_t meth;
3613 
3614 	INP_WLOCK_ASSERT(tptoinpcb(tp));
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(tptoinpcb(tp));
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(tptoinpcb(tp));
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(tptoinpcb(tp));
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 = tptosocket(tp);
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 retransmitted 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 
4758 	/*
4759 	 * Persistence timer into zero window. Force a byte to be output, if
4760 	 * possible.
4761 	 */
4762 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4763 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4764 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4765 	/*
4766 	 * Have we exceeded the user specified progress time?
4767 	 */
4768 	if (ctf_progress_timeout_check(tp, true)) {
4769 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4770 		return (-ETIMEDOUT);	/* tcp_drop() */
4771 	}
4772 	/*
4773 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4774 	 * window is closed.  After a full backoff, drop the connection if
4775 	 * the idle time (no responses to probes) reaches the maximum
4776 	 * backoff that we would use if retransmitting.
4777 	 */
4778 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
4779 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4780 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4781 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4782 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4783 		return (-ETIMEDOUT);	/* tcp_drop() */
4784 	}
4785 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4786 	    tp->snd_una == tp->snd_max) {
4787 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4788 		retval = 0;
4789 		goto out;
4790 	}
4791 	/*
4792 	 * If the user has closed the socket then drop a persisting
4793 	 * connection after a much reduced timeout.
4794 	 */
4795 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4796 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4797 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4798 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4799 		return (-ETIMEDOUT);	/* tcp_drop() */
4800 	}
4801 	t_template = tcpip_maketemplate(bbr->rc_inp);
4802 	if (t_template) {
4803 		tcp_respond(tp, t_template->tt_ipgen,
4804 			    &t_template->tt_t, (struct mbuf *)NULL,
4805 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4806 		/* This sends an ack */
4807 		if (tp->t_flags & TF_DELACK)
4808 			tp->t_flags &= ~TF_DELACK;
4809 		free(t_template, M_TEMP);
4810 	}
4811 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
4812 		tp->t_rxtshift++;
4813 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4814 out:
4815 	return (retval);
4816 }
4817 
4818 /*
4819  * If a keepalive goes off, we had no other timers
4820  * happening. We always return 1 here since this
4821  * routine either drops the connection or sends
4822  * out a segment with respond.
4823  */
4824 static int
4825 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4826 {
4827 	struct tcptemp *t_template;
4828 	struct inpcb *inp = tptoinpcb(tp);
4829 
4830 	if (bbr->rc_all_timers_stopped) {
4831 		return (1);
4832 	}
4833 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4834 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4835 	/*
4836 	 * Keep-alive timer went off; send something or drop connection if
4837 	 * idle for too long.
4838 	 */
4839 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4840 	if (tp->t_state < TCPS_ESTABLISHED)
4841 		goto dropit;
4842 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4843 	    tp->t_state <= TCPS_CLOSING) {
4844 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4845 			goto dropit;
4846 		/*
4847 		 * Send a packet designed to force a response if the peer is
4848 		 * up and reachable: either an ACK if the connection is
4849 		 * still alive, or an RST if the peer has closed the
4850 		 * connection due to timeout or reboot. Using sequence
4851 		 * number tp->snd_una-1 causes the transmitted zero-length
4852 		 * segment to lie outside the receive window; by the
4853 		 * protocol spec, this requires the correspondent TCP to
4854 		 * respond.
4855 		 */
4856 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4857 		t_template = tcpip_maketemplate(inp);
4858 		if (t_template) {
4859 			tcp_respond(tp, t_template->tt_ipgen,
4860 			    &t_template->tt_t, (struct mbuf *)NULL,
4861 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4862 			free(t_template, M_TEMP);
4863 		}
4864 	}
4865 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4866 	return (1);
4867 dropit:
4868 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4869 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4870 	return (-ETIMEDOUT);	/* tcp_drop() */
4871 }
4872 
4873 /*
4874  * Retransmit helper function, clear up all the ack
4875  * flags and take care of important book keeping.
4876  */
4877 static void
4878 bbr_remxt_tmr(struct tcpcb *tp)
4879 {
4880 	/*
4881 	 * The retransmit timer went off, all sack'd blocks must be
4882 	 * un-acked.
4883 	 */
4884 	struct bbr_sendmap *rsm, *trsm = NULL;
4885 	struct tcp_bbr *bbr;
4886 	uint32_t cts, lost;
4887 
4888 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4889 	cts = tcp_get_usecs(&bbr->rc_tv);
4890 	lost = bbr->r_ctl.rc_lost;
4891 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4892 		bbr_set_state(tp, bbr, 0);
4893 
4894 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4895 		if (rsm->r_flags & BBR_ACKED) {
4896 			uint32_t old_flags;
4897 
4898 			rsm->r_dupack = 0;
4899 			if (rsm->r_in_tmap == 0) {
4900 				/* We must re-add it back to the tlist */
4901 				if (trsm == NULL) {
4902 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4903 				} else {
4904 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4905 				}
4906 				rsm->r_in_tmap = 1;
4907 			}
4908 			old_flags = rsm->r_flags;
4909 			rsm->r_flags |= BBR_RXT_CLEARED;
4910 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4911 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4912 		} else {
4913 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4914 			    (rsm->r_start == tp->snd_una)) {
4915 				/*
4916 				 * Special case for TCP FO. Where
4917 				 * we sent more data beyond the snd_max.
4918 				 * We don't mark that as lost and stop here.
4919 				 */
4920 				break;
4921 			}
4922 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4923 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4924 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4925 			}
4926 			if (bbr_marks_rxt_sack_passed) {
4927 				/*
4928 				 * With this option, we will rack out
4929 				 * in 1ms increments the rest of the packets.
4930 				 */
4931 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4932 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4933 			} else {
4934 				/*
4935 				 * With this option we only mark them lost
4936 				 * and remove all sack'd markings. We will run
4937 				 * another RXT or a TLP. This will cause
4938 				 * us to eventually send more based on what
4939 				 * ack's come in.
4940 				 */
4941 				rsm->r_flags |= BBR_MARKED_LOST;
4942 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4943 				rsm->r_flags &= ~BBR_SACK_PASSED;
4944 			}
4945 		}
4946 		trsm = rsm;
4947 	}
4948 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4949 	/* Clear the count (we just un-acked them) */
4950 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4951 	bbr->rc_tlp_new_data = 0;
4952 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4953 	/* zap the behindness on a rxt */
4954 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4955 	bbr->r_agg_early_set = 0;
4956 	bbr->r_ctl.rc_agg_early = 0;
4957 	bbr->rc_tlp_rtx_out = 0;
4958 	bbr->r_ctl.rc_sacked = 0;
4959 	bbr->r_ctl.rc_sacklast = NULL;
4960 	bbr->r_timer_override = 1;
4961 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4962 }
4963 
4964 /*
4965  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4966  * we will setup to retransmit the lowest seq number outstanding.
4967  */
4968 static int
4969 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4970 {
4971 	struct inpcb *inp = tptoinpcb(tp);
4972 	int32_t rexmt;
4973 	int32_t retval = 0;
4974 	bool isipv6;
4975 
4976 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4977 	if (bbr->rc_all_timers_stopped) {
4978 		return (1);
4979 	}
4980 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4981 	    (tp->snd_una == tp->snd_max)) {
4982 		/* Nothing outstanding .. nothing to do */
4983 		return (0);
4984 	}
4985 	/*
4986 	 * Retransmission timer went off.  Message has not been acked within
4987 	 * retransmit interval.  Back off to a longer retransmit interval
4988 	 * and retransmit one segment.
4989 	 */
4990 	if (ctf_progress_timeout_check(tp, true)) {
4991 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4992 		return (-ETIMEDOUT);	/* tcp_drop() */
4993 	}
4994 	bbr_remxt_tmr(tp);
4995 	if ((bbr->r_ctl.rc_resend == NULL) ||
4996 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4997 		/*
4998 		 * If the rwnd collapsed on
4999 		 * the one we are retransmitting
5000 		 * it does not count against the
5001 		 * rxt count.
5002 		 */
5003 		tp->t_rxtshift++;
5004 	}
5005 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT) {
5006 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
5007 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
5008 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
5009 		/* XXXGL: previously t_softerror was casted to uint16_t */
5010 		MPASS(tp->t_softerror >= 0);
5011 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
5012 		return (retval);	/* tcp_drop() */
5013 	}
5014 	if (tp->t_state == TCPS_SYN_SENT) {
5015 		/*
5016 		 * If the SYN was retransmitted, indicate CWND to be limited
5017 		 * to 1 segment in cc_conn_init().
5018 		 */
5019 		tp->snd_cwnd = 1;
5020 	} else if (tp->t_rxtshift == 1) {
5021 		/*
5022 		 * first retransmit; record ssthresh and cwnd so they can be
5023 		 * recovered if this turns out to be a "bad" retransmit. A
5024 		 * retransmit is considered "bad" if an ACK for this segment
5025 		 * is received within RTT/2 interval; the assumption here is
5026 		 * that the ACK was already in flight.  See "On Estimating
5027 		 * End-to-End Network Path Properties" by Allman and Paxson
5028 		 * for more details.
5029 		 */
5030 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5031 		if (!IN_RECOVERY(tp->t_flags)) {
5032 			tp->snd_cwnd_prev = tp->snd_cwnd;
5033 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5034 			tp->snd_recover_prev = tp->snd_recover;
5035 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5036 			tp->t_flags |= TF_PREVVALID;
5037 		} else {
5038 			tp->t_flags &= ~TF_PREVVALID;
5039 		}
5040 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5041 	} else {
5042 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5043 		tp->t_flags &= ~TF_PREVVALID;
5044 	}
5045 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5046 	if ((tp->t_state == TCPS_SYN_SENT) ||
5047 	    (tp->t_state == TCPS_SYN_RECEIVED))
5048 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5049 	else
5050 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5051 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5052 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5053 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5054 	/*
5055 	 * We enter the path for PLMTUD if connection is established or, if
5056 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5057 	 * amount of data we send is very small, we could send it in couple
5058 	 * of packets and process straight to FIN. In that case we won't
5059 	 * catch ESTABLISHED state.
5060 	 */
5061 #ifdef INET6
5062 	isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
5063 #else
5064 	isipv6 = false;
5065 #endif
5066 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5067 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5068 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5069 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5070 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5071 		/*
5072 		 * Idea here is that at each stage of mtu probe (usually,
5073 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5074 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5075 		 * should take care of that.
5076 		 */
5077 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5078 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5079 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5080 		    tp->t_rxtshift % 2 == 0)) {
5081 			/*
5082 			 * Enter Path MTU Black-hole Detection mechanism: -
5083 			 * Disable Path MTU Discovery (IP "DF" bit). -
5084 			 * Reduce MTU to lower value than what we negotiated
5085 			 * with peer.
5086 			 */
5087 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5088 				/*
5089 				 * Record that we may have found a black
5090 				 * hole.
5091 				 */
5092 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5093 				/* Keep track of previous MSS. */
5094 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5095 			}
5096 			/*
5097 			 * Reduce the MSS to blackhole value or to the
5098 			 * default in an attempt to retransmit.
5099 			 */
5100 #ifdef INET6
5101 			isipv6 = bbr->r_is_v6;
5102 			if (isipv6 &&
5103 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5104 				/* Use the sysctl tuneable blackhole MSS. */
5105 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5106 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5107 			} else if (isipv6) {
5108 				/* Use the default MSS. */
5109 				tp->t_maxseg = V_tcp_v6mssdflt;
5110 				/*
5111 				 * Disable Path MTU Discovery when we switch
5112 				 * to minmss.
5113 				 */
5114 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5115 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5116 			}
5117 #endif
5118 #if defined(INET6) && defined(INET)
5119 			else
5120 #endif
5121 #ifdef INET
5122 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5123 				/* Use the sysctl tuneable blackhole MSS. */
5124 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5125 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5126 			} else {
5127 				/* Use the default MSS. */
5128 				tp->t_maxseg = V_tcp_mssdflt;
5129 				/*
5130 				 * Disable Path MTU Discovery when we switch
5131 				 * to minmss.
5132 				 */
5133 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5134 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5135 			}
5136 #endif
5137 		} else {
5138 			/*
5139 			 * If further retransmissions are still unsuccessful
5140 			 * with a lowered MTU, maybe this isn't a blackhole
5141 			 * and we restore the previous MSS and blackhole
5142 			 * detection flags. The limit '6' is determined by
5143 			 * giving each probe stage (1448, 1188, 524) 2
5144 			 * chances to recover.
5145 			 */
5146 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5147 			    (tp->t_rxtshift >= 6)) {
5148 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5149 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5150 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5151 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5152 			}
5153 		}
5154 	}
5155 	/*
5156 	 * Disable RFC1323 and SACK if we haven't got any response to our
5157 	 * third SYN to work-around some broken terminal servers (most of
5158 	 * which have hopefully been retired) that have bad VJ header
5159 	 * compression code which trashes TCP segments containing
5160 	 * unknown-to-them TCP options.
5161 	 */
5162 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5163 	    (tp->t_rxtshift == 3))
5164 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5165 	/*
5166 	 * If we backed off this far, our srtt estimate is probably bogus.
5167 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5168 	 * move the current srtt into rttvar to keep the current retransmit
5169 	 * times until then.
5170 	 */
5171 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5172 #ifdef INET6
5173 		if (bbr->r_is_v6)
5174 			in6_losing(inp);
5175 		else
5176 #endif
5177 			in_losing(inp);
5178 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5179 		tp->t_srtt = 0;
5180 	}
5181 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5182 	tp->snd_recover = tp->snd_max;
5183 	tp->t_flags |= TF_ACKNOW;
5184 	tp->t_rtttime = 0;
5185 
5186 	return (retval);
5187 }
5188 
5189 static int
5190 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5191 {
5192 	int32_t ret = 0;
5193 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5194 
5195 	if (timers == 0) {
5196 		return (0);
5197 	}
5198 	if (tp->t_state == TCPS_LISTEN) {
5199 		/* no timers on listen sockets */
5200 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5201 			return (0);
5202 		return (1);
5203 	}
5204 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5205 		uint32_t left;
5206 
5207 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5208 			ret = -1;
5209 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5210 			return (0);
5211 		}
5212 		if (hpts_calling == 0) {
5213 			ret = -2;
5214 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5215 			return (0);
5216 		}
5217 		/*
5218 		 * Ok our timer went off early and we are not paced false
5219 		 * alarm, go back to sleep.
5220 		 */
5221 		left = bbr->r_ctl.rc_timer_exp - cts;
5222 		ret = -3;
5223 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5224 		tcp_hpts_insert(tptoinpcb(tp), HPTS_USEC_TO_SLOTS(left));
5225 		return (1);
5226 	}
5227 	bbr->rc_tmr_stopped = 0;
5228 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5229 	if (timers & PACE_TMR_DELACK) {
5230 		ret = bbr_timeout_delack(tp, bbr, cts);
5231 	} else if (timers & PACE_TMR_PERSIT) {
5232 		ret = bbr_timeout_persist(tp, bbr, cts);
5233 	} else if (timers & PACE_TMR_RACK) {
5234 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5235 		ret = bbr_timeout_rack(tp, bbr, cts);
5236 	} else if (timers & PACE_TMR_TLP) {
5237 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5238 		ret = bbr_timeout_tlp(tp, bbr, cts);
5239 	} else if (timers & PACE_TMR_RXT) {
5240 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5241 		ret = bbr_timeout_rxt(tp, bbr, cts);
5242 	} else if (timers & PACE_TMR_KEEP) {
5243 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5244 	}
5245 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5246 	return (ret);
5247 }
5248 
5249 static void
5250 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5251 {
5252 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5253 		uint8_t hpts_removed = 0;
5254 
5255 		if (tcp_in_hpts(bbr->rc_inp) &&
5256 		    (bbr->rc_timer_first == 1)) {
5257 			/*
5258 			 * If we are canceling timer's when we have the
5259 			 * timer ahead of the output being paced. We also
5260 			 * must remove ourselves from the hpts.
5261 			 */
5262 			hpts_removed = 1;
5263 			tcp_hpts_remove(bbr->rc_inp);
5264 			if (bbr->r_ctl.rc_last_delay_val) {
5265 				/* Update the last hptsi delay too */
5266 				uint32_t time_since_send;
5267 
5268 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5269 					time_since_send = cts - bbr->rc_pacer_started;
5270 				else
5271 					time_since_send = 0;
5272 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5273 					/* Cut down our slot time */
5274 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5275 				} else {
5276 					bbr->r_ctl.rc_last_delay_val = 0;
5277 				}
5278 				bbr->rc_pacer_started = cts;
5279 			}
5280 		}
5281 		bbr->rc_timer_first = 0;
5282 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5283 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5284 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5285 	}
5286 }
5287 
5288 static int
5289 bbr_stopall(struct tcpcb *tp)
5290 {
5291 	struct tcp_bbr *bbr;
5292 
5293 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5294 	bbr->rc_all_timers_stopped = 1;
5295 	return (0);
5296 }
5297 
5298 static uint32_t
5299 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5300 {
5301 	struct bbr_sendmap *rsm;
5302 
5303 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5304 	if ((rsm == NULL) || (u_rsm == rsm))
5305 		return (cts);
5306 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5307 }
5308 
5309 static void
5310 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5311      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5312 {
5313 	int32_t idx;
5314 
5315 	rsm->r_rtr_cnt++;
5316 	rsm->r_dupack = 0;
5317 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5318 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5319 		rsm->r_flags |= BBR_OVERMAX;
5320 	}
5321 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5322 		/* Take off the collapsed flag at rxt */
5323 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5324 	}
5325 	if (rsm->r_flags & BBR_MARKED_LOST) {
5326 		/* We have retransmitted, its no longer lost */
5327 		rsm->r_flags &= ~BBR_MARKED_LOST;
5328 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5329 	}
5330 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5331 		/*
5332 		 * We hit a RXT timer on it and
5333 		 * we cleared the "acked" flag.
5334 		 * We now have it going back into
5335 		 * flight, we can remove the cleared
5336 		 * flag and possibly do accounting on
5337 		 * this piece.
5338 		 */
5339 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5340 	}
5341 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5342 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5343 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5344 	}
5345 	idx = rsm->r_rtr_cnt - 1;
5346 	rsm->r_tim_lastsent[idx] = cts;
5347 	rsm->r_pacing_delay = pacing_time;
5348 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5349 	rsm->r_ts_valid = bbr->rc_ts_valid;
5350 	if (bbr->rc_ts_valid)
5351 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5352 	if (bbr->r_ctl.r_app_limited_until)
5353 		rsm->r_app_limited = 1;
5354 	else
5355 		rsm->r_app_limited = 0;
5356 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5357 		rsm->r_bbr_state = bbr_state_val(bbr);
5358 	else
5359 		rsm->r_bbr_state = 8;
5360 	if (rsm->r_flags & BBR_ACKED) {
5361 		/* Problably MTU discovery messing with us */
5362 		uint32_t old_flags;
5363 
5364 		old_flags = rsm->r_flags;
5365 		rsm->r_flags &= ~BBR_ACKED;
5366 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5367 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5368 		if (bbr->r_ctl.rc_sacked == 0)
5369 			bbr->r_ctl.rc_sacklast = NULL;
5370 	}
5371 	if (rsm->r_in_tmap) {
5372 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5373 	}
5374 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5375 	rsm->r_in_tmap = 1;
5376 	if (rsm->r_flags & BBR_SACK_PASSED) {
5377 		/* We have retransmitted due to the SACK pass */
5378 		rsm->r_flags &= ~BBR_SACK_PASSED;
5379 		rsm->r_flags |= BBR_WAS_SACKPASS;
5380 	}
5381 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5382 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5383 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5384 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5385 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5386 		rsm->r_is_gain = 1;
5387 		rsm->r_is_drain = 0;
5388 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5389 		rsm->r_is_drain = 1;
5390 		rsm->r_is_gain = 0;
5391 	} else {
5392 		rsm->r_is_drain = 0;
5393 		rsm->r_is_gain = 0;
5394 	}
5395 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5396 }
5397 
5398 /*
5399  * Returns 0, or the sequence where we stopped
5400  * updating. We also update the lenp to be the amount
5401  * of data left.
5402  */
5403 
5404 static uint32_t
5405 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5406     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5407 {
5408 	/*
5409 	 * We (re-)transmitted starting at rsm->r_start for some length
5410 	 * (possibly less than r_end.
5411 	 */
5412 	struct bbr_sendmap *nrsm;
5413 	uint32_t c_end;
5414 	int32_t len;
5415 
5416 	len = *lenp;
5417 	c_end = rsm->r_start + len;
5418 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5419 		/*
5420 		 * We retransmitted the whole piece or more than the whole
5421 		 * slopping into the next rsm.
5422 		 */
5423 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5424 		if (c_end == rsm->r_end) {
5425 			*lenp = 0;
5426 			return (0);
5427 		} else {
5428 			int32_t act_len;
5429 
5430 			/* Hangs over the end return whats left */
5431 			act_len = rsm->r_end - rsm->r_start;
5432 			*lenp = (len - act_len);
5433 			return (rsm->r_end);
5434 		}
5435 		/* We don't get out of this block. */
5436 	}
5437 	/*
5438 	 * Here we retransmitted less than the whole thing which means we
5439 	 * have to split this into what was transmitted and what was not.
5440 	 */
5441 	nrsm = bbr_alloc_full_limit(bbr);
5442 	if (nrsm == NULL) {
5443 		*lenp = 0;
5444 		return (0);
5445 	}
5446 	/*
5447 	 * So here we are going to take the original rsm and make it what we
5448 	 * retransmitted. nrsm will be the tail portion we did not
5449 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5450 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5451 	 * 1, 6 and the new piece will be 6, 11.
5452 	 */
5453 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5454 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5455 	nrsm->r_dupack = 0;
5456 	if (rsm->r_in_tmap) {
5457 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5458 		nrsm->r_in_tmap = 1;
5459 	}
5460 	rsm->r_flags &= (~BBR_HAS_FIN);
5461 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5462 	*lenp = 0;
5463 	return (0);
5464 }
5465 
5466 static uint64_t
5467 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5468 {
5469 	uint64_t bw;
5470 
5471 	bw = bbr_get_bw(bbr);
5472 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5473 	bw /= (uint64_t)BBR_UNIT;
5474 	return(bw);
5475 }
5476 
5477 static void
5478 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5479 		       uint64_t act_rate, uint64_t rate_wanted)
5480 {
5481 	/*
5482 	 * We could not get a full gains worth
5483 	 * of rate.
5484 	 */
5485 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5486 		/* we can't even get the real rate */
5487 		uint64_t red;
5488 
5489 		bbr->skip_gain = 1;
5490 		bbr->gain_is_limited = 0;
5491 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5492 		if (red)
5493 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5494 	} else {
5495 		/* We can use a lower gain */
5496 		bbr->skip_gain = 0;
5497 		bbr->gain_is_limited = 1;
5498 	}
5499 }
5500 
5501 static void
5502 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5503 {
5504 	const struct tcp_hwrate_limit_table *nrte;
5505 	int error, rate = -1;
5506 
5507 	if (bbr->r_ctl.crte == NULL)
5508 		return;
5509 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5510 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5511 		/* Lost our routes? */
5512 		/* Clear the way for a re-attempt */
5513 		bbr->bbr_attempt_hdwr_pace = 0;
5514 lost_rate:
5515 		bbr->gain_is_limited = 0;
5516 		bbr->skip_gain = 0;
5517 		bbr->bbr_hdrw_pacing = 0;
5518 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5519 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5520 		tcp_bbr_tso_size_check(bbr, cts);
5521 		return;
5522 	}
5523 	rate = bbr_get_hardware_rate(bbr);
5524 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5525 				   bbr->rc_tp,
5526 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5527 				   rate,
5528 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5529 				   &error, NULL);
5530 	if (nrte == NULL) {
5531 		goto lost_rate;
5532 	}
5533 	if (nrte != bbr->r_ctl.crte) {
5534 		bbr->r_ctl.crte = nrte;
5535 		if (error == 0)  {
5536 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5537 			if (bbr->r_ctl.crte->rate < rate) {
5538 				/* We have a problem */
5539 				bbr_setup_less_of_rate(bbr, cts,
5540 						       bbr->r_ctl.crte->rate, rate);
5541 			} else {
5542 				/* We are good */
5543 				bbr->gain_is_limited = 0;
5544 				bbr->skip_gain = 0;
5545 			}
5546 		} else {
5547 			/* A failure should release the tag */
5548 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5549 			bbr->gain_is_limited = 0;
5550 			bbr->skip_gain = 0;
5551 			bbr->bbr_hdrw_pacing = 0;
5552 		}
5553 		bbr_type_log_hdwr_pacing(bbr,
5554 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5555 					 rate,
5556 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5557 					 __LINE__,
5558 					 cts,
5559 					 error);
5560 	}
5561 }
5562 
5563 static void
5564 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5565 {
5566 	/*
5567 	 * If we have hardware pacing support
5568 	 * we need to factor that in for our
5569 	 * TSO size.
5570 	 */
5571 	const struct tcp_hwrate_limit_table *rlp;
5572 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5573 
5574 	if ((bbr->bbr_hdrw_pacing == 0) ||
5575 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5576 	    (bbr->r_ctl.crte == NULL))
5577 		return;
5578 	if (bbr->hw_pacing_set == 0) {
5579 		/* Not yet by the hdwr pacing count delay */
5580 		return;
5581 	}
5582 	if (bbr_hdwr_pace_adjust == 0) {
5583 		/* No adjustment */
5584 		return;
5585 	}
5586 	rlp = bbr->r_ctl.crte;
5587 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5588 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5589 	else
5590 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5591 	/*
5592 	 * So lets first get the
5593 	 * time we will take between
5594 	 * TSO sized sends currently without
5595 	 * hardware help.
5596 	 */
5597 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5598 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5599 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5600 	hdwr_delay *= rlp->time_between;
5601 	if (cur_delay > hdwr_delay)
5602 		delta = cur_delay - hdwr_delay;
5603 	else
5604 		delta = 0;
5605 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5606 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5607 			     1);
5608 	if (delta &&
5609 	    (delta < (max(rlp->time_between,
5610 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5611 		/*
5612 		 * Now lets divide by the pacing
5613 		 * time between each segment the
5614 		 * hardware sends rounding up and
5615 		 * derive a bytes from that. We multiply
5616 		 * that by bbr_hdwr_pace_adjust to get
5617 		 * more bang for our buck.
5618 		 *
5619 		 * The goal is to have the software pacer
5620 		 * waiting no more than an additional
5621 		 * pacing delay if we can (without the
5622 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5623 		 */
5624 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5625 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5626 		seg_sz *= bbr_hdwr_pace_adjust;
5627 		if (bbr_hdwr_pace_floor &&
5628 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5629 			/* Currently hardware paces
5630 			 * out rs_min_seg segments at a time.
5631 			 * We need to make sure we always send at least
5632 			 * a full burst of bbr_hdwr_pace_floor down.
5633 			 */
5634 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5635 		}
5636 		seg_sz *= maxseg;
5637 	} else if (delta == 0) {
5638 		/*
5639 		 * The highest pacing rate is
5640 		 * above our b/w gained. This means
5641 		 * we probably are going quite fast at
5642 		 * the hardware highest rate. Lets just multiply
5643 		 * the calculated TSO size by the
5644 		 * multiplier factor (its probably
5645 		 * 4 segments in the default config for
5646 		 * mlx).
5647 		 */
5648 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5649 		if (bbr_hdwr_pace_floor &&
5650 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5651 			/* Currently hardware paces
5652 			 * out rs_min_seg segments at a time.
5653 			 * We need to make sure we always send at least
5654 			 * a full burst of bbr_hdwr_pace_floor down.
5655 			 */
5656 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5657 		}
5658 	} else {
5659 		/*
5660 		 * The pacing time difference is so
5661 		 * big that the hardware will
5662 		 * pace out more rapidly then we
5663 		 * really want and then we
5664 		 * will have a long delay. Lets just keep
5665 		 * the same TSO size so its as if
5666 		 * we were not using hdwr pacing (we
5667 		 * just gain a bit of spacing from the
5668 		 * hardware if seg_sz > 1).
5669 		 */
5670 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5671 	}
5672 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5673 		new_tso = seg_sz;
5674 	else
5675 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5676 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5677 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5678 
5679 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5680 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5681 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5682 	}
5683 }
5684 
5685 static void
5686 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5687 {
5688 	uint64_t bw;
5689 	uint32_t old_tso = 0, new_tso;
5690 	uint32_t maxseg, bytes;
5691 	uint32_t tls_seg=0;
5692 	/*
5693 	 * Google/linux uses the following algorithm to determine
5694 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5695 	 *
5696 	 *  bytes = bw_in_bytes_per_second / 1000
5697 	 *  bytes = min(bytes, 64k)
5698 	 *  tso_segs = bytes / MSS
5699 	 *  if (bw < 1.2Mbs)
5700 	 *      min_tso_segs = 1
5701 	 *  else
5702 	 *	min_tso_segs = 2
5703 	 * tso_segs = max(tso_segs, min_tso_segs)
5704 	 *
5705 	 * * Note apply a device specific limit (we apply this in the
5706 	 *   tcp_m_copym).
5707 	 * Note that before the initial measurement is made google bursts out
5708 	 * a full iwnd just like new-reno/cubic.
5709 	 *
5710 	 * We do not use this algorithm. Instead we
5711 	 * use a two phased approach:
5712 	 *
5713 	 *  if ( bw <= per-tcb-cross-over)
5714 	 *     goal_tso =  calculate how much with this bw we
5715 	 *                 can send in goal-time seconds.
5716 	 *     if (goal_tso > mss)
5717 	 *         seg = goal_tso / mss
5718 	 *         tso = seg * mss
5719 	 *     else
5720 	 *         tso = mss
5721 	 *     if (tso > per-tcb-max)
5722 	 *         tso = per-tcb-max
5723 	 *  else if ( bw > 512Mbps)
5724 	 *     tso = max-tso (64k/mss)
5725 	 *  else
5726 	 *     goal_tso = bw / per-tcb-divsor
5727 	 *     seg = (goal_tso + mss-1)/mss
5728 	 *     tso = seg * mss
5729 	 *
5730 	 * if (tso < per-tcb-floor)
5731 	 *    tso = per-tcb-floor
5732 	 * if (tso > per-tcb-utter_max)
5733 	 *    tso = per-tcb-utter_max
5734 	 *
5735 	 * Note the default per-tcb-divisor is 1000 (same as google).
5736 	 * the goal cross over is 30Mbps however. To recreate googles
5737 	 * algorithm you need to set:
5738 	 *
5739 	 * cross-over = 23,168,000 bps
5740 	 * goal-time = 18000
5741 	 * per-tcb-max = 2
5742 	 * per-tcb-divisor = 1000
5743 	 * per-tcb-floor = 1
5744 	 *
5745 	 * This will get you "google bbr" behavior with respect to tso size.
5746 	 *
5747 	 * Note we do set anything TSO size until we are past the initial
5748 	 * window. Before that we gnerally use either a single MSS
5749 	 * or we use the full IW size (so we burst a IW at a time)
5750 	 */
5751 
5752 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5753 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5754 	} else {
5755 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5756 	}
5757 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5758 	if (bbr->rc_past_init_win == 0) {
5759 		/*
5760 		 * Not enough data has been acknowledged to make a
5761 		 * judgement. Set up the initial TSO based on if we
5762 		 * are sending a full IW at once or not.
5763 		 */
5764 		if (bbr->rc_use_google)
5765 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5766 		else if (bbr->bbr_init_win_cheat)
5767 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5768 		else
5769 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5770 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5771 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5772 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5773 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5774 		}
5775 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5776 			bbr_adjust_for_hw_pacing(bbr, cts);
5777 		return;
5778 	}
5779 	/**
5780 	 * Now lets set the TSO goal based on our delivery rate in
5781 	 * bytes per second. Note we only do this if
5782 	 * we have acked at least the initial cwnd worth of data.
5783 	 */
5784 	bw = bbr_get_bw(bbr);
5785 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5786 	     (bbr->rc_use_google == 0)) {
5787 		/* We clamp to one MSS in recovery */
5788 		new_tso = maxseg;
5789 	} else if (bbr->rc_use_google) {
5790 		int min_tso_segs;
5791 
5792 		/* Google considers the gain too */
5793 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5794 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5795 			bw /= BBR_UNIT;
5796 		}
5797 		bytes = bw / 1024;
5798 		if (bytes > (64 * 1024))
5799 			bytes = 64 * 1024;
5800 		new_tso = bytes / maxseg;
5801 		if (bw < ONE_POINT_TWO_MEG)
5802 			min_tso_segs = 1;
5803 		else
5804 			min_tso_segs = 2;
5805 		if (new_tso < min_tso_segs)
5806 			new_tso = min_tso_segs;
5807 		new_tso *= maxseg;
5808 	} else if (bbr->rc_no_pacing) {
5809 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5810 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5811 		/*
5812 		 * Calculate the worse case b/w TSO if we are inserting no
5813 		 * more than a delay_target number of TSO's.
5814 		 */
5815 		uint32_t tso_len, min_tso;
5816 
5817 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5818 		if (tso_len > maxseg) {
5819 			new_tso = tso_len / maxseg;
5820 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5821 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5822 			new_tso *= maxseg;
5823 		} else {
5824 			/*
5825 			 * less than a full sized frame yikes.. long rtt or
5826 			 * low bw?
5827 			 */
5828 			min_tso = bbr_minseg(bbr);
5829 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5830 				new_tso = rounddown(tso_len, min_tso);
5831 			else
5832 				new_tso = min_tso;
5833 		}
5834 	} else if (bw > FIVETWELVE_MBPS) {
5835 		/*
5836 		 * This guy is so fast b/w wise that we can TSO as large as
5837 		 * possible of segments that the NIC will allow.
5838 		 */
5839 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5840 	} else {
5841 		/*
5842 		 * This formula is based on attempting to send a segment or
5843 		 * more every bbr_hptsi_per_second. The default is 1000
5844 		 * which means you are targeting what you can send every 1ms
5845 		 * based on the peers bw.
5846 		 *
5847 		 * If the number drops to say 500, then you are looking more
5848 		 * at 2ms and you will raise how much we send in a single
5849 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5850 		 * trade off of course is you will send more at once and
5851 		 * thus tend to clump up the sends into larger "bursts"
5852 		 * building a queue.
5853 		 */
5854 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5855 		new_tso = roundup(bw, (uint64_t)maxseg);
5856 		/*
5857 		 * Gate the floor to match what our lower than 48Mbps
5858 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5859 		 * becomes the floor for this calculation.
5860 		 */
5861 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5862 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5863 	}
5864 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5865 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5866 	if (new_tso > PACE_MAX_IP_BYTES)
5867 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5868 	/* Enforce an utter maximum. */
5869 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5870 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5871 	}
5872 	if (old_tso != new_tso) {
5873 		/* Only log changes */
5874 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5875 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5876 	}
5877 	/* We have hardware pacing! */
5878 	bbr_adjust_for_hw_pacing(bbr, cts);
5879 }
5880 
5881 static void
5882 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5883     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5884     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5885     struct sockbuf *sb)
5886 {
5887 
5888 	struct bbr_sendmap *rsm, *nrsm;
5889 	register uint32_t snd_max, snd_una;
5890 	uint32_t pacing_time;
5891 	/*
5892 	 * Add to the RACK log of packets in flight or retransmitted. If
5893 	 * there is a TS option we will use the TS echoed, if not we will
5894 	 * grab a TS.
5895 	 *
5896 	 * Retransmissions will increment the count and move the ts to its
5897 	 * proper place. Note that if options do not include TS's then we
5898 	 * won't be able to effectively use the ACK for an RTT on a retran.
5899 	 *
5900 	 * Notes about r_start and r_end. Lets consider a send starting at
5901 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5902 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5903 	 * This means that r_end is actually the first sequence for the next
5904 	 * slot (11).
5905 	 *
5906 	 */
5907 	INP_WLOCK_ASSERT(tptoinpcb(tp));
5908 	if (err) {
5909 		/*
5910 		 * We don't log errors -- we could but snd_max does not
5911 		 * advance in this case either.
5912 		 */
5913 		return;
5914 	}
5915 	if (th_flags & TH_RST) {
5916 		/*
5917 		 * We don't log resets and we return immediately from
5918 		 * sending
5919 		 */
5920 		*abandon = 1;
5921 		return;
5922 	}
5923 	snd_una = tp->snd_una;
5924 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5925 		/*
5926 		 * The call to bbr_log_output is made before bumping
5927 		 * snd_max. This means we can record one extra byte on a SYN
5928 		 * or FIN if seq_out is adding more on and a FIN is present
5929 		 * (and we are not resending).
5930 		 */
5931 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5932 			len++;
5933 		if (th_flags & TH_FIN)
5934 			len++;
5935 	}
5936 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5937 		/* Are sending an old segment to induce an ack (keep-alive)? */
5938 		return;
5939 	}
5940 	if (SEQ_LT(seq_out, snd_una)) {
5941 		/* huh? should we panic? */
5942 		uint32_t end;
5943 
5944 		end = seq_out + len;
5945 		seq_out = snd_una;
5946 		len = end - seq_out;
5947 	}
5948 	snd_max = tp->snd_max;
5949 	if (len == 0) {
5950 		/* We don't log zero window probes */
5951 		return;
5952 	}
5953 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5954 	/* First question is it a retransmission? */
5955 	if (seq_out == snd_max) {
5956 again:
5957 		rsm = bbr_alloc(bbr);
5958 		if (rsm == NULL) {
5959 			return;
5960 		}
5961 		rsm->r_flags = 0;
5962 		if (th_flags & TH_SYN)
5963 			rsm->r_flags |= BBR_HAS_SYN;
5964 		if (th_flags & TH_FIN)
5965 			rsm->r_flags |= BBR_HAS_FIN;
5966 		rsm->r_tim_lastsent[0] = cts;
5967 		rsm->r_rtr_cnt = 1;
5968 		rsm->r_rtr_bytes = 0;
5969 		rsm->r_start = seq_out;
5970 		rsm->r_end = rsm->r_start + len;
5971 		rsm->r_dupack = 0;
5972 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5973 		rsm->r_pacing_delay = pacing_time;
5974 		rsm->r_ts_valid = bbr->rc_ts_valid;
5975 		if (bbr->rc_ts_valid)
5976 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5977 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
5978 		if (bbr->r_ctl.r_app_limited_until)
5979 			rsm->r_app_limited = 1;
5980 		else
5981 			rsm->r_app_limited = 0;
5982 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5983 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5984 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5985 		/*
5986 		 * Here we must also add in this rsm since snd_max
5987 		 * is updated after we return from a new send.
5988 		 */
5989 		rsm->r_flight_at_send += len;
5990 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
5991 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5992 		rsm->r_in_tmap = 1;
5993 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5994 			rsm->r_bbr_state = bbr_state_val(bbr);
5995 		else
5996 			rsm->r_bbr_state = 8;
5997 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5998 			rsm->r_is_gain = 1;
5999 			rsm->r_is_drain = 0;
6000 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6001 			rsm->r_is_drain = 1;
6002 			rsm->r_is_gain = 0;
6003 		} else {
6004 			rsm->r_is_drain = 0;
6005 			rsm->r_is_gain = 0;
6006 		}
6007 		return;
6008 	}
6009 	/*
6010 	 * If we reach here its a retransmission and we need to find it.
6011 	 */
6012 more:
6013 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6014 		rsm = hintrsm;
6015 		hintrsm = NULL;
6016 	} else if (bbr->r_ctl.rc_next) {
6017 		/* We have a hint from a previous run */
6018 		rsm = bbr->r_ctl.rc_next;
6019 	} else {
6020 		/* No hints sorry */
6021 		rsm = NULL;
6022 	}
6023 	if ((rsm) && (rsm->r_start == seq_out)) {
6024 		/*
6025 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6026 		 * likely case.
6027 		 */
6028 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6029 		if (len == 0) {
6030 			return;
6031 		} else {
6032 			goto more;
6033 		}
6034 	}
6035 	/* Ok it was not the last pointer go through it the hard way. */
6036 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6037 		if (rsm->r_start == seq_out) {
6038 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6039 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6040 			if (len == 0) {
6041 				return;
6042 			} else {
6043 				continue;
6044 			}
6045 		}
6046 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6047 			/* Transmitted within this piece */
6048 			/*
6049 			 * Ok we must split off the front and then let the
6050 			 * update do the rest
6051 			 */
6052 			nrsm = bbr_alloc_full_limit(bbr);
6053 			if (nrsm == NULL) {
6054 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6055 				return;
6056 			}
6057 			/*
6058 			 * copy rsm to nrsm and then trim the front of rsm
6059 			 * to not include this part.
6060 			 */
6061 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6062 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6063 			if (rsm->r_in_tmap) {
6064 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6065 				nrsm->r_in_tmap = 1;
6066 			}
6067 			rsm->r_flags &= (~BBR_HAS_FIN);
6068 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6069 			if (len == 0) {
6070 				return;
6071 			}
6072 		}
6073 	}
6074 	/*
6075 	 * Hmm not found in map did they retransmit both old and on into the
6076 	 * new?
6077 	 */
6078 	if (seq_out == tp->snd_max) {
6079 		goto again;
6080 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6081 #ifdef BBR_INVARIANTS
6082 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6083 		    seq_out, len, tp->snd_una, tp->snd_max);
6084 		printf("Starting Dump of all rack entries\n");
6085 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6086 			printf("rsm:%p start:%u end:%u\n",
6087 			    rsm, rsm->r_start, rsm->r_end);
6088 		}
6089 		printf("Dump complete\n");
6090 		panic("seq_out not found rack:%p tp:%p",
6091 		    bbr, tp);
6092 #endif
6093 	} else {
6094 #ifdef BBR_INVARIANTS
6095 		/*
6096 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6097 		 * flag)
6098 		 */
6099 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6100 		    seq_out, len, tp->snd_max, tp);
6101 #endif
6102 	}
6103 }
6104 
6105 static void
6106 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6107 {
6108 	/*
6109 	 * Collapse timeout back the cum-ack moved.
6110 	 */
6111 	tp->t_rxtshift = 0;
6112 	tp->t_softerror = 0;
6113 }
6114 
6115 static void
6116 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6117 {
6118 	bbr->rtt_valid = 1;
6119 	bbr->r_ctl.cur_rtt = rtt_usecs;
6120 	bbr->r_ctl.ts_in = tsin;
6121 	if (rsm_send_time)
6122 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6123 }
6124 
6125 static void
6126 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6127 {
6128 	/**
6129 	 * We have in our bbr control:
6130 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6131 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6132 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6133 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6134 	 *
6135 	 * Now we can calculate the time between the sends by doing:
6136 	 *
6137 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6138 	 *
6139 	 * And the peer's time between receiving them by doing:
6140 	 *
6141 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6142 	 *
6143 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6144 	 * We also may find that we can't use the timestamps if say we see
6145 	 * that the peer_delta indicates that though we may have taken 10ms to
6146 	 * pace out the data, it only saw 1ms between the two packets. This would
6147 	 * indicate that somewhere on the path is a batching entity that is giving
6148 	 * out time-slices of the actual b/w. This would mean we could not use
6149 	 * reliably the peers timestamps.
6150 	 *
6151 	 * We expect delta > peer_delta initially. Until we figure out the
6152 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6153 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6154 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6155 	 * put a 1 there. If the value is faster then ours, we will disable the
6156 	 * use of timestamps (though we could revist this later if we find it to be not
6157 	 * just an isolated one or two flows)).
6158 	 *
6159 	 * To detect the batching middle boxes we will come up with our compensation and
6160 	 * if with it in place, we find the peer is drastically off (by some margin) in
6161 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6162 	 *
6163 	 */
6164 	uint64_t delta, peer_delta, delta_up;
6165 
6166 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6167 	if (delta < bbr_min_usec_delta) {
6168 		/*
6169 		 * Have not seen a min amount of time
6170 		 * between our send times so we can
6171 		 * make a determination of the timestamp
6172 		 * yet.
6173 		 */
6174 		return;
6175 	}
6176 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6177 	if (peer_delta < bbr_min_peer_delta) {
6178 		/*
6179 		 * We may have enough in the form of
6180 		 * our delta but the peers number
6181 		 * has not changed that much. It could
6182 		 * be its clock ratio is such that
6183 		 * we need more data (10ms tick) or
6184 		 * there may be other compression scenarios
6185 		 * going on. In any event we need the
6186 		 * spread to be larger.
6187 		 */
6188 		return;
6189 	}
6190 	/* Ok lets first see which way our delta is going */
6191 	if (peer_delta > delta) {
6192 		/* Very unlikely, the peer without
6193 		 * compensation shows that it saw
6194 		 * the two sends arrive further apart
6195 		 * then we saw then in micro-seconds.
6196 		 */
6197 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6198 			/* well it looks like the peer is a micro-second clock. */
6199 			bbr->rc_ts_clock_set = 1;
6200 			bbr->r_ctl.bbr_peer_tsratio = 1;
6201 		} else {
6202 			bbr->rc_ts_cant_be_used = 1;
6203 			bbr->rc_ts_clock_set = 1;
6204 		}
6205 		return;
6206 	}
6207 	/* Ok we know that the peer_delta is smaller than our send distance */
6208 	bbr->rc_ts_clock_set = 1;
6209 	/* First question is it within the percentage that they are using usec time? */
6210 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6211 	if ((peer_delta + delta_up) >= delta) {
6212 		/* Its a usec clock */
6213 		bbr->r_ctl.bbr_peer_tsratio = 1;
6214 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6215 		return;
6216 	}
6217 	/* Ok if not usec, what about 10usec (though unlikely)? */
6218 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6219 	if (((peer_delta * 10) + delta_up) >= delta) {
6220 		bbr->r_ctl.bbr_peer_tsratio = 10;
6221 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6222 		return;
6223 	}
6224 	/* And what about 100usec (though again unlikely)? */
6225 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6226 	if (((peer_delta * 100) + delta_up) >= delta) {
6227 		bbr->r_ctl.bbr_peer_tsratio = 100;
6228 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6229 		return;
6230 	}
6231 	/* And how about 1 msec (the most likely one)? */
6232 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6233 	if (((peer_delta * 1000) + delta_up) >= delta) {
6234 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6235 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6236 		return;
6237 	}
6238 	/* Ok if not msec could it be 10 msec? */
6239 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6240 	if (((peer_delta * 10000) + delta_up) >= delta) {
6241 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6242 		return;
6243 	}
6244 	/* If we fall down here the clock tick so slowly we can't use it */
6245 	bbr->rc_ts_cant_be_used = 1;
6246 	bbr->r_ctl.bbr_peer_tsratio = 0;
6247 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6248 }
6249 
6250 /*
6251  * Collect new round-trip time estimate
6252  * and update averages and current timeout.
6253  */
6254 static void
6255 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6256 {
6257 	int32_t delta;
6258 	uint32_t rtt, tsin;
6259 	int32_t rtt_ticks;
6260 
6261 	if (bbr->rtt_valid == 0)
6262 		/* No valid sample */
6263 		return;
6264 
6265 	rtt = bbr->r_ctl.cur_rtt;
6266 	tsin = bbr->r_ctl.ts_in;
6267 	if (bbr->rc_prtt_set_ts) {
6268 		/*
6269 		 * We are to force feed the rttProp filter due
6270 		 * to an entry into PROBE_RTT. This assures
6271 		 * that the times are sync'd between when we
6272 		 * go into PROBE_RTT and the filter expiration.
6273 		 *
6274 		 * Google does not use a true filter, so they do
6275 		 * this implicitly since they only keep one value
6276 		 * and when they enter probe-rtt they update the
6277 		 * value to the newest rtt.
6278 		 */
6279 		uint32_t rtt_prop;
6280 
6281 		bbr->rc_prtt_set_ts = 0;
6282 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6283 		if (rtt > rtt_prop)
6284 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6285 		else
6286 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6287 	}
6288 	if (bbr->rc_ack_was_delayed)
6289 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6290 
6291 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6292 		bbr->r_ctl.rc_lowest_rtt = rtt;
6293 	bbr_log_rtt_sample(bbr, rtt, tsin);
6294 	if (bbr->r_init_rtt) {
6295 		/*
6296 		 * The initial rtt is not-trusted, nuke it and lets get
6297 		 * our first valid measurement in.
6298 		 */
6299 		bbr->r_init_rtt = 0;
6300 		tp->t_srtt = 0;
6301 	}
6302 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6303 		/*
6304 		 * So we have not yet figured out
6305 		 * what the peers TSTMP value is
6306 		 * in (most likely ms). We need a
6307 		 * series of cum-ack's to determine
6308 		 * this reliably.
6309 		 */
6310 		if (bbr->rc_ack_is_cumack) {
6311 			if (bbr->rc_ts_data_set) {
6312 				/* Lets attempt to determine the timestamp granularity. */
6313 				bbr_make_timestamp_determination(bbr);
6314 			} else {
6315 				bbr->rc_ts_data_set = 1;
6316 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6317 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6318 			}
6319 		} else {
6320 			/*
6321 			 * We have to have consecutive acks
6322 			 * reset any "filled" state to none.
6323 			 */
6324 			bbr->rc_ts_data_set = 0;
6325 		}
6326 	}
6327 	/* Round it up */
6328 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6329 	if (rtt_ticks == 0)
6330 		rtt_ticks = 1;
6331 	if (tp->t_srtt != 0) {
6332 		/*
6333 		 * srtt is stored as fixed point with 5 bits after the
6334 		 * binary point (i.e., scaled by 8).  The following magic is
6335 		 * equivalent to the smoothing algorithm in rfc793 with an
6336 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6337 		 * Adjust rtt to origin 0.
6338 		 */
6339 
6340 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6341 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6342 
6343 		tp->t_srtt += delta;
6344 		if (tp->t_srtt <= 0)
6345 			tp->t_srtt = 1;
6346 
6347 		/*
6348 		 * We accumulate a smoothed rtt variance (actually, a
6349 		 * smoothed mean difference), then set the retransmit timer
6350 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6351 		 * is stored as fixed point with 4 bits after the binary
6352 		 * point (scaled by 16).  The following is equivalent to
6353 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6354 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6355 		 * wired-in beta.
6356 		 */
6357 		if (delta < 0)
6358 			delta = -delta;
6359 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6360 		tp->t_rttvar += delta;
6361 		if (tp->t_rttvar <= 0)
6362 			tp->t_rttvar = 1;
6363 	} else {
6364 		/*
6365 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6366 		 * variance to half the rtt (so our first retransmit happens
6367 		 * at 3*rtt).
6368 		 */
6369 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6370 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6371 	}
6372 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6373 	tp->t_rttupdated++;
6374 #ifdef STATS
6375 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6376 #endif
6377 	/*
6378 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6379 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6380 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6381 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6382 	 * uncertainty in the firing of the timer.  The bias will give us
6383 	 * exactly the 1.5 tick we need.  But, because the bias is
6384 	 * statistical, we have to test that we don't drop below the minimum
6385 	 * feasible timer (which is 2 ticks).
6386 	 */
6387 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6388 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6389 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6390 
6391 	/*
6392 	 * We received an ack for a packet that wasn't retransmitted; it is
6393 	 * probably safe to discard any error indications we've received
6394 	 * recently.  This isn't quite right, but close enough for now (a
6395 	 * route might have failed after we sent a segment, and the return
6396 	 * path might not be symmetrical).
6397 	 */
6398 	tp->t_softerror = 0;
6399 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6400 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6401 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6402 }
6403 
6404 static void
6405 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6406 {
6407 	bbr->r_ctl.rc_rtt_shrinks = cts;
6408 	if (bbr_can_force_probertt &&
6409 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6410 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6411 		/*
6412 		 * We should enter probe-rtt its been too long
6413 		 * since we have been there.
6414 		 */
6415 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6416 	} else
6417 		bbr_check_probe_rtt_limits(bbr, cts);
6418 }
6419 
6420 static void
6421 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6422 {
6423 	uint64_t orig_bw;
6424 
6425 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6426 		/* We never apply a zero measurement */
6427 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6428 				    0, 0, 0, 0, 0, 0);
6429 		return;
6430 	}
6431 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6432 		bbr->r_ctl.r_measurement_count++;
6433 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6434 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6435 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6436 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6437 			    0, 0, 0, 0, 0, 0);
6438 	if (orig_bw &&
6439 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6440 		if (bbr->bbr_hdrw_pacing) {
6441 			/*
6442 			 * Apply a new rate to the hardware
6443 			 * possibly.
6444 			 */
6445 			bbr_update_hardware_pacing_rate(bbr, cts);
6446 		}
6447 		bbr_set_state_target(bbr, __LINE__);
6448 		tcp_bbr_tso_size_check(bbr, cts);
6449 		if (bbr->r_recovery_bw)  {
6450 			bbr_setup_red_bw(bbr, cts);
6451 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6452 		}
6453 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6454 		tcp_bbr_tso_size_check(bbr, cts);
6455 }
6456 
6457 static void
6458 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6459 {
6460 	if (bbr->rc_in_persist == 0) {
6461 		/* We log only when not in persist */
6462 		/* Translate to a Bytes Per Second */
6463 		uint64_t tim, bw, ts_diff, ts_bw;
6464 		uint32_t delivered;
6465 
6466 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6467 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6468 		else
6469 			tim = 1;
6470 		/*
6471 		 * Now that we have processed the tim (skipping the sample
6472 		 * or possibly updating the time, go ahead and
6473 		 * calculate the cdr.
6474 		 */
6475 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6476 		bw = (uint64_t)delivered;
6477 		bw *= (uint64_t)USECS_IN_SECOND;
6478 		bw /= tim;
6479 		if (bw == 0) {
6480 			/* We must have a calculatable amount */
6481 			return;
6482 		}
6483 		/*
6484 		 * If we are using this b/w shove it in now so we
6485 		 * can see in the trace viewer if it gets over-ridden.
6486 		 */
6487 		if (rsm->r_ts_valid &&
6488 		    bbr->rc_ts_valid &&
6489 		    bbr->rc_ts_clock_set &&
6490 		    (bbr->rc_ts_cant_be_used == 0) &&
6491 		    bbr->rc_use_ts_limit) {
6492 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6493 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6494 			if ((delivered == 0) ||
6495 			    (rtt < 1000)) {
6496 				/* Can't use the ts */
6497 				bbr_log_type_bbrupd(bbr, 61, cts,
6498 						    ts_diff,
6499 						    bbr->r_ctl.last_inbound_ts,
6500 						    rsm->r_del_ack_ts, 0,
6501 						    0, 0, 0, delivered);
6502 			} else {
6503 				ts_bw = (uint64_t)delivered;
6504 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6505 				ts_bw /= ts_diff;
6506 				bbr_log_type_bbrupd(bbr, 62, cts,
6507 						    (ts_bw >> 32),
6508 						    (ts_bw & 0xffffffff), 0, 0,
6509 						    0, 0, ts_diff, delivered);
6510 				if ((bbr->ts_can_raise) &&
6511 				    (ts_bw > bw)) {
6512 					bbr_log_type_bbrupd(bbr, 8, cts,
6513 							    delivered,
6514 							    ts_diff,
6515 							    (bw >> 32),
6516 							    (bw & 0x00000000ffffffff),
6517 							    0, 0, 0, 0);
6518 					bw = ts_bw;
6519 				} else if (ts_bw && (ts_bw < bw)) {
6520 					bbr_log_type_bbrupd(bbr, 7, cts,
6521 							    delivered,
6522 							    ts_diff,
6523 							    (bw >> 32),
6524 							    (bw & 0x00000000ffffffff),
6525 							    0, 0, 0, 0);
6526 					bw = ts_bw;
6527 				}
6528 			}
6529 		}
6530 		if (rsm->r_first_sent_time &&
6531 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6532 			uint64_t sbw, sti;
6533 			/*
6534 			 * We use what was in flight at the time of our
6535 			 * send  and the size of this send to figure
6536 			 * out what we have been sending at (amount).
6537 			 * For the time we take from the time of
6538 			 * the send of the first send outstanding
6539 			 * until this send plus this sends pacing
6540 			 * time. This gives us a good calculation
6541 			 * as to the rate we have been sending at.
6542 			 */
6543 
6544 			sbw = (uint64_t)(rsm->r_flight_at_send);
6545 			sbw *= (uint64_t)USECS_IN_SECOND;
6546 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6547 			sti += rsm->r_pacing_delay;
6548 			sbw /= sti;
6549 			if (sbw < bw) {
6550 				bbr_log_type_bbrupd(bbr, 6, cts,
6551 						    delivered,
6552 						    (uint32_t)sti,
6553 						    (bw >> 32),
6554 						    (uint32_t)bw,
6555 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6556 						    (uint32_t)sbw);
6557 				bw = sbw;
6558 			}
6559 		}
6560 		/* Use the google algorithm for b/w measurements */
6561 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6562 		if ((rsm->r_app_limited == 0) ||
6563 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6564 			tcp_bbr_commit_bw(bbr, cts);
6565 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6566 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6567 		}
6568 	}
6569 }
6570 
6571 static void
6572 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6573 {
6574 	if (bbr->rc_in_persist == 0) {
6575 		/* We log only when not in persist */
6576 		/* Translate to a Bytes Per Second */
6577 		uint64_t tim, bw;
6578 		uint32_t delivered;
6579 		int no_apply = 0;
6580 
6581 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6582 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6583 		else
6584 			tim = 1;
6585 		/*
6586 		 * Now that we have processed the tim (skipping the sample
6587 		 * or possibly updating the time, go ahead and
6588 		 * calculate the cdr.
6589 		 */
6590 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6591 		bw = (uint64_t)delivered;
6592 		bw *= (uint64_t)USECS_IN_SECOND;
6593 		bw /= tim;
6594 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6595 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6596 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6597 
6598 			no_apply = 1;
6599 		}
6600 		/*
6601 		 * If we are using this b/w shove it in now so we
6602 		 * can see in the trace viewer if it gets over-ridden.
6603 		 */
6604 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6605 		/* Gate by the sending rate */
6606 		if (rsm->r_first_sent_time &&
6607 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6608 			uint64_t sbw, sti;
6609 			/*
6610 			 * We use what was in flight at the time of our
6611 			 * send  and the size of this send to figure
6612 			 * out what we have been sending at (amount).
6613 			 * For the time we take from the time of
6614 			 * the send of the first send outstanding
6615 			 * until this send plus this sends pacing
6616 			 * time. This gives us a good calculation
6617 			 * as to the rate we have been sending at.
6618 			 */
6619 
6620 			sbw = (uint64_t)(rsm->r_flight_at_send);
6621 			sbw *= (uint64_t)USECS_IN_SECOND;
6622 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6623 			sti += rsm->r_pacing_delay;
6624 			sbw /= sti;
6625 			if (sbw < bw) {
6626 				bbr_log_type_bbrupd(bbr, 6, cts,
6627 						    delivered,
6628 						    (uint32_t)sti,
6629 						    (bw >> 32),
6630 						    (uint32_t)bw,
6631 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6632 						    (uint32_t)sbw);
6633 				bw = sbw;
6634 			}
6635 			if ((sti > tim) &&
6636 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6637 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6638 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6639 				no_apply = 1;
6640 			} else
6641 				no_apply = 0;
6642 		}
6643 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6644 		if ((no_apply == 0) &&
6645 		    ((rsm->r_app_limited == 0) ||
6646 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6647 			tcp_bbr_commit_bw(bbr, cts);
6648 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6649 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6650 		}
6651 	}
6652 }
6653 
6654 static void
6655 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6656     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6657 {
6658 	uint64_t old_rttprop;
6659 
6660 	/* Update our delivery time and amount */
6661 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6662 	bbr->r_ctl.rc_del_time = cts;
6663 	if (rtt == 0) {
6664 		/*
6665 		 * 0 means its a retransmit, for now we don't use these for
6666 		 * the rest of BBR.
6667 		 */
6668 		return;
6669 	}
6670 	if ((bbr->rc_use_google == 0) &&
6671 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6672 	    (match != BBR_RTT_BY_TIMESTAMP)){
6673 		/*
6674 		 * We get a lot of rtt updates, lets not pay attention to
6675 		 * any that are not an exact match. That way we don't have
6676 		 * to worry about timestamps and the whole nonsense of
6677 		 * unsure if its a retransmission etc (if we ever had the
6678 		 * timestamp fixed to always have the last thing sent this
6679 		 * would not be a issue).
6680 		 */
6681 		return;
6682 	}
6683 	if ((bbr_no_retran && bbr->rc_use_google) &&
6684 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6685 	    (match != BBR_RTT_BY_TIMESTAMP)){
6686 		/*
6687 		 * We only do measurements in google mode
6688 		 * with bbr_no_retran on for sure things.
6689 		 */
6690 		return;
6691 	}
6692 	/* Only update srtt if we know by exact match */
6693 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6694 	if (ack_type == BBR_CUM_ACKED)
6695 		bbr->rc_ack_is_cumack = 1;
6696 	else
6697 		bbr->rc_ack_is_cumack = 0;
6698 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6699 	/*
6700 	 * Note the following code differs to the original
6701 	 * BBR spec. It calls for <= not <. However after a
6702 	 * long discussion in email with Neal, he acknowledged
6703 	 * that it should be < than so that we will have flows
6704 	 * going into probe-rtt (we were seeing cases where that
6705 	 * did not happen and caused ugly things to occur). We
6706 	 * have added this agreed upon fix to our code base.
6707 	 */
6708 	if (rtt < old_rttprop) {
6709 		/* Update when we last saw a rtt drop */
6710 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6711 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6712 	}
6713 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6714 	    match, rsm->r_start, rsm->r_flags);
6715 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6716 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6717 		/*
6718 		 * The RTT-prop moved, reset the target (may be a
6719 		 * nop for some states).
6720 		 */
6721 		bbr_set_state_target(bbr, __LINE__);
6722 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6723 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6724 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6725 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6726 			/* It went up */
6727 			bbr_check_probe_rtt_limits(bbr, cts);
6728 	}
6729 	if ((bbr->rc_use_google == 0) &&
6730 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6731 		/*
6732 		 * We don't do b/w update with
6733 		 * these since they are not really
6734 		 * reliable.
6735 		 */
6736 		return;
6737 	}
6738 	if (bbr->r_ctl.r_app_limited_until &&
6739 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6740 		/* We are no longer app-limited */
6741 		bbr->r_ctl.r_app_limited_until = 0;
6742 	}
6743 	if (bbr->rc_use_google) {
6744 		bbr_google_measurement(bbr, rsm, rtt, cts);
6745 	} else {
6746 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6747 	}
6748 }
6749 
6750 /*
6751  * Convert a timestamp that the main stack
6752  * uses (milliseconds) into one that bbr uses
6753  * (microseconds). Return that converted timestamp.
6754  */
6755 static uint32_t
6756 bbr_ts_convert(uint32_t cts) {
6757 	uint32_t sec, msec;
6758 
6759 	sec = cts / MS_IN_USEC;
6760 	msec = cts - (MS_IN_USEC * sec);
6761 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6762 }
6763 
6764 /*
6765  * Return 0 if we did not update the RTT time, return
6766  * 1 if we did.
6767  */
6768 static int
6769 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6770     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6771 {
6772 	int32_t i;
6773 	uint32_t t, uts = 0;
6774 
6775 	if ((rsm->r_flags & BBR_ACKED) ||
6776 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6777 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6778 		/* Already done */
6779 		return (0);
6780 	}
6781 	if (rsm->r_rtt_not_allowed) {
6782 		/* Not allowed */
6783 		return (0);
6784 	}
6785 	if (rsm->r_rtr_cnt == 1) {
6786 		/*
6787 		 * Only one transmit. Hopefully the normal case.
6788 		 */
6789 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6790 			t = cts - rsm->r_tim_lastsent[0];
6791 		else
6792 			t = 1;
6793 		if ((int)t <= 0)
6794 			t = 1;
6795 		bbr->r_ctl.rc_last_rtt = t;
6796 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6797 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6798 		return (1);
6799 	}
6800 	/* Convert to usecs */
6801 	if ((bbr_can_use_ts_for_rtt == 1) &&
6802 	    (bbr->rc_use_google == 1) &&
6803 	    (ack_type == BBR_CUM_ACKED) &&
6804 	    (to->to_flags & TOF_TS) &&
6805 	    (to->to_tsecr != 0)) {
6806 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6807 		if (t < 1)
6808 			t = 1;
6809 		t *= MS_IN_USEC;
6810 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6811 				    BBR_RTT_BY_TIMESTAMP,
6812 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6813 				    ack_type, to);
6814 		return (1);
6815 	}
6816 	uts = bbr_ts_convert(to->to_tsecr);
6817 	if ((to->to_flags & TOF_TS) &&
6818 	    (to->to_tsecr != 0) &&
6819 	    (ack_type == BBR_CUM_ACKED) &&
6820 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6821 		/*
6822 		 * Now which timestamp does it match? In this block the ACK
6823 		 * may be coming from a previous transmission.
6824 		 */
6825 		uint32_t fudge;
6826 
6827 		fudge = BBR_TIMER_FUDGE;
6828 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6829 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6830 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6831 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6832 					t = cts - rsm->r_tim_lastsent[i];
6833 				else
6834 					t = 1;
6835 				if ((int)t <= 0)
6836 					t = 1;
6837 				bbr->r_ctl.rc_last_rtt = t;
6838 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6839 						    rsm->r_tim_lastsent[i], ack_type, to);
6840 				if ((i + 1) < rsm->r_rtr_cnt) {
6841 					/* Likely */
6842 					return (0);
6843 				} else if (rsm->r_flags & BBR_TLP) {
6844 					bbr->rc_tlp_rtx_out = 0;
6845 				}
6846 				return (1);
6847 			}
6848 		}
6849 		/* Fall through if we can't find a matching timestamp */
6850 	}
6851 	/*
6852 	 * Ok its a SACK block that we retransmitted. or a windows
6853 	 * machine without timestamps. We can tell nothing from the
6854 	 * time-stamp since its not there or the time the peer last
6855 	 * recieved a segment that moved forward its cum-ack point.
6856 	 *
6857 	 * Lets look at the last retransmit and see what we can tell
6858 	 * (with BBR for space we only keep 2 note we have to keep
6859 	 * at least 2 so the map can not be condensed more).
6860 	 */
6861 	i = rsm->r_rtr_cnt - 1;
6862 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6863 		t = cts - rsm->r_tim_lastsent[i];
6864 	else
6865 		goto not_sure;
6866 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6867 		/*
6868 		 * We retransmitted and the ack came back in less
6869 		 * than the smallest rtt we have observed in the
6870 		 * windowed rtt. We most likey did an improper
6871 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6872 		 * the rack-draft.
6873 		 *
6874 		 * Use the prior transmission to update all the
6875 		 * information as long as there is only one prior
6876 		 * transmission.
6877 		 */
6878 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6879 #ifdef BBR_INVARIANTS
6880 			if (rsm->r_rtr_cnt == 1)
6881 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6882 #endif
6883 			i = rsm->r_rtr_cnt - 2;
6884 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6885 				t = cts - rsm->r_tim_lastsent[i];
6886 			else
6887 				t = 1;
6888 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6889 					    rsm->r_tim_lastsent[i], ack_type, to);
6890 			return (0);
6891 		} else {
6892 			/*
6893 			 * Too many prior transmissions, just
6894 			 * updated BBR delivered
6895 			 */
6896 not_sure:
6897 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6898 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6899 		}
6900 	} else {
6901 		/*
6902 		 * We retransmitted it and the retransmit did the
6903 		 * job.
6904 		 */
6905 		if (rsm->r_flags & BBR_TLP)
6906 			bbr->rc_tlp_rtx_out = 0;
6907 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6908 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6909 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6910 		else
6911 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6912 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6913 		return (1);
6914 	}
6915 	return (0);
6916 }
6917 
6918 /*
6919  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6920  */
6921 static void
6922 bbr_log_sack_passed(struct tcpcb *tp,
6923     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6924 {
6925 	struct bbr_sendmap *nrsm;
6926 
6927 	nrsm = rsm;
6928 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6929 	    bbr_head, r_tnext) {
6930 		if (nrsm == rsm) {
6931 			/* Skip orginal segment he is acked */
6932 			continue;
6933 		}
6934 		if (nrsm->r_flags & BBR_ACKED) {
6935 			/* Skip ack'd segments */
6936 			continue;
6937 		}
6938 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6939 			/*
6940 			 * We found one that is already marked
6941 			 * passed, we have been here before and
6942 			 * so all others below this are marked.
6943 			 */
6944 			break;
6945 		}
6946 		BBR_STAT_INC(bbr_sack_passed);
6947 		nrsm->r_flags |= BBR_SACK_PASSED;
6948 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6949 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6950 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6951 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6952 			nrsm->r_flags |= BBR_MARKED_LOST;
6953 		}
6954 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6955 	}
6956 }
6957 
6958 /*
6959  * Returns the number of bytes that were
6960  * newly ack'd by sack blocks.
6961  */
6962 static uint32_t
6963 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6964     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6965 {
6966 	int32_t times = 0;
6967 	uint32_t start, end, changed = 0;
6968 	struct bbr_sendmap *rsm, *nrsm;
6969 	int32_t used_ref = 1;
6970 	uint8_t went_back = 0, went_fwd = 0;
6971 
6972 	start = sack->start;
6973 	end = sack->end;
6974 	rsm = *prsm;
6975 	if (rsm == NULL)
6976 		used_ref = 0;
6977 
6978 	/* Do we locate the block behind where we last were? */
6979 	if (rsm && SEQ_LT(start, rsm->r_start)) {
6980 		went_back = 1;
6981 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
6982 			if (SEQ_GEQ(start, rsm->r_start) &&
6983 			    SEQ_LT(start, rsm->r_end)) {
6984 				goto do_rest_ofb;
6985 			}
6986 		}
6987 	}
6988 start_at_beginning:
6989 	went_fwd = 1;
6990 	/*
6991 	 * Ok lets locate the block where this guy is fwd from rsm (if its
6992 	 * set)
6993 	 */
6994 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
6995 		if (SEQ_GEQ(start, rsm->r_start) &&
6996 		    SEQ_LT(start, rsm->r_end)) {
6997 			break;
6998 		}
6999 	}
7000 do_rest_ofb:
7001 	if (rsm == NULL) {
7002 		/*
7003 		 * This happens when we get duplicate sack blocks with the
7004 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7005 		 * will not change there location so we would just start at
7006 		 * the end of the first one and get lost.
7007 		 */
7008 		if (tp->t_flags & TF_SENTFIN) {
7009 			/*
7010 			 * Check to see if we have not logged the FIN that
7011 			 * went out.
7012 			 */
7013 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7014 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7015 				/*
7016 				 * Ok we did not get the FIN logged.
7017 				 */
7018 				nrsm->r_end++;
7019 				rsm = nrsm;
7020 				goto do_rest_ofb;
7021 			}
7022 		}
7023 		if (times == 1) {
7024 #ifdef BBR_INVARIANTS
7025 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7026 			    tp, bbr, sack, to, prsm);
7027 #else
7028 			goto out;
7029 #endif
7030 		}
7031 		times++;
7032 		BBR_STAT_INC(bbr_sack_proc_restart);
7033 		rsm = NULL;
7034 		goto start_at_beginning;
7035 	}
7036 	/* Ok we have an ACK for some piece of rsm */
7037 	if (rsm->r_start != start) {
7038 		/*
7039 		 * Need to split this in two pieces the before and after.
7040 		 */
7041 		if (bbr_sack_mergable(rsm, start, end))
7042 			nrsm = bbr_alloc_full_limit(bbr);
7043 		else
7044 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7045 		if (nrsm == NULL) {
7046 			/* We could not allocate ignore the sack */
7047 			struct sackblk blk;
7048 
7049 			blk.start = start;
7050 			blk.end = end;
7051 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7052 			goto out;
7053 		}
7054 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7055 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7056 		if (rsm->r_in_tmap) {
7057 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7058 			nrsm->r_in_tmap = 1;
7059 		}
7060 		rsm->r_flags &= (~BBR_HAS_FIN);
7061 		rsm = nrsm;
7062 	}
7063 	if (SEQ_GEQ(end, rsm->r_end)) {
7064 		/*
7065 		 * The end of this block is either beyond this guy or right
7066 		 * at this guy.
7067 		 */
7068 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7069 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7070 			changed += (rsm->r_end - rsm->r_start);
7071 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7072 			bbr_log_sack_passed(tp, bbr, rsm);
7073 			if (rsm->r_flags & BBR_MARKED_LOST) {
7074 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7075 			}
7076 			/* Is Reordering occuring? */
7077 			if (rsm->r_flags & BBR_SACK_PASSED) {
7078 				BBR_STAT_INC(bbr_reorder_seen);
7079 				bbr->r_ctl.rc_reorder_ts = cts;
7080 				if (rsm->r_flags & BBR_MARKED_LOST) {
7081 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7082 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7083 						/* LT sampling also needs adjustment */
7084 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7085 				}
7086 			}
7087 			rsm->r_flags |= BBR_ACKED;
7088 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7089 			if (rsm->r_in_tmap) {
7090 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7091 				rsm->r_in_tmap = 0;
7092 			}
7093 		}
7094 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7095 		if (end == rsm->r_end) {
7096 			/* This block only - done */
7097 			goto out;
7098 		}
7099 		/* There is more not coverend by this rsm move on */
7100 		start = rsm->r_end;
7101 		nrsm = TAILQ_NEXT(rsm, r_next);
7102 		rsm = nrsm;
7103 		times = 0;
7104 		goto do_rest_ofb;
7105 	}
7106 	if (rsm->r_flags & BBR_ACKED) {
7107 		/* Been here done that */
7108 		goto out;
7109 	}
7110 	/* Ok we need to split off this one at the tail */
7111 	if (bbr_sack_mergable(rsm, start, end))
7112 		nrsm = bbr_alloc_full_limit(bbr);
7113 	else
7114 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7115 	if (nrsm == NULL) {
7116 		/* failed XXXrrs what can we do but loose the sack info? */
7117 		struct sackblk blk;
7118 
7119 		blk.start = start;
7120 		blk.end = end;
7121 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7122 		goto out;
7123 	}
7124 	/* Clone it */
7125 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7126 	/* The sack block does not cover this guy fully */
7127 	rsm->r_flags &= (~BBR_HAS_FIN);
7128 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7129 	if (rsm->r_in_tmap) {
7130 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7131 		nrsm->r_in_tmap = 1;
7132 	}
7133 	nrsm->r_dupack = 0;
7134 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7135 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7136 	changed += (rsm->r_end - rsm->r_start);
7137 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7138 	bbr_log_sack_passed(tp, bbr, rsm);
7139 	/* Is Reordering occuring? */
7140 	if (rsm->r_flags & BBR_MARKED_LOST) {
7141 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7142 	}
7143 	if (rsm->r_flags & BBR_SACK_PASSED) {
7144 		BBR_STAT_INC(bbr_reorder_seen);
7145 		bbr->r_ctl.rc_reorder_ts = cts;
7146 		if (rsm->r_flags & BBR_MARKED_LOST) {
7147 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7148 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7149 				/* LT sampling also needs adjustment */
7150 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7151 		}
7152 	}
7153 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7154 	rsm->r_flags |= BBR_ACKED;
7155 	if (rsm->r_in_tmap) {
7156 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7157 		rsm->r_in_tmap = 0;
7158 	}
7159 out:
7160 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7161 		/*
7162 		 * Now can we merge this newly acked
7163 		 * block with either the previous or
7164 		 * next block?
7165 		 */
7166 		nrsm = TAILQ_NEXT(rsm, r_next);
7167 		if (nrsm &&
7168 		    (nrsm->r_flags & BBR_ACKED)) {
7169 			/* yep this and next can be merged */
7170 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7171 		}
7172 		/* Now what about the previous? */
7173 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7174 		if (nrsm &&
7175 		    (nrsm->r_flags & BBR_ACKED)) {
7176 			/* yep the previous and this can be merged */
7177 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7178 		}
7179 	}
7180 	if (used_ref == 0) {
7181 		BBR_STAT_INC(bbr_sack_proc_all);
7182 	} else {
7183 		BBR_STAT_INC(bbr_sack_proc_short);
7184 	}
7185 	if (went_fwd && went_back) {
7186 		BBR_STAT_INC(bbr_sack_search_both);
7187 	} else if (went_fwd) {
7188 		BBR_STAT_INC(bbr_sack_search_fwd);
7189 	} else if (went_back) {
7190 		BBR_STAT_INC(bbr_sack_search_back);
7191 	}
7192 	/* Save off where the next seq is */
7193 	if (rsm)
7194 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7195 	else
7196 		bbr->r_ctl.rc_sacklast = NULL;
7197 	*prsm = rsm;
7198 	return (changed);
7199 }
7200 
7201 static void inline
7202 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7203 {
7204 	struct bbr_sendmap *tmap;
7205 
7206 	BBR_STAT_INC(bbr_reneges_seen);
7207 	tmap = NULL;
7208 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7209 		/* Its no longer sacked, mark it so */
7210 		uint32_t oflags;
7211 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7212 #ifdef BBR_INVARIANTS
7213 		if (rsm->r_in_tmap) {
7214 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7215 			    bbr, rsm, rsm->r_flags);
7216 		}
7217 #endif
7218 		oflags = rsm->r_flags;
7219 		if (rsm->r_flags & BBR_MARKED_LOST) {
7220 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7221 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7222 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7223 				/* LT sampling also needs adjustment */
7224 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7225 		}
7226 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7227 		rsm->r_flags |= BBR_WAS_RENEGED;
7228 		rsm->r_flags |= BBR_RXT_CLEARED;
7229 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7230 		/* Rebuild it into our tmap */
7231 		if (tmap == NULL) {
7232 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7233 			tmap = rsm;
7234 		} else {
7235 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7236 			tmap = rsm;
7237 		}
7238 		tmap->r_in_tmap = 1;
7239 		/*
7240 		 * XXXrrs Delivered? Should we do anything here?
7241 		 *
7242 		 * Of course we don't on a rxt timeout so maybe its ok that
7243 		 * we don't?
7244 		 *
7245 		 * For now lets not.
7246 		 */
7247 		rsm = TAILQ_NEXT(rsm, r_next);
7248 	}
7249 	/*
7250 	 * Now lets possibly clear the sack filter so we start recognizing
7251 	 * sacks that cover this area.
7252 	 */
7253 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7254 }
7255 
7256 static void
7257 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7258 {
7259 	struct tcp_bbr *bbr;
7260 	struct bbr_sendmap *rsm;
7261 	uint32_t cts;
7262 
7263 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7264 	cts = bbr->r_ctl.rc_rcvtime;
7265 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7266 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7267 		if ((rsm->r_end - rsm->r_start) <= 1) {
7268 			/* Log out the SYN completely */
7269 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7270 			rsm->r_rtr_bytes = 0;
7271 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7272 			if (rsm->r_in_tmap) {
7273 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7274 				rsm->r_in_tmap = 0;
7275 			}
7276 			if (bbr->r_ctl.rc_next == rsm) {
7277 				/* scoot along the marker */
7278 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7279 			}
7280 			if (to != NULL)
7281 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7282 			bbr_free(bbr, rsm);
7283 		} else {
7284 			/* There is more (Fast open)? strip out SYN. */
7285 			rsm->r_flags &= ~BBR_HAS_SYN;
7286 			rsm->r_start++;
7287 		}
7288 	}
7289 }
7290 
7291 /*
7292  * Returns the number of bytes that were
7293  * acknowledged by SACK blocks.
7294  */
7295 
7296 static uint32_t
7297 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7298     uint32_t *prev_acked)
7299 {
7300 	uint32_t changed, last_seq, entered_recovery = 0;
7301 	struct tcp_bbr *bbr;
7302 	struct bbr_sendmap *rsm;
7303 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7304 	register uint32_t th_ack;
7305 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7306 	uint32_t cts, acked, ack_point, sack_changed = 0;
7307 	uint32_t p_maxseg, maxseg, p_acked = 0;
7308 
7309 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7310 	if (tcp_get_flags(th) & TH_RST) {
7311 		/* We don't log resets */
7312 		return (0);
7313 	}
7314 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7315 	cts = bbr->r_ctl.rc_rcvtime;
7316 
7317 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7318 	changed = 0;
7319 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7320 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7321 	th_ack = th->th_ack;
7322 	if (SEQ_GT(th_ack, tp->snd_una)) {
7323 		acked = th_ack - tp->snd_una;
7324 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7325 		bbr->rc_tp->t_acktime = ticks;
7326 	} else
7327 		acked = 0;
7328 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7329 		/* Only sent here for sack processing */
7330 		goto proc_sack;
7331 	}
7332 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7333 		changed = th_ack - rsm->r_start;
7334 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7335 		/*
7336 		 * For the SYN incoming case we will not have called
7337 		 * tcp_output for the sending of the SYN, so there will be
7338 		 * no map. All other cases should probably be a panic.
7339 		 */
7340 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7341 			/*
7342 			 * We have a timestamp that can be used to generate
7343 			 * an initial RTT.
7344 			 */
7345 			uint32_t ts, now, rtt;
7346 
7347 			ts = bbr_ts_convert(to->to_tsecr);
7348 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7349 			rtt = now - ts;
7350 			if (rtt < 1)
7351 				rtt = 1;
7352 			bbr_log_type_bbrrttprop(bbr, rtt,
7353 						tp->iss, 0, cts,
7354 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7355 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7356 			changed = 1;
7357 			bbr->r_wanted_output = 1;
7358 			goto out;
7359 		}
7360 		goto proc_sack;
7361 	} else if (rsm == NULL) {
7362 		goto out;
7363 	}
7364 	if (changed) {
7365 		/*
7366 		 * The ACK point is advancing to th_ack, we must drop off
7367 		 * the packets in the rack log and calculate any eligble
7368 		 * RTT's.
7369 		 */
7370 		bbr->r_wanted_output = 1;
7371 more:
7372 		if (rsm == NULL) {
7373 			if (tp->t_flags & TF_SENTFIN) {
7374 				/* if we send a FIN we will not hav a map */
7375 				goto proc_sack;
7376 			}
7377 #ifdef BBR_INVARIANTS
7378 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7379 			    tp,
7380 			    th, tp->t_state, bbr,
7381 			    tp->snd_una, tp->snd_max, changed);
7382 #endif
7383 			goto proc_sack;
7384 		}
7385 	}
7386 	if (SEQ_LT(th_ack, rsm->r_start)) {
7387 		/* Huh map is missing this */
7388 #ifdef BBR_INVARIANTS
7389 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7390 		    rsm->r_start,
7391 		    th_ack, tp->t_state,
7392 		    bbr->r_state, bbr);
7393 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7394 #endif
7395 		goto proc_sack;
7396 	} else if (th_ack == rsm->r_start) {
7397 		/* None here to ack */
7398 		goto proc_sack;
7399 	}
7400 	/*
7401 	 * Clear the dup ack counter, it will
7402 	 * either be freed or if there is some
7403 	 * remaining we need to start it at zero.
7404 	 */
7405 	rsm->r_dupack = 0;
7406 	/* Now do we consume the whole thing? */
7407 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7408 		/* Its all consumed. */
7409 		uint32_t left;
7410 
7411 		if (rsm->r_flags & BBR_ACKED) {
7412 			/*
7413 			 * It was acked on the scoreboard -- remove it from
7414 			 * total
7415 			 */
7416 			p_acked += (rsm->r_end - rsm->r_start);
7417 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7418 			if (bbr->r_ctl.rc_sacked == 0)
7419 				bbr->r_ctl.rc_sacklast = NULL;
7420 		} else {
7421 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7422 			if (rsm->r_flags & BBR_MARKED_LOST) {
7423 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7424 			}
7425 			if (rsm->r_flags & BBR_SACK_PASSED) {
7426 				/*
7427 				 * There are acked segments ACKED on the
7428 				 * scoreboard further up. We are seeing
7429 				 * reordering.
7430 				 */
7431 				BBR_STAT_INC(bbr_reorder_seen);
7432 				bbr->r_ctl.rc_reorder_ts = cts;
7433 				if (rsm->r_flags & BBR_MARKED_LOST) {
7434 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7435 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7436 						/* LT sampling also needs adjustment */
7437 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7438 				}
7439 			}
7440 			rsm->r_flags &= ~BBR_MARKED_LOST;
7441 		}
7442 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7443 		rsm->r_rtr_bytes = 0;
7444 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7445 		if (rsm->r_in_tmap) {
7446 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7447 			rsm->r_in_tmap = 0;
7448 		}
7449 		if (bbr->r_ctl.rc_next == rsm) {
7450 			/* scoot along the marker */
7451 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7452 		}
7453 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7454 		/* Adjust the packet counts */
7455 		left = th_ack - rsm->r_end;
7456 		/* Free back to zone */
7457 		bbr_free(bbr, rsm);
7458 		if (left) {
7459 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7460 			goto more;
7461 		}
7462 		goto proc_sack;
7463 	}
7464 	if (rsm->r_flags & BBR_ACKED) {
7465 		/*
7466 		 * It was acked on the scoreboard -- remove it from total
7467 		 * for the part being cum-acked.
7468 		 */
7469 		p_acked += (rsm->r_end - rsm->r_start);
7470 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7471 		if (bbr->r_ctl.rc_sacked == 0)
7472 			bbr->r_ctl.rc_sacklast = NULL;
7473 	} else {
7474 		/*
7475 		 * It was acked up to th_ack point for the first time
7476 		 */
7477 		struct bbr_sendmap lrsm;
7478 
7479 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7480 		lrsm.r_end = th_ack;
7481 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7482 	}
7483 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7484 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7485 		/*
7486 		 * It was marked lost and partly ack'd now
7487 		 * for the first time. We lower the rc_lost_bytes
7488 		 * and still leave it MARKED.
7489 		 */
7490 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7491 	}
7492 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7493 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7494 	rsm->r_rtr_bytes = 0;
7495 	/* adjust packet count */
7496 	rsm->r_start = th_ack;
7497 proc_sack:
7498 	/* Check for reneging */
7499 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7500 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7501 		/*
7502 		 * The peer has moved snd_una up to the edge of this send,
7503 		 * i.e. one that it had previously acked. The only way that
7504 		 * can be true if the peer threw away data (space issues)
7505 		 * that it had previously sacked (else it would have given
7506 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7507 		 * markings here.
7508 		 *
7509 		 * Note we have to look to make sure th_ack is our
7510 		 * rsm->r_start in case we get an old ack where th_ack is
7511 		 * behind snd_una.
7512 		 */
7513 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7514 	}
7515 	if ((to->to_flags & TOF_SACK) == 0) {
7516 		/* We are done nothing left to log */
7517 		goto out;
7518 	}
7519 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7520 	if (rsm) {
7521 		last_seq = rsm->r_end;
7522 	} else {
7523 		last_seq = tp->snd_max;
7524 	}
7525 	/* Sack block processing */
7526 	if (SEQ_GT(th_ack, tp->snd_una))
7527 		ack_point = th_ack;
7528 	else
7529 		ack_point = tp->snd_una;
7530 	for (i = 0; i < to->to_nsacks; i++) {
7531 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7532 		    &sack, sizeof(sack));
7533 		sack.start = ntohl(sack.start);
7534 		sack.end = ntohl(sack.end);
7535 		if (SEQ_GT(sack.end, sack.start) &&
7536 		    SEQ_GT(sack.start, ack_point) &&
7537 		    SEQ_LT(sack.start, tp->snd_max) &&
7538 		    SEQ_GT(sack.end, ack_point) &&
7539 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7540 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7541 			    (SEQ_LT(sack.end, last_seq)) &&
7542 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7543 				/*
7544 				 * Not the last piece and its smaller than
7545 				 * 1/8th of a p_maxseg. We ignore this.
7546 				 */
7547 				BBR_STAT_INC(bbr_runt_sacks);
7548 				continue;
7549 			}
7550 			sack_blocks[num_sack_blks] = sack;
7551 			num_sack_blks++;
7552 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7553 		    SEQ_LEQ(sack.end, th_ack)) {
7554 			/*
7555 			 * Its a D-SACK block.
7556 			 */
7557 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7558 		}
7559 	}
7560 	if (num_sack_blks == 0)
7561 		goto out;
7562 	/*
7563 	 * Sort the SACK blocks so we can update the rack scoreboard with
7564 	 * just one pass.
7565 	 */
7566 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7567 				  num_sack_blks, th->th_ack);
7568 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7569 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7570 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7571 	num_sack_blks = new_sb;
7572 	if (num_sack_blks < 2) {
7573 		goto do_sack_work;
7574 	}
7575 	/* Sort the sacks */
7576 	for (i = 0; i < num_sack_blks; i++) {
7577 		for (j = i + 1; j < num_sack_blks; j++) {
7578 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7579 				sack = sack_blocks[i];
7580 				sack_blocks[i] = sack_blocks[j];
7581 				sack_blocks[j] = sack;
7582 			}
7583 		}
7584 	}
7585 	/*
7586 	 * Now are any of the sack block ends the same (yes some
7587 	 * implememtations send these)?
7588 	 */
7589 again:
7590 	if (num_sack_blks > 1) {
7591 		for (i = 0; i < num_sack_blks; i++) {
7592 			for (j = i + 1; j < num_sack_blks; j++) {
7593 				if (sack_blocks[i].end == sack_blocks[j].end) {
7594 					/*
7595 					 * Ok these two have the same end we
7596 					 * want the smallest end and then
7597 					 * throw away the larger and start
7598 					 * again.
7599 					 */
7600 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7601 						/*
7602 						 * The second block covers
7603 						 * more area use that
7604 						 */
7605 						sack_blocks[i].start = sack_blocks[j].start;
7606 					}
7607 					/*
7608 					 * Now collapse out the dup-sack and
7609 					 * lower the count
7610 					 */
7611 					for (k = (j + 1); k < num_sack_blks; k++) {
7612 						sack_blocks[j].start = sack_blocks[k].start;
7613 						sack_blocks[j].end = sack_blocks[k].end;
7614 						j++;
7615 					}
7616 					num_sack_blks--;
7617 					goto again;
7618 				}
7619 			}
7620 		}
7621 	}
7622 do_sack_work:
7623 	rsm = bbr->r_ctl.rc_sacklast;
7624 	for (i = 0; i < num_sack_blks; i++) {
7625 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7626 		if (acked) {
7627 			bbr->r_wanted_output = 1;
7628 			changed += acked;
7629 			sack_changed += acked;
7630 		}
7631 	}
7632 out:
7633 	*prev_acked = p_acked;
7634 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7635 		/*
7636 		 * Ok we have a high probability that we need to go in to
7637 		 * recovery since we have data sack'd
7638 		 */
7639 		struct bbr_sendmap *rsm;
7640 
7641 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7642 		if (rsm) {
7643 			/* Enter recovery */
7644 			entered_recovery = 1;
7645 			bbr->r_wanted_output = 1;
7646 			/*
7647 			 * When we enter recovery we need to assure we send
7648 			 * one packet.
7649 			 */
7650 			if (bbr->r_ctl.rc_resend == NULL) {
7651 				bbr->r_ctl.rc_resend = rsm;
7652 			}
7653 		}
7654 	}
7655 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7656 		/*
7657 		 * See if we need to rack-retransmit anything if so set it
7658 		 * up as the thing to resend assuming something else is not
7659 		 * already in that position.
7660 		 */
7661 		if (bbr->r_ctl.rc_resend == NULL) {
7662 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7663 		}
7664 	}
7665 	/*
7666 	 * We return the amount that changed via sack, this is used by the
7667 	 * ack-received code to augment what was changed between th_ack <->
7668 	 * snd_una.
7669 	 */
7670 	return (sack_changed);
7671 }
7672 
7673 static void
7674 bbr_strike_dupack(struct tcp_bbr *bbr)
7675 {
7676 	struct bbr_sendmap *rsm;
7677 
7678 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7679 	if (rsm && (rsm->r_dupack < 0xff)) {
7680 		rsm->r_dupack++;
7681 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7682 			bbr->r_wanted_output = 1;
7683 	}
7684 }
7685 
7686 /*
7687  * Return value of 1, we do not need to call bbr_process_data().
7688  * return value of 0, bbr_process_data can be called.
7689  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7690  * its unlocked and probably unsafe to touch the TCB.
7691  */
7692 static int
7693 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7694     struct tcpcb *tp, struct tcpopt *to,
7695     uint32_t tiwin, int32_t tlen,
7696     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7697 {
7698 	int32_t ourfinisacked = 0;
7699 	int32_t acked_amount;
7700 	uint16_t nsegs;
7701 	int32_t acked;
7702 	uint32_t lost, sack_changed = 0;
7703 	struct mbuf *mfree;
7704 	struct tcp_bbr *bbr;
7705 	uint32_t prev_acked = 0;
7706 
7707 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7708 	lost = bbr->r_ctl.rc_lost;
7709 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7710 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7711 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7712 		bbr->r_wanted_output = 1;
7713 		return (1);
7714 	}
7715 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7716 		/* Process the ack */
7717 		if (bbr->rc_in_persist)
7718 			tp->t_rxtshift = 0;
7719 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7720 			bbr_strike_dupack(bbr);
7721 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7722 	}
7723 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7724 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7725 		/*
7726 		 * Old ack, behind the last one rcv'd or a duplicate ack
7727 		 * with SACK info.
7728 		 */
7729 		if (th->th_ack == tp->snd_una) {
7730 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7731 			if (bbr->r_state == TCPS_SYN_SENT) {
7732 				/*
7733 				 * Special case on where we sent SYN. When
7734 				 * the SYN-ACK is processed in syn_sent
7735 				 * state it bumps the snd_una. This causes
7736 				 * us to hit here even though we did ack 1
7737 				 * byte.
7738 				 *
7739 				 * Go through the nothing left case so we
7740 				 * send data.
7741 				 */
7742 				goto nothing_left;
7743 			}
7744 		}
7745 		return (0);
7746 	}
7747 	/*
7748 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7749 	 * something we sent.
7750 	 */
7751 	if (tp->t_flags & TF_NEEDSYN) {
7752 		/*
7753 		 * T/TCP: Connection was half-synchronized, and our SYN has
7754 		 * been ACK'd (so connection is now fully synchronized).  Go
7755 		 * to non-starred state, increment snd_una for ACK of SYN,
7756 		 * and check if we can do window scaling.
7757 		 */
7758 		tp->t_flags &= ~TF_NEEDSYN;
7759 		tp->snd_una++;
7760 		/* Do window scaling? */
7761 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7762 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7763 			tp->rcv_scale = tp->request_r_scale;
7764 			/* Send window already scaled. */
7765 		}
7766 	}
7767 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7768 
7769 	acked = BYTES_THIS_ACK(tp, th);
7770 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7771 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7772 
7773 	/*
7774 	 * If we just performed our first retransmit, and the ACK arrives
7775 	 * within our recovery window, then it was a mistake to do the
7776 	 * retransmit in the first place.  Recover our original cwnd and
7777 	 * ssthresh, and proceed to transmit where we left off.
7778 	 */
7779 	if (tp->t_flags & TF_PREVVALID) {
7780 		tp->t_flags &= ~TF_PREVVALID;
7781 		if (tp->t_rxtshift == 1 &&
7782 		    (int)(ticks - tp->t_badrxtwin) < 0)
7783 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7784 	}
7785 	SOCKBUF_LOCK(&so->so_snd);
7786 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7787 	tp->snd_wnd -= acked_amount;
7788 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7789 	/* NB: sowwakeup_locked() does an implicit unlock. */
7790 	sowwakeup_locked(so);
7791 	m_freem(mfree);
7792 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7793 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7794 	}
7795 	tp->snd_una = th->th_ack;
7796 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7797 	if (IN_RECOVERY(tp->t_flags)) {
7798 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7799 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7800 			tcp_bbr_partialack(tp);
7801 		} else {
7802 			bbr_post_recovery(tp);
7803 		}
7804 	}
7805 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7806 		tp->snd_recover = tp->snd_una;
7807 	}
7808 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7809 		tp->snd_nxt = tp->snd_max;
7810 	}
7811 	if (tp->snd_una == tp->snd_max) {
7812 		/* Nothing left outstanding */
7813 nothing_left:
7814 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7815 		if (sbavail(&so->so_snd) == 0)
7816 			bbr->rc_tp->t_acktime = 0;
7817 		if ((sbused(&so->so_snd) == 0) &&
7818 		    (tp->t_flags & TF_SENTFIN)) {
7819 			ourfinisacked = 1;
7820 		}
7821 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7822 		if (bbr->rc_in_persist == 0) {
7823 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7824 		}
7825 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7826 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7827 		/*
7828 		 * We invalidate the last ack here since we
7829 		 * don't want to transfer forward the time
7830 		 * for our sum's calculations.
7831 		 */
7832 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7833 		    (sbavail(&so->so_snd) == 0) &&
7834 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7835 			/*
7836 			 * The socket was gone and the peer sent data, time
7837 			 * to reset him.
7838 			 */
7839 			*ret_val = 1;
7840 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7841 			/* tcp_close will kill the inp pre-log the Reset */
7842 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7843 			tp = tcp_close(tp);
7844 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7845 			BBR_STAT_INC(bbr_dropped_af_data);
7846 			return (1);
7847 		}
7848 		/* Set need output so persist might get set */
7849 		bbr->r_wanted_output = 1;
7850 	}
7851 	if (ofia)
7852 		*ofia = ourfinisacked;
7853 	return (0);
7854 }
7855 
7856 static void
7857 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7858 {
7859 	if (bbr->rc_in_persist == 0) {
7860 		bbr_timer_cancel(bbr, __LINE__, cts);
7861 		bbr->r_ctl.rc_last_delay_val = 0;
7862 		tp->t_rxtshift = 0;
7863 		bbr->rc_in_persist = 1;
7864 		bbr->r_ctl.rc_went_idle_time = cts;
7865 		/* We should be capped when rw went to 0 but just in case */
7866 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7867 		/* Time freezes for the state, so do the accounting now */
7868 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7869 			uint32_t time_in;
7870 
7871 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7872 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7873 				int32_t idx;
7874 
7875 				idx = bbr_state_val(bbr);
7876 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7877 			} else {
7878 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7879 			}
7880 		}
7881 		bbr->r_ctl.rc_bbr_state_time = cts;
7882 	}
7883 }
7884 
7885 static void
7886 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7887 {
7888 	/*
7889 	 * Note that if idle time does not exceed our
7890 	 * threshold, we do nothing continuing the state
7891 	 * transitions we were last walking through.
7892 	 */
7893 	if (idle_time >= bbr_idle_restart_threshold) {
7894 		if (bbr->rc_use_idle_restart) {
7895 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7896 			/*
7897 			 * Set our target using BBR_UNIT, so
7898 			 * we increase at a dramatic rate but
7899 			 * we stop when we get the pipe
7900 			 * full again for our current b/w estimate.
7901 			 */
7902 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7903 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7904 			bbr_set_state_target(bbr, __LINE__);
7905 			/* Now setup our gains to ramp up */
7906 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7907 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7908 			bbr_log_type_statechange(bbr, cts, __LINE__);
7909 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7910 			bbr_substate_change(bbr, cts, __LINE__, 1);
7911 		}
7912 	}
7913 }
7914 
7915 static void
7916 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7917 {
7918 	uint32_t idle_time;
7919 
7920 	if (bbr->rc_in_persist == 0)
7921 		return;
7922 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7923 	bbr->rc_in_persist = 0;
7924 	bbr->rc_hit_state_1 = 0;
7925 	bbr->r_ctl.rc_del_time = cts;
7926 	/*
7927 	 * We invalidate the last ack here since we
7928 	 * don't want to transfer forward the time
7929 	 * for our sum's calculations.
7930 	 */
7931 	if (tcp_in_hpts(bbr->rc_inp)) {
7932 		tcp_hpts_remove(bbr->rc_inp);
7933 		bbr->rc_timer_first = 0;
7934 		bbr->r_ctl.rc_hpts_flags = 0;
7935 		bbr->r_ctl.rc_last_delay_val = 0;
7936 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7937 		bbr->r_agg_early_set = 0;
7938 		bbr->r_ctl.rc_agg_early = 0;
7939 	}
7940 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7941 	if (idle_time >= bbr_rtt_probe_time) {
7942 		/*
7943 		 * This qualifies as a RTT_PROBE session since we drop the
7944 		 * data outstanding to nothing and waited more than
7945 		 * bbr_rtt_probe_time.
7946 		 */
7947 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7948 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7949 	}
7950 	tp->t_rxtshift = 0;
7951 	/*
7952 	 * If in probeBW and we have persisted more than an RTT lets do
7953 	 * special handling.
7954 	 */
7955 	/* Force a time based epoch */
7956 	bbr_set_epoch(bbr, cts, __LINE__);
7957 	/*
7958 	 * Setup the lost so we don't count anything against the guy
7959 	 * we have been stuck with during persists.
7960 	 */
7961 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7962 	/* Time un-freezes for the state */
7963 	bbr->r_ctl.rc_bbr_state_time = cts;
7964 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7965 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7966 		/*
7967 		 * If we are going back to probe-bw
7968 		 * or probe_rtt, we may need to possibly
7969 		 * do a fast restart.
7970 		 */
7971 		bbr_restart_after_idle(bbr, cts, idle_time);
7972 	}
7973 }
7974 
7975 static void
7976 bbr_collapsed_window(struct tcp_bbr *bbr)
7977 {
7978 	/*
7979 	 * Now we must walk the
7980 	 * send map and divide the
7981 	 * ones left stranded. These
7982 	 * guys can't cause us to abort
7983 	 * the connection and are really
7984 	 * "unsent". However if a buggy
7985 	 * client actually did keep some
7986 	 * of the data i.e. collapsed the win
7987 	 * and refused to ack and then opened
7988 	 * the win and acked that data. We would
7989 	 * get into an ack war, the simplier
7990 	 * method then of just pretending we
7991 	 * did not send those segments something
7992 	 * won't work.
7993 	 */
7994 	struct bbr_sendmap *rsm, *nrsm;
7995 	tcp_seq max_seq;
7996 	uint32_t maxseg;
7997 	int can_split = 0;
7998 	int fnd = 0;
7999 
8000 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8001 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8002 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8003 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8004 		/* Find the first seq past or at maxseq */
8005 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8006 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8007 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8008 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8009 			fnd = 1;
8010 			break;
8011 		}
8012 	}
8013 	bbr->rc_has_collapsed = 0;
8014 	if (!fnd) {
8015 		/* Nothing to do strange */
8016 		return;
8017 	}
8018 	/*
8019 	 * Now can we split?
8020 	 *
8021 	 * We don't want to split if splitting
8022 	 * would generate too many small segments
8023 	 * less we let an attacker fragment our
8024 	 * send_map and leave us out of memory.
8025 	 */
8026 	if ((max_seq != rsm->r_start) &&
8027 	    (max_seq != rsm->r_end)){
8028 		/* can we split? */
8029 		int res1, res2;
8030 
8031 		res1 = max_seq - rsm->r_start;
8032 		res2 = rsm->r_end - max_seq;
8033 		if ((res1 >= (maxseg/8)) &&
8034 		    (res2 >= (maxseg/8))) {
8035 			/* No small pieces here */
8036 			can_split = 1;
8037 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8038 			/* We are under the limit */
8039 			can_split = 1;
8040 		}
8041 	}
8042 	/* Ok do we need to split this rsm? */
8043 	if (max_seq == rsm->r_start) {
8044 		/* It's this guy no split required */
8045 		nrsm = rsm;
8046 	} else if (max_seq == rsm->r_end) {
8047 		/* It's the next one no split required. */
8048 		nrsm = TAILQ_NEXT(rsm, r_next);
8049 		if (nrsm == NULL) {
8050 			/* Huh? */
8051 			return;
8052 		}
8053 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8054 		/* yep we need to split it */
8055 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8056 		if (nrsm == NULL) {
8057 			/* failed XXXrrs what can we do mark the whole? */
8058 			nrsm = rsm;
8059 			goto no_split;
8060 		}
8061 		/* Clone it */
8062 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8063 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8064 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8065 		if (rsm->r_in_tmap) {
8066 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8067 			nrsm->r_in_tmap = 1;
8068 		}
8069 	} else {
8070 		/*
8071 		 * Split not allowed just start here just
8072 		 * use this guy.
8073 		 */
8074 		nrsm = rsm;
8075 	}
8076 no_split:
8077 	BBR_STAT_INC(bbr_collapsed_win);
8078 	/* reuse fnd as a count */
8079 	fnd = 0;
8080 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8081 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8082 		fnd++;
8083 		bbr->rc_has_collapsed = 1;
8084 	}
8085 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8086 }
8087 
8088 static void
8089 bbr_un_collapse_window(struct tcp_bbr *bbr)
8090 {
8091 	struct bbr_sendmap *rsm;
8092 	int cleared = 0;
8093 
8094 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8095 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8096 			/* Clear the flag */
8097 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8098 			cleared++;
8099 		} else
8100 			break;
8101 	}
8102 	bbr_log_type_rwnd_collapse(bbr,
8103 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8104 	bbr->rc_has_collapsed = 0;
8105 }
8106 
8107 /*
8108  * Return value of 1, the TCB is unlocked and most
8109  * likely gone, return value of 0, the TCB is still
8110  * locked.
8111  */
8112 static int
8113 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8114     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8115     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8116 {
8117 	/*
8118 	 * Update window information. Don't look at window if no ACK: TAC's
8119 	 * send garbage on first SYN.
8120 	 */
8121 	uint16_t nsegs;
8122 	int32_t tfo_syn;
8123 	struct tcp_bbr *bbr;
8124 
8125 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8126 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8127 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8128 	if ((thflags & TH_ACK) &&
8129 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8130 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8131 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8132 		/* keep track of pure window updates */
8133 		if (tlen == 0 &&
8134 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8135 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8136 		tp->snd_wnd = tiwin;
8137 		tp->snd_wl1 = th->th_seq;
8138 		tp->snd_wl2 = th->th_ack;
8139 		if (tp->snd_wnd > tp->max_sndwnd)
8140 			tp->max_sndwnd = tp->snd_wnd;
8141 		bbr->r_wanted_output = 1;
8142 	} else if (thflags & TH_ACK) {
8143 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8144 			tp->snd_wnd = tiwin;
8145 			tp->snd_wl1 = th->th_seq;
8146 			tp->snd_wl2 = th->th_ack;
8147 		}
8148 	}
8149 	if (tp->snd_wnd < ctf_outstanding(tp))
8150 		/* The peer collapsed its window on us */
8151 		bbr_collapsed_window(bbr);
8152  	else if (bbr->rc_has_collapsed)
8153 		bbr_un_collapse_window(bbr);
8154 	/* Was persist timer active and now we have window space? */
8155 	if ((bbr->rc_in_persist != 0) &&
8156 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8157 				bbr_minseg(bbr)))) {
8158 		/*
8159 		 * Make the rate persist at end of persist mode if idle long
8160 		 * enough
8161 		 */
8162 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8163 
8164 		/* Make sure we output to start the timer */
8165 		bbr->r_wanted_output = 1;
8166 	}
8167 	/* Do we need to enter persist? */
8168 	if ((bbr->rc_in_persist == 0) &&
8169 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8170 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8171 	    (tp->snd_max == tp->snd_una) &&
8172 	    sbavail(&so->so_snd) &&
8173 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8174 		/* No send window.. we must enter persist */
8175 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8176 	}
8177 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8178 		m_freem(m);
8179 		return (0);
8180 	}
8181 	/*
8182 	 * We don't support urgent data but
8183 	 * drag along the up just to make sure
8184 	 * if there is a stack switch no one
8185 	 * is surprised.
8186 	 */
8187 	tp->rcv_up = tp->rcv_nxt;
8188 
8189 	/*
8190 	 * Process the segment text, merging it into the TCP sequencing
8191 	 * queue, and arranging for acknowledgment of receipt if necessary.
8192 	 * This process logically involves adjusting tp->rcv_wnd as data is
8193 	 * presented to the user (this happens in tcp_usrreq.c, case
8194 	 * PRU_RCVD).  If a FIN has already been received on this connection
8195 	 * then we just ignore the text.
8196 	 */
8197 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8198 		   IS_FASTOPEN(tp->t_flags));
8199 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8200 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8201 		tcp_seq save_start = th->th_seq;
8202 		tcp_seq save_rnxt  = tp->rcv_nxt;
8203 		int     save_tlen  = tlen;
8204 
8205 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8206 		/*
8207 		 * Insert segment which includes th into TCP reassembly
8208 		 * queue with control block tp.  Set thflags to whether
8209 		 * reassembly now includes a segment with FIN.  This handles
8210 		 * the common case inline (segment is the next to be
8211 		 * received on an established connection, and the queue is
8212 		 * empty), avoiding linkage into and removal from the queue
8213 		 * and repetition of various conversions. Set DELACK for
8214 		 * segments received in order, but ack immediately when
8215 		 * segments are out of order (so fast retransmit can work).
8216 		 */
8217 		if (th->th_seq == tp->rcv_nxt &&
8218 		    SEGQ_EMPTY(tp) &&
8219 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8220 		    tfo_syn)) {
8221 #ifdef NETFLIX_SB_LIMITS
8222 			u_int mcnt, appended;
8223 
8224 			if (so->so_rcv.sb_shlim) {
8225 				mcnt = m_memcnt(m);
8226 				appended = 0;
8227 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8228 				    CFO_NOSLEEP, NULL) == false) {
8229 					counter_u64_add(tcp_sb_shlim_fails, 1);
8230 					m_freem(m);
8231 					return (0);
8232 				}
8233 			}
8234 
8235 #endif
8236 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8237 				bbr->bbr_segs_rcvd += max(1, nsegs);
8238 				tp->t_flags |= TF_DELACK;
8239 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8240 			} else {
8241 				bbr->r_wanted_output = 1;
8242 				tp->t_flags |= TF_ACKNOW;
8243 			}
8244 			tp->rcv_nxt += tlen;
8245 			if (tlen &&
8246 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8247 			    (tp->t_fbyte_in == 0)) {
8248 				tp->t_fbyte_in = ticks;
8249 				if (tp->t_fbyte_in == 0)
8250 					tp->t_fbyte_in = 1;
8251 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8252 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8253 			}
8254 			thflags = tcp_get_flags(th) & TH_FIN;
8255 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8256 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8257 			SOCKBUF_LOCK(&so->so_rcv);
8258 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8259 				m_freem(m);
8260 			else
8261 #ifdef NETFLIX_SB_LIMITS
8262 				appended =
8263 #endif
8264 					sbappendstream_locked(&so->so_rcv, m, 0);
8265 			/* NB: sorwakeup_locked() does an implicit unlock. */
8266 			sorwakeup_locked(so);
8267 #ifdef NETFLIX_SB_LIMITS
8268 			if (so->so_rcv.sb_shlim && appended != mcnt)
8269 				counter_fo_release(so->so_rcv.sb_shlim,
8270 				    mcnt - appended);
8271 #endif
8272 
8273 		} else {
8274 			/*
8275 			 * XXX: Due to the header drop above "th" is
8276 			 * theoretically invalid by now.  Fortunately
8277 			 * m_adj() doesn't actually frees any mbufs when
8278 			 * trimming from the head.
8279 			 */
8280 			tcp_seq temp = save_start;
8281 
8282 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8283 			tp->t_flags |= TF_ACKNOW;
8284 			if (tp->t_flags & TF_WAKESOR) {
8285 				tp->t_flags &= ~TF_WAKESOR;
8286 				/* NB: sorwakeup_locked() does an implicit unlock. */
8287 				sorwakeup_locked(so);
8288 			}
8289 		}
8290 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8291 		    (save_tlen > 0) &&
8292 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8293 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8294 				/*
8295 				 * DSACK actually handled in the fastpath
8296 				 * above.
8297 				 */
8298 				tcp_update_sack_list(tp, save_start,
8299 				    save_start + save_tlen);
8300 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8301 				if ((tp->rcv_numsacks >= 1) &&
8302 				    (tp->sackblks[0].end == save_start)) {
8303 					/*
8304 					 * Partial overlap, recorded at todrop
8305 					 * above.
8306 					 */
8307 					tcp_update_sack_list(tp,
8308 					    tp->sackblks[0].start,
8309 					    tp->sackblks[0].end);
8310 				} else {
8311 					tcp_update_dsack_list(tp, save_start,
8312 					    save_start + save_tlen);
8313 				}
8314 			} else if (tlen >= save_tlen) {
8315 				/* Update of sackblks. */
8316 				tcp_update_dsack_list(tp, save_start,
8317 				    save_start + save_tlen);
8318 			} else if (tlen > 0) {
8319 				tcp_update_dsack_list(tp, save_start,
8320 				    save_start + tlen);
8321 			}
8322 		}
8323 	} else {
8324 		m_freem(m);
8325 		thflags &= ~TH_FIN;
8326 	}
8327 
8328 	/*
8329 	 * If FIN is received ACK the FIN and let the user know that the
8330 	 * connection is closing.
8331 	 */
8332 	if (thflags & TH_FIN) {
8333 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8334 			/* The socket upcall is handled by socantrcvmore. */
8335 			socantrcvmore(so);
8336 			/*
8337 			 * If connection is half-synchronized (ie NEEDSYN
8338 			 * flag on) then delay ACK, so it may be piggybacked
8339 			 * when SYN is sent. Otherwise, since we received a
8340 			 * FIN then no more input can be expected, send ACK
8341 			 * now.
8342 			 */
8343 			if (tp->t_flags & TF_NEEDSYN) {
8344 				tp->t_flags |= TF_DELACK;
8345 				bbr_timer_cancel(bbr,
8346 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8347 			} else {
8348 				tp->t_flags |= TF_ACKNOW;
8349 			}
8350 			tp->rcv_nxt++;
8351 		}
8352 		switch (tp->t_state) {
8353 			/*
8354 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8355 			 * CLOSE_WAIT state.
8356 			 */
8357 		case TCPS_SYN_RECEIVED:
8358 			tp->t_starttime = ticks;
8359 			/* FALLTHROUGH */
8360 		case TCPS_ESTABLISHED:
8361 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8362 			break;
8363 
8364 			/*
8365 			 * If still in FIN_WAIT_1 STATE FIN has not been
8366 			 * acked so enter the CLOSING state.
8367 			 */
8368 		case TCPS_FIN_WAIT_1:
8369 			tcp_state_change(tp, TCPS_CLOSING);
8370 			break;
8371 
8372 			/*
8373 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8374 			 * starting the time-wait timer, turning off the
8375 			 * other standard timers.
8376 			 */
8377 		case TCPS_FIN_WAIT_2:
8378 			bbr->rc_timer_first = 1;
8379 			bbr_timer_cancel(bbr,
8380 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8381 			tcp_twstart(tp);
8382 			return (1);
8383 		}
8384 	}
8385 	/*
8386 	 * Return any desired output.
8387 	 */
8388 	if ((tp->t_flags & TF_ACKNOW) ||
8389 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8390 		bbr->r_wanted_output = 1;
8391 	}
8392 	return (0);
8393 }
8394 
8395 /*
8396  * Here nothing is really faster, its just that we
8397  * have broken out the fast-data path also just like
8398  * the fast-ack. Return 1 if we processed the packet
8399  * return 0 if you need to take the "slow-path".
8400  */
8401 static int
8402 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8403     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8404     uint32_t tiwin, int32_t nxt_pkt)
8405 {
8406 	uint16_t nsegs;
8407 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8408 	struct tcp_bbr *bbr;
8409 #ifdef NETFLIX_SB_LIMITS
8410 	u_int mcnt, appended;
8411 #endif
8412 #ifdef TCPDEBUG
8413 	/*
8414 	 * The size of tcp_saveipgen must be the size of the max ip header,
8415 	 * now IPv6.
8416 	 */
8417 	u_char tcp_saveipgen[IP6_HDR_LEN];
8418 	struct tcphdr tcp_savetcp;
8419 	short ostate = 0;
8420 
8421 #endif
8422 	/* On the hpts and we would have called output */
8423 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8424 
8425 	/*
8426 	 * If last ACK falls within this segment's sequence numbers, record
8427 	 * the timestamp. NOTE that the test is modified according to the
8428 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8429 	 */
8430 	if (bbr->r_ctl.rc_resend != NULL) {
8431 		return (0);
8432 	}
8433 	if (tiwin && tiwin != tp->snd_wnd) {
8434 		return (0);
8435 	}
8436 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8437 		return (0);
8438 	}
8439 	if (__predict_false((to->to_flags & TOF_TS) &&
8440 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8441 		return (0);
8442 	}
8443 	if (__predict_false((th->th_ack != tp->snd_una))) {
8444 		return (0);
8445 	}
8446 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8447 		return (0);
8448 	}
8449 	if ((to->to_flags & TOF_TS) != 0 &&
8450 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8451 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8452 		tp->ts_recent = to->to_tsval;
8453 	}
8454 	/*
8455 	 * This is a pure, in-sequence data packet with nothing on the
8456 	 * reassembly queue and we have enough buffer space to take it.
8457 	 */
8458 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8459 
8460 #ifdef NETFLIX_SB_LIMITS
8461 	if (so->so_rcv.sb_shlim) {
8462 		mcnt = m_memcnt(m);
8463 		appended = 0;
8464 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8465 		    CFO_NOSLEEP, NULL) == false) {
8466 			counter_u64_add(tcp_sb_shlim_fails, 1);
8467 			m_freem(m);
8468 			return (1);
8469 		}
8470 	}
8471 #endif
8472 	/* Clean receiver SACK report if present */
8473 	if (tp->rcv_numsacks)
8474 		tcp_clean_sackreport(tp);
8475 	KMOD_TCPSTAT_INC(tcps_preddat);
8476 	tp->rcv_nxt += tlen;
8477 	if (tlen &&
8478 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8479 	    (tp->t_fbyte_in == 0)) {
8480 		tp->t_fbyte_in = ticks;
8481 		if (tp->t_fbyte_in == 0)
8482 			tp->t_fbyte_in = 1;
8483 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8484 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8485 	}
8486 	/*
8487 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8488 	 */
8489 	tp->snd_wl1 = th->th_seq;
8490 	/*
8491 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8492 	 */
8493 	tp->rcv_up = tp->rcv_nxt;
8494 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8495 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8496 #ifdef TCPDEBUG
8497 	if (so->so_options & SO_DEBUG)
8498 		tcp_trace(TA_INPUT, ostate, tp,
8499 		    (void *)tcp_saveipgen, &tcp_savetcp, 0);
8500 #endif
8501 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8502 
8503 	/* Add data to socket buffer. */
8504 	SOCKBUF_LOCK(&so->so_rcv);
8505 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8506 		m_freem(m);
8507 	} else {
8508 		/*
8509 		 * Set new socket buffer size. Give up when limit is
8510 		 * reached.
8511 		 */
8512 		if (newsize)
8513 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8514 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8515 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8516 
8517 #ifdef NETFLIX_SB_LIMITS
8518 		appended =
8519 #endif
8520 			sbappendstream_locked(&so->so_rcv, m, 0);
8521 		ctf_calc_rwin(so, tp);
8522 	}
8523 	/* NB: sorwakeup_locked() does an implicit unlock. */
8524 	sorwakeup_locked(so);
8525 #ifdef NETFLIX_SB_LIMITS
8526 	if (so->so_rcv.sb_shlim && mcnt != appended)
8527 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8528 #endif
8529 	if (DELAY_ACK(tp, bbr, nsegs)) {
8530 		bbr->bbr_segs_rcvd += max(1, nsegs);
8531 		tp->t_flags |= TF_DELACK;
8532 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8533 	} else {
8534 		bbr->r_wanted_output = 1;
8535 		tp->t_flags |= TF_ACKNOW;
8536 	}
8537 	return (1);
8538 }
8539 
8540 /*
8541  * This subfunction is used to try to highly optimize the
8542  * fast path. We again allow window updates that are
8543  * in sequence to remain in the fast-path. We also add
8544  * in the __predict's to attempt to help the compiler.
8545  * Note that if we return a 0, then we can *not* process
8546  * it and the caller should push the packet into the
8547  * slow-path. If we return 1, then all is well and
8548  * the packet is fully processed.
8549  */
8550 static int
8551 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8552     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8553     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8554 {
8555 	int32_t acked;
8556 	uint16_t nsegs;
8557 	uint32_t sack_changed;
8558 #ifdef TCPDEBUG
8559 	/*
8560 	 * The size of tcp_saveipgen must be the size of the max ip header,
8561 	 * now IPv6.
8562 	 */
8563 	u_char tcp_saveipgen[IP6_HDR_LEN];
8564 	struct tcphdr tcp_savetcp;
8565 	short ostate = 0;
8566 
8567 #endif
8568 	uint32_t prev_acked = 0;
8569 	struct tcp_bbr *bbr;
8570 
8571 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8572 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8573 		return (0);
8574 	}
8575 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8576 		/* Above what we have sent? */
8577 		return (0);
8578 	}
8579 	if (__predict_false(tiwin == 0)) {
8580 		/* zero window */
8581 		return (0);
8582 	}
8583 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8584 		/* We need a SYN or a FIN, unlikely.. */
8585 		return (0);
8586 	}
8587 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8588 		/* Timestamp is behind .. old ack with seq wrap? */
8589 		return (0);
8590 	}
8591 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8592 		/* Still recovering */
8593 		return (0);
8594 	}
8595 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8596 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8597 		/* We are retransmitting */
8598 		return (0);
8599 	}
8600 	if (__predict_false(bbr->rc_in_persist != 0)) {
8601 		/* In persist mode */
8602 		return (0);
8603 	}
8604 	if (bbr->r_ctl.rc_sacked) {
8605 		/* We have sack holes on our scoreboard */
8606 		return (0);
8607 	}
8608 	/* Ok if we reach here, we can process a fast-ack */
8609 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8610 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8611 	/*
8612 	 * We never detect loss in fast ack [we can't
8613 	 * have a sack and can't be in recovery so
8614 	 * we always pass 0 (nothing detected)].
8615 	 */
8616 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8617 	/* Did the window get updated? */
8618 	if (tiwin != tp->snd_wnd) {
8619 		tp->snd_wnd = tiwin;
8620 		tp->snd_wl1 = th->th_seq;
8621 		if (tp->snd_wnd > tp->max_sndwnd)
8622 			tp->max_sndwnd = tp->snd_wnd;
8623 	}
8624 	/* Do we need to exit persists? */
8625 	if ((bbr->rc_in_persist != 0) &&
8626 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8627 			       bbr_minseg(bbr)))) {
8628 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8629 		bbr->r_wanted_output = 1;
8630 	}
8631 	/* Do we need to enter persists? */
8632 	if ((bbr->rc_in_persist == 0) &&
8633 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8634 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8635 	    (tp->snd_max == tp->snd_una) &&
8636 	    sbavail(&so->so_snd) &&
8637 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8638 		/* No send window.. we must enter persist */
8639 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8640 	}
8641 	/*
8642 	 * If last ACK falls within this segment's sequence numbers, record
8643 	 * the timestamp. NOTE that the test is modified according to the
8644 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8645 	 */
8646 	if ((to->to_flags & TOF_TS) != 0 &&
8647 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8648 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8649 		tp->ts_recent = to->to_tsval;
8650 	}
8651 	/*
8652 	 * This is a pure ack for outstanding data.
8653 	 */
8654 	KMOD_TCPSTAT_INC(tcps_predack);
8655 
8656 	/*
8657 	 * "bad retransmit" recovery.
8658 	 */
8659 	if (tp->t_flags & TF_PREVVALID) {
8660 		tp->t_flags &= ~TF_PREVVALID;
8661 		if (tp->t_rxtshift == 1 &&
8662 		    (int)(ticks - tp->t_badrxtwin) < 0)
8663 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8664 	}
8665 	/*
8666 	 * Recalculate the transmit timer / rtt.
8667 	 *
8668 	 * Some boxes send broken timestamp replies during the SYN+ACK
8669 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8670 	 * and blow up the retransmit timer.
8671 	 */
8672 	acked = BYTES_THIS_ACK(tp, th);
8673 
8674 #ifdef TCP_HHOOK
8675 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8676 	hhook_run_tcp_est_in(tp, th, to);
8677 #endif
8678 
8679 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8680 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8681 	sbdrop(&so->so_snd, acked);
8682 
8683 	if (SEQ_GT(th->th_ack, tp->snd_una))
8684 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8685 	tp->snd_una = th->th_ack;
8686 	if (tp->snd_wnd < ctf_outstanding(tp))
8687 		/* The peer collapsed its window on us */
8688 		bbr_collapsed_window(bbr);
8689 	else if (bbr->rc_has_collapsed)
8690 		bbr_un_collapse_window(bbr);
8691 
8692 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8693 		tp->snd_recover = tp->snd_una;
8694 	}
8695 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8696 	/*
8697 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8698 	 */
8699 	tp->snd_wl2 = th->th_ack;
8700 	m_freem(m);
8701 	/*
8702 	 * If all outstanding data are acked, stop retransmit timer,
8703 	 * otherwise restart timer using current (possibly backed-off)
8704 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8705 	 * If data are ready to send, let tcp_output decide between more
8706 	 * output or persist.
8707 	 */
8708 #ifdef TCPDEBUG
8709 	if (so->so_options & SO_DEBUG)
8710 		tcp_trace(TA_INPUT, ostate, tp,
8711 		    (void *)tcp_saveipgen,
8712 		    &tcp_savetcp, 0);
8713 #endif
8714 	/* Wake up the socket if we have room to write more */
8715 	sowwakeup(so);
8716 	if (tp->snd_una == tp->snd_max) {
8717 		/* Nothing left outstanding */
8718 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8719 		if (sbavail(&so->so_snd) == 0)
8720 			bbr->rc_tp->t_acktime = 0;
8721 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8722 		if (bbr->rc_in_persist == 0) {
8723 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8724 		}
8725 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8726 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8727 		/*
8728 		 * We invalidate the last ack here since we
8729 		 * don't want to transfer forward the time
8730 		 * for our sum's calculations.
8731 		 */
8732 		bbr->r_wanted_output = 1;
8733 	}
8734 	if (sbavail(&so->so_snd)) {
8735 		bbr->r_wanted_output = 1;
8736 	}
8737 	return (1);
8738 }
8739 
8740 /*
8741  * Return value of 1, the TCB is unlocked and most
8742  * likely gone, return value of 0, the TCB is still
8743  * locked.
8744  */
8745 static int
8746 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8747     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8748     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8749 {
8750 	int32_t todrop;
8751 	int32_t ourfinisacked = 0;
8752 	struct tcp_bbr *bbr;
8753 	int32_t ret_val = 0;
8754 
8755 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8756 
8757 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8758 	ctf_calc_rwin(so, tp);
8759 	/*
8760 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8761 	 * SYN, drop the input. if seg contains a RST, then drop the
8762 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8763 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8764 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8765 	 * not support ECN so we will not say we are capable. if SYN has
8766 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8767 	 * segment to be acked (eventually) continue processing rest of
8768 	 * data/controls, beginning with URG
8769 	 */
8770 	if ((thflags & TH_ACK) &&
8771 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8772 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8773 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8774 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8775 		return (1);
8776 	}
8777 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8778 		TCP_PROBE5(connect__refused, NULL, tp,
8779 		    mtod(m, const char *), tp, th);
8780 		tp = tcp_drop(tp, ECONNREFUSED);
8781 		ctf_do_drop(m, tp);
8782 		return (1);
8783 	}
8784 	if (thflags & TH_RST) {
8785 		ctf_do_drop(m, tp);
8786 		return (1);
8787 	}
8788 	if (!(thflags & TH_SYN)) {
8789 		ctf_do_drop(m, tp);
8790 		return (1);
8791 	}
8792 	tp->irs = th->th_seq;
8793 	tcp_rcvseqinit(tp);
8794 	if (thflags & TH_ACK) {
8795 		int tfo_partial = 0;
8796 
8797 		KMOD_TCPSTAT_INC(tcps_connects);
8798 		soisconnected(so);
8799 #ifdef MAC
8800 		mac_socketpeer_set_from_mbuf(m, so);
8801 #endif
8802 		/* Do window scaling on this connection? */
8803 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8804 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8805 			tp->rcv_scale = tp->request_r_scale;
8806 		}
8807 		tp->rcv_adv += min(tp->rcv_wnd,
8808 		    TCP_MAXWIN << tp->rcv_scale);
8809 		/*
8810 		 * If not all the data that was sent in the TFO SYN
8811 		 * has been acked, resend the remainder right away.
8812 		 */
8813 		if (IS_FASTOPEN(tp->t_flags) &&
8814 		    (tp->snd_una != tp->snd_max)) {
8815 			tp->snd_nxt = th->th_ack;
8816 			tfo_partial = 1;
8817 		}
8818 		/*
8819 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8820 		 * will be turned on later.
8821 		 */
8822 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8823 			bbr->bbr_segs_rcvd += 1;
8824 			tp->t_flags |= TF_DELACK;
8825 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8826 		} else {
8827 			bbr->r_wanted_output = 1;
8828 			tp->t_flags |= TF_ACKNOW;
8829 		}
8830 		if (SEQ_GT(th->th_ack, tp->iss)) {
8831 			/*
8832 			 * The SYN is acked
8833 			 * handle it specially.
8834 			 */
8835 			bbr_log_syn(tp, to);
8836 		}
8837 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8838 			/*
8839 			 * We advance snd_una for the
8840 			 * fast open case. If th_ack is
8841 			 * acknowledging data beyond
8842 			 * snd_una we can't just call
8843 			 * ack-processing since the
8844 			 * data stream in our send-map
8845 			 * will start at snd_una + 1 (one
8846 			 * beyond the SYN). If its just
8847 			 * equal we don't need to do that
8848 			 * and there is no send_map.
8849 			 */
8850 			tp->snd_una++;
8851 		}
8852 		/*
8853 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8854 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8855 		 */
8856 		tp->t_starttime = ticks;
8857 		if (tp->t_flags & TF_NEEDFIN) {
8858 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8859 			tp->t_flags &= ~TF_NEEDFIN;
8860 			thflags &= ~TH_SYN;
8861 		} else {
8862 			tcp_state_change(tp, TCPS_ESTABLISHED);
8863 			TCP_PROBE5(connect__established, NULL, tp,
8864 			    mtod(m, const char *), tp, th);
8865 			cc_conn_init(tp);
8866 		}
8867 	} else {
8868 		/*
8869 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8870 		 * open.  If segment contains CC option and there is a
8871 		 * cached CC, apply TAO test. If it succeeds, connection is *
8872 		 * half-synchronized. Otherwise, do 3-way handshake:
8873 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8874 		 * there was no CC option, clear cached CC value.
8875 		 */
8876 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
8877 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8878 	}
8879 	/*
8880 	 * Advance th->th_seq to correspond to first data byte. If data,
8881 	 * trim to stay within window, dropping FIN if necessary.
8882 	 */
8883 	th->th_seq++;
8884 	if (tlen > tp->rcv_wnd) {
8885 		todrop = tlen - tp->rcv_wnd;
8886 		m_adj(m, -todrop);
8887 		tlen = tp->rcv_wnd;
8888 		thflags &= ~TH_FIN;
8889 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8890 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8891 	}
8892 	tp->snd_wl1 = th->th_seq - 1;
8893 	tp->rcv_up = th->th_seq;
8894 	/*
8895 	 * Client side of transaction: already sent SYN and data. If the
8896 	 * remote host used T/TCP to validate the SYN, our data will be
8897 	 * ACK'd; if so, enter normal data segment processing in the middle
8898 	 * of step 5, ack processing. Otherwise, goto step 6.
8899 	 */
8900 	if (thflags & TH_ACK) {
8901 		if ((to->to_flags & TOF_TS) != 0) {
8902 			uint32_t t, rtt;
8903 
8904 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8905 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8906 				rtt = t - to->to_tsecr;
8907 				if (rtt == 0) {
8908 					rtt = 1;
8909 				}
8910 				rtt *= MS_IN_USEC;
8911 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8912 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8913 						       rtt, bbr->r_ctl.rc_rcvtime);
8914 			}
8915 		}
8916 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8917 			return (ret_val);
8918 		/* We may have changed to FIN_WAIT_1 above */
8919 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8920 			/*
8921 			 * In FIN_WAIT_1 STATE in addition to the processing
8922 			 * for the ESTABLISHED state if our FIN is now
8923 			 * acknowledged then enter FIN_WAIT_2.
8924 			 */
8925 			if (ourfinisacked) {
8926 				/*
8927 				 * If we can't receive any more data, then
8928 				 * closing user can proceed. Starting the
8929 				 * timer is contrary to the specification,
8930 				 * but if we don't get a FIN we'll hang
8931 				 * forever.
8932 				 *
8933 				 * XXXjl: we should release the tp also, and
8934 				 * use a compressed state.
8935 				 */
8936 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8937 					soisdisconnected(so);
8938 					tcp_timer_activate(tp, TT_2MSL,
8939 					    (tcp_fast_finwait2_recycle ?
8940 					    tcp_finwait2_timeout :
8941 					    TP_MAXIDLE(tp)));
8942 				}
8943 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8944 			}
8945 		}
8946 	}
8947 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8948 	    tiwin, thflags, nxt_pkt));
8949 }
8950 
8951 /*
8952  * Return value of 1, the TCB is unlocked and most
8953  * likely gone, return value of 0, the TCB is still
8954  * locked.
8955  */
8956 static int
8957 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8958 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8959 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8960 {
8961 	int32_t ourfinisacked = 0;
8962 	int32_t ret_val;
8963 	struct tcp_bbr *bbr;
8964 
8965 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8966 
8967 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8968 	ctf_calc_rwin(so, tp);
8969 	if ((thflags & TH_ACK) &&
8970 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8971 	     SEQ_GT(th->th_ack, tp->snd_max))) {
8972 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8973 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8974 		return (1);
8975 	}
8976 	if (IS_FASTOPEN(tp->t_flags)) {
8977 		/*
8978 		 * When a TFO connection is in SYN_RECEIVED, the only valid
8979 		 * packets are the initial SYN, a retransmit/copy of the
8980 		 * initial SYN (possibly with a subset of the original
8981 		 * data), a valid ACK, a FIN, or a RST.
8982 		 */
8983 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
8984 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8985 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8986 			return (1);
8987 		} else if (thflags & TH_SYN) {
8988 			/* non-initial SYN is ignored */
8989 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
8990 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
8991 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
8992 				ctf_do_drop(m, NULL);
8993 				return (0);
8994 			}
8995 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
8996 			ctf_do_drop(m, NULL);
8997 			return (0);
8998 		}
8999 	}
9000 	if ((thflags & TH_RST) ||
9001 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9002 		return (ctf_process_rst(m, th, so, tp));
9003 	/*
9004 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9005 	 * it's less than ts_recent, drop it.
9006 	 */
9007 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9008 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9009 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9010 			return (ret_val);
9011 	}
9012 	/*
9013 	 * In the SYN-RECEIVED state, validate that the packet belongs to
9014 	 * this connection before trimming the data to fit the receive
9015 	 * window.  Check the sequence number versus IRS since we know the
9016 	 * sequence numbers haven't wrapped.  This is a partial fix for the
9017 	 * "LAND" DoS attack.
9018 	 */
9019 	if (SEQ_LT(th->th_seq, tp->irs)) {
9020 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
9021 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9022 		return (1);
9023 	}
9024 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9025 		return (ret_val);
9026 	}
9027 	/*
9028 	 * If last ACK falls within this segment's sequence numbers, record
9029 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9030 	 * from the latest proposal of the tcplw@cray.com list (Braden
9031 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9032 	 * with our earlier PAWS tests, so this check should be solely
9033 	 * predicated on the sequence space of this segment. 3) That we
9034 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9035 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9036 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9037 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9038 	 * p.869. In such cases, we can still calculate the RTT correctly
9039 	 * when RCV.NXT == Last.ACK.Sent.
9040 	 */
9041 	if ((to->to_flags & TOF_TS) != 0 &&
9042 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9043 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9044 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9045 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9046 		tp->ts_recent = to->to_tsval;
9047 	}
9048 	tp->snd_wnd = tiwin;
9049 	/*
9050 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9051 	 * is on (half-synchronized state), then queue data for later
9052 	 * processing; else drop segment and return.
9053 	 */
9054 	if ((thflags & TH_ACK) == 0) {
9055 		if (IS_FASTOPEN(tp->t_flags)) {
9056 			cc_conn_init(tp);
9057 		}
9058 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9059 					 tiwin, thflags, nxt_pkt));
9060 	}
9061 	KMOD_TCPSTAT_INC(tcps_connects);
9062 	if (tp->t_flags & TF_SONOTCONN) {
9063 		tp->t_flags &= ~TF_SONOTCONN;
9064 		soisconnected(so);
9065 	}
9066 	/* Do window scaling? */
9067 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9068 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9069 		tp->rcv_scale = tp->request_r_scale;
9070 	}
9071 	/*
9072 	 * ok for the first time in lets see if we can use the ts to figure
9073 	 * out what the initial RTT was.
9074 	 */
9075 	if ((to->to_flags & TOF_TS) != 0) {
9076 		uint32_t t, rtt;
9077 
9078 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9079 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9080 			rtt = t - to->to_tsecr;
9081 			if (rtt == 0) {
9082 				rtt = 1;
9083 			}
9084 			rtt *= MS_IN_USEC;
9085 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9086 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9087 		}
9088 	}
9089 	/* Drop off any SYN in the send map (probably not there)  */
9090 	if (thflags & TH_ACK)
9091 		bbr_log_syn(tp, to);
9092 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9093 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9094 		tp->t_tfo_pending = NULL;
9095 	}
9096 	/*
9097 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9098 	 * FIN-WAIT-1
9099 	 */
9100 	tp->t_starttime = ticks;
9101 	if (tp->t_flags & TF_NEEDFIN) {
9102 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9103 		tp->t_flags &= ~TF_NEEDFIN;
9104 	} else {
9105 		tcp_state_change(tp, TCPS_ESTABLISHED);
9106 		TCP_PROBE5(accept__established, NULL, tp,
9107 			   mtod(m, const char *), tp, th);
9108 		/*
9109 		 * TFO connections call cc_conn_init() during SYN
9110 		 * processing.  Calling it again here for such connections
9111 		 * is not harmless as it would undo the snd_cwnd reduction
9112 		 * that occurs when a TFO SYN|ACK is retransmitted.
9113 		 */
9114 		if (!IS_FASTOPEN(tp->t_flags))
9115 			cc_conn_init(tp);
9116 	}
9117 	/*
9118 	 * Account for the ACK of our SYN prior to
9119 	 * regular ACK processing below, except for
9120 	 * simultaneous SYN, which is handled later.
9121 	 */
9122 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9123 		tp->snd_una++;
9124 	/*
9125 	 * If segment contains data or ACK, will call tcp_reass() later; if
9126 	 * not, do so now to pass queued data to user.
9127 	 */
9128 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9129 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9130 			(struct mbuf *)0);
9131 		if (tp->t_flags & TF_WAKESOR) {
9132 			tp->t_flags &= ~TF_WAKESOR;
9133 			/* NB: sorwakeup_locked() does an implicit unlock. */
9134 			sorwakeup_locked(so);
9135 		}
9136 	}
9137 	tp->snd_wl1 = th->th_seq - 1;
9138 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9139 		return (ret_val);
9140 	}
9141 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9142 		/* We could have went to FIN_WAIT_1 (or EST) above */
9143 		/*
9144 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9145 		 * ESTABLISHED state if our FIN is now acknowledged then
9146 		 * enter FIN_WAIT_2.
9147 		 */
9148 		if (ourfinisacked) {
9149 			/*
9150 			 * If we can't receive any more data, then closing
9151 			 * user can proceed. Starting the timer is contrary
9152 			 * to the specification, but if we don't get a FIN
9153 			 * we'll hang forever.
9154 			 *
9155 			 * XXXjl: we should release the tp also, and use a
9156 			 * compressed state.
9157 			 */
9158 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9159 				soisdisconnected(so);
9160 				tcp_timer_activate(tp, TT_2MSL,
9161 						   (tcp_fast_finwait2_recycle ?
9162 						    tcp_finwait2_timeout :
9163 						    TP_MAXIDLE(tp)));
9164 			}
9165 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9166 		}
9167 	}
9168 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9169 				 tiwin, thflags, nxt_pkt));
9170 }
9171 
9172 /*
9173  * Return value of 1, the TCB is unlocked and most
9174  * likely gone, return value of 0, the TCB is still
9175  * locked.
9176  */
9177 static int
9178 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9179     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9180     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9181 {
9182 	struct tcp_bbr *bbr;
9183 	int32_t ret_val;
9184 
9185 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9186 
9187 	/*
9188 	 * Header prediction: check for the two common cases of a
9189 	 * uni-directional data xfer.  If the packet has no control flags,
9190 	 * is in-sequence, the window didn't change and we're not
9191 	 * retransmitting, it's a candidate.  If the length is zero and the
9192 	 * ack moved forward, we're the sender side of the xfer.  Just free
9193 	 * the data acked & wake any higher level process that was blocked
9194 	 * waiting for space.  If the length is non-zero and the ack didn't
9195 	 * move, we're the receiver side.  If we're getting packets in-order
9196 	 * (the reassembly queue is empty), add the data toc The socket
9197 	 * buffer and note that we need a delayed ack. Make sure that the
9198 	 * hidden state-flags are also off. Since we check for
9199 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9200 	 */
9201 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9202 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9203 		/*
9204 		 * If we have delived under 4 segments increase the initial
9205 		 * window if raised by the peer. We use this to determine
9206 		 * dynamic and static rwnd's at the end of a connection.
9207 		 */
9208 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9209 	}
9210 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9211 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9212 	    __predict_true(SEGQ_EMPTY(tp)) &&
9213 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9214 		if (tlen == 0) {
9215 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9216 			    tiwin, nxt_pkt, iptos)) {
9217 				return (0);
9218 			}
9219 		} else {
9220 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9221 			    tiwin, nxt_pkt)) {
9222 				return (0);
9223 			}
9224 		}
9225 	}
9226 	ctf_calc_rwin(so, tp);
9227 
9228 	if ((thflags & TH_RST) ||
9229 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9230 		return (ctf_process_rst(m, th, so, tp));
9231 	/*
9232 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9233 	 * synchronized state.
9234 	 */
9235 	if (thflags & TH_SYN) {
9236 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9237 		return (ret_val);
9238 	}
9239 	/*
9240 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9241 	 * it's less than ts_recent, drop it.
9242 	 */
9243 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9244 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9245 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9246 			return (ret_val);
9247 	}
9248 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9249 		return (ret_val);
9250 	}
9251 	/*
9252 	 * If last ACK falls within this segment's sequence numbers, record
9253 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9254 	 * from the latest proposal of the tcplw@cray.com list (Braden
9255 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9256 	 * with our earlier PAWS tests, so this check should be solely
9257 	 * predicated on the sequence space of this segment. 3) That we
9258 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9259 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9260 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9261 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9262 	 * p.869. In such cases, we can still calculate the RTT correctly
9263 	 * when RCV.NXT == Last.ACK.Sent.
9264 	 */
9265 	if ((to->to_flags & TOF_TS) != 0 &&
9266 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9267 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9268 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9269 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9270 		tp->ts_recent = to->to_tsval;
9271 	}
9272 	/*
9273 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9274 	 * is on (half-synchronized state), then queue data for later
9275 	 * processing; else drop segment and return.
9276 	 */
9277 	if ((thflags & TH_ACK) == 0) {
9278 		if (tp->t_flags & TF_NEEDSYN) {
9279 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9280 			    tiwin, thflags, nxt_pkt));
9281 		} else if (tp->t_flags & TF_ACKNOW) {
9282 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9283 			bbr->r_wanted_output = 1;
9284 			return (ret_val);
9285 		} else {
9286 			ctf_do_drop(m, NULL);
9287 			return (0);
9288 		}
9289 	}
9290 	/*
9291 	 * Ack processing.
9292 	 */
9293 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9294 		return (ret_val);
9295 	}
9296 	if (sbavail(&so->so_snd)) {
9297 		if (ctf_progress_timeout_check(tp, true)) {
9298 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9299 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9300 			return (1);
9301 		}
9302 	}
9303 	/* State changes only happen in bbr_process_data() */
9304 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9305 	    tiwin, thflags, nxt_pkt));
9306 }
9307 
9308 /*
9309  * Return value of 1, the TCB is unlocked and most
9310  * likely gone, return value of 0, the TCB is still
9311  * locked.
9312  */
9313 static int
9314 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9315     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9316     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9317 {
9318 	struct tcp_bbr *bbr;
9319 	int32_t ret_val;
9320 
9321 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9322 
9323 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9324 	ctf_calc_rwin(so, tp);
9325 	if ((thflags & TH_RST) ||
9326 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9327 		return (ctf_process_rst(m, th, so, tp));
9328 	/*
9329 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9330 	 * synchronized state.
9331 	 */
9332 	if (thflags & TH_SYN) {
9333 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9334 		return (ret_val);
9335 	}
9336 	/*
9337 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9338 	 * it's less than ts_recent, drop it.
9339 	 */
9340 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9341 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9342 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9343 			return (ret_val);
9344 	}
9345 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9346 		return (ret_val);
9347 	}
9348 	/*
9349 	 * If last ACK falls within this segment's sequence numbers, record
9350 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9351 	 * from the latest proposal of the tcplw@cray.com list (Braden
9352 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9353 	 * with our earlier PAWS tests, so this check should be solely
9354 	 * predicated on the sequence space of this segment. 3) That we
9355 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9356 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9357 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9358 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9359 	 * p.869. In such cases, we can still calculate the RTT correctly
9360 	 * when RCV.NXT == Last.ACK.Sent.
9361 	 */
9362 	if ((to->to_flags & TOF_TS) != 0 &&
9363 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9364 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9365 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9366 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9367 		tp->ts_recent = to->to_tsval;
9368 	}
9369 	/*
9370 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9371 	 * is on (half-synchronized state), then queue data for later
9372 	 * processing; else drop segment and return.
9373 	 */
9374 	if ((thflags & TH_ACK) == 0) {
9375 		if (tp->t_flags & TF_NEEDSYN) {
9376 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9377 			    tiwin, thflags, nxt_pkt));
9378 		} else if (tp->t_flags & TF_ACKNOW) {
9379 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9380 			bbr->r_wanted_output = 1;
9381 			return (ret_val);
9382 		} else {
9383 			ctf_do_drop(m, NULL);
9384 			return (0);
9385 		}
9386 	}
9387 	/*
9388 	 * Ack processing.
9389 	 */
9390 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9391 		return (ret_val);
9392 	}
9393 	if (sbavail(&so->so_snd)) {
9394 		if (ctf_progress_timeout_check(tp, true)) {
9395 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9396 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9397 			return (1);
9398 		}
9399 	}
9400 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9401 	    tiwin, thflags, nxt_pkt));
9402 }
9403 
9404 static int
9405 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9406     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9407 {
9408 
9409 	if (bbr->rc_allow_data_af_clo == 0) {
9410 close_now:
9411 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9412 		/* tcp_close will kill the inp pre-log the Reset */
9413 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9414 		tp = tcp_close(tp);
9415 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9416 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9417 		return (1);
9418 	}
9419 	if (sbavail(&so->so_snd) == 0)
9420 		goto close_now;
9421 	/* Ok we allow data that is ignored and a followup reset */
9422 	tp->rcv_nxt = th->th_seq + *tlen;
9423 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9424 	bbr->r_wanted_output = 1;
9425 	*tlen = 0;
9426 	return (0);
9427 }
9428 
9429 /*
9430  * Return value of 1, the TCB is unlocked and most
9431  * likely gone, return value of 0, the TCB is still
9432  * locked.
9433  */
9434 static int
9435 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9436     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9437     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9438 {
9439 	int32_t ourfinisacked = 0;
9440 	int32_t ret_val;
9441 	struct tcp_bbr *bbr;
9442 
9443 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9444 
9445 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9446 	ctf_calc_rwin(so, tp);
9447 	if ((thflags & TH_RST) ||
9448 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9449 		return (ctf_process_rst(m, th, so, tp));
9450 	/*
9451 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9452 	 * synchronized state.
9453 	 */
9454 	if (thflags & TH_SYN) {
9455 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9456 		return (ret_val);
9457 	}
9458 	/*
9459 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9460 	 * it's less than ts_recent, drop it.
9461 	 */
9462 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9463 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9464 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9465 			return (ret_val);
9466 	}
9467 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9468 		return (ret_val);
9469 	}
9470 	/*
9471 	 * If new data are received on a connection after the user processes
9472 	 * are gone, then RST the other end.
9473 	 * We call a new function now so we might continue and setup
9474 	 * to reset at all data being ack'd.
9475 	 */
9476 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9477 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9478 		return (1);
9479 	/*
9480 	 * If last ACK falls within this segment's sequence numbers, record
9481 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9482 	 * from the latest proposal of the tcplw@cray.com list (Braden
9483 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9484 	 * with our earlier PAWS tests, so this check should be solely
9485 	 * predicated on the sequence space of this segment. 3) That we
9486 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9487 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9488 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9489 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9490 	 * p.869. In such cases, we can still calculate the RTT correctly
9491 	 * when RCV.NXT == Last.ACK.Sent.
9492 	 */
9493 	if ((to->to_flags & TOF_TS) != 0 &&
9494 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9495 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9496 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9497 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9498 		tp->ts_recent = to->to_tsval;
9499 	}
9500 	/*
9501 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9502 	 * is on (half-synchronized state), then queue data for later
9503 	 * processing; else drop segment and return.
9504 	 */
9505 	if ((thflags & TH_ACK) == 0) {
9506 		if (tp->t_flags & TF_NEEDSYN) {
9507 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9508 			    tiwin, thflags, nxt_pkt));
9509 		} else if (tp->t_flags & TF_ACKNOW) {
9510 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9511 			bbr->r_wanted_output = 1;
9512 			return (ret_val);
9513 		} else {
9514 			ctf_do_drop(m, NULL);
9515 			return (0);
9516 		}
9517 	}
9518 	/*
9519 	 * Ack processing.
9520 	 */
9521 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9522 		return (ret_val);
9523 	}
9524 	if (ourfinisacked) {
9525 		/*
9526 		 * If we can't receive any more data, then closing user can
9527 		 * proceed. Starting the timer is contrary to the
9528 		 * specification, but if we don't get a FIN we'll hang
9529 		 * forever.
9530 		 *
9531 		 * XXXjl: we should release the tp also, and use a
9532 		 * compressed state.
9533 		 */
9534 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9535 			soisdisconnected(so);
9536 			tcp_timer_activate(tp, TT_2MSL,
9537 			    (tcp_fast_finwait2_recycle ?
9538 			    tcp_finwait2_timeout :
9539 			    TP_MAXIDLE(tp)));
9540 		}
9541 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9542 	}
9543 	if (sbavail(&so->so_snd)) {
9544 		if (ctf_progress_timeout_check(tp, true)) {
9545 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9546 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9547 			return (1);
9548 		}
9549 	}
9550 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9551 	    tiwin, thflags, nxt_pkt));
9552 }
9553 
9554 /*
9555  * Return value of 1, the TCB is unlocked and most
9556  * likely gone, return value of 0, the TCB is still
9557  * locked.
9558  */
9559 static int
9560 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9561     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9562     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9563 {
9564 	int32_t ourfinisacked = 0;
9565 	int32_t ret_val;
9566 	struct tcp_bbr *bbr;
9567 
9568 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9569 
9570 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9571 	ctf_calc_rwin(so, tp);
9572 	if ((thflags & TH_RST) ||
9573 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9574 		return (ctf_process_rst(m, th, so, tp));
9575 	/*
9576 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9577 	 * synchronized state.
9578 	 */
9579 	if (thflags & TH_SYN) {
9580 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9581 		return (ret_val);
9582 	}
9583 	/*
9584 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9585 	 * it's less than ts_recent, drop it.
9586 	 */
9587 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9588 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9589 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9590 			return (ret_val);
9591 	}
9592 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9593 		return (ret_val);
9594 	}
9595 	/*
9596 	 * If new data are received on a connection after the user processes
9597 	 * are gone, then RST the other end.
9598 	 * We call a new function now so we might continue and setup
9599 	 * to reset at all data being ack'd.
9600 	 */
9601 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9602 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9603 		return (1);
9604 	/*
9605 	 * If last ACK falls within this segment's sequence numbers, record
9606 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9607 	 * from the latest proposal of the tcplw@cray.com list (Braden
9608 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9609 	 * with our earlier PAWS tests, so this check should be solely
9610 	 * predicated on the sequence space of this segment. 3) That we
9611 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9612 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9613 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9614 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9615 	 * p.869. In such cases, we can still calculate the RTT correctly
9616 	 * when RCV.NXT == Last.ACK.Sent.
9617 	 */
9618 	if ((to->to_flags & TOF_TS) != 0 &&
9619 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9620 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9621 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9622 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9623 		tp->ts_recent = to->to_tsval;
9624 	}
9625 	/*
9626 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9627 	 * is on (half-synchronized state), then queue data for later
9628 	 * processing; else drop segment and return.
9629 	 */
9630 	if ((thflags & TH_ACK) == 0) {
9631 		if (tp->t_flags & TF_NEEDSYN) {
9632 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9633 			    tiwin, thflags, nxt_pkt));
9634 		} else if (tp->t_flags & TF_ACKNOW) {
9635 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9636 			bbr->r_wanted_output = 1;
9637 			return (ret_val);
9638 		} else {
9639 			ctf_do_drop(m, NULL);
9640 			return (0);
9641 		}
9642 	}
9643 	/*
9644 	 * Ack processing.
9645 	 */
9646 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9647 		return (ret_val);
9648 	}
9649 	if (ourfinisacked) {
9650 		tcp_twstart(tp);
9651 		m_freem(m);
9652 		return (1);
9653 	}
9654 	if (sbavail(&so->so_snd)) {
9655 		if (ctf_progress_timeout_check(tp, true)) {
9656 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9657 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9658 			return (1);
9659 		}
9660 	}
9661 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9662 	    tiwin, thflags, nxt_pkt));
9663 }
9664 
9665 /*
9666  * Return value of 1, the TCB is unlocked and most
9667  * likely gone, return value of 0, the TCB is still
9668  * locked.
9669  */
9670 static int
9671 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9672     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9673     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9674 {
9675 	int32_t ourfinisacked = 0;
9676 	int32_t ret_val;
9677 	struct tcp_bbr *bbr;
9678 
9679 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9680 
9681 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9682 	ctf_calc_rwin(so, tp);
9683 	if ((thflags & TH_RST) ||
9684 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9685 		return (ctf_process_rst(m, th, so, tp));
9686 	/*
9687 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9688 	 * synchronized state.
9689 	 */
9690 	if (thflags & TH_SYN) {
9691 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9692 		return (ret_val);
9693 	}
9694 	/*
9695 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9696 	 * it's less than ts_recent, drop it.
9697 	 */
9698 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9699 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9700 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9701 			return (ret_val);
9702 	}
9703 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9704 		return (ret_val);
9705 	}
9706 	/*
9707 	 * If new data are received on a connection after the user processes
9708 	 * are gone, then RST the other end.
9709 	 * We call a new function now so we might continue and setup
9710 	 * to reset at all data being ack'd.
9711 	 */
9712 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9713 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9714 		return (1);
9715 	/*
9716 	 * If last ACK falls within this segment's sequence numbers, record
9717 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9718 	 * from the latest proposal of the tcplw@cray.com list (Braden
9719 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9720 	 * with our earlier PAWS tests, so this check should be solely
9721 	 * predicated on the sequence space of this segment. 3) That we
9722 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9723 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9724 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9725 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9726 	 * p.869. In such cases, we can still calculate the RTT correctly
9727 	 * when RCV.NXT == Last.ACK.Sent.
9728 	 */
9729 	if ((to->to_flags & TOF_TS) != 0 &&
9730 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9731 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9732 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9733 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9734 		tp->ts_recent = to->to_tsval;
9735 	}
9736 	/*
9737 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9738 	 * is on (half-synchronized state), then queue data for later
9739 	 * processing; else drop segment and return.
9740 	 */
9741 	if ((thflags & TH_ACK) == 0) {
9742 		if (tp->t_flags & TF_NEEDSYN) {
9743 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9744 			    tiwin, thflags, nxt_pkt));
9745 		} else if (tp->t_flags & TF_ACKNOW) {
9746 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9747 			bbr->r_wanted_output = 1;
9748 			return (ret_val);
9749 		} else {
9750 			ctf_do_drop(m, NULL);
9751 			return (0);
9752 		}
9753 	}
9754 	/*
9755 	 * case TCPS_LAST_ACK: Ack processing.
9756 	 */
9757 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9758 		return (ret_val);
9759 	}
9760 	if (ourfinisacked) {
9761 		tp = tcp_close(tp);
9762 		ctf_do_drop(m, tp);
9763 		return (1);
9764 	}
9765 	if (sbavail(&so->so_snd)) {
9766 		if (ctf_progress_timeout_check(tp, true)) {
9767 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9768 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9769 			return (1);
9770 		}
9771 	}
9772 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9773 	    tiwin, thflags, nxt_pkt));
9774 }
9775 
9776 /*
9777  * Return value of 1, the TCB is unlocked and most
9778  * likely gone, return value of 0, the TCB is still
9779  * locked.
9780  */
9781 static int
9782 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9783     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9784     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9785 {
9786 	int32_t ourfinisacked = 0;
9787 	int32_t ret_val;
9788 	struct tcp_bbr *bbr;
9789 
9790 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9791 
9792 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9793 	ctf_calc_rwin(so, tp);
9794 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9795 	if ((thflags & TH_RST) ||
9796 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9797 		return (ctf_process_rst(m, th, so, tp));
9798 
9799 	/*
9800 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9801 	 * synchronized state.
9802 	 */
9803 	if (thflags & TH_SYN) {
9804 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9805 		return (ret_val);
9806 	}
9807 	/*
9808 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9809 	 * it's less than ts_recent, drop it.
9810 	 */
9811 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9812 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9813 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9814 			return (ret_val);
9815 	}
9816 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9817 		return (ret_val);
9818 	}
9819 	/*
9820 	 * If new data are received on a connection after the user processes
9821 	 * are gone, then we may RST the other end depending on the outcome
9822 	 * of bbr_check_data_after_close.
9823 	 * We call a new function now so we might continue and setup
9824 	 * to reset at all data being ack'd.
9825 	 */
9826 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9827 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9828 		return (1);
9829 	/*
9830 	 * If last ACK falls within this segment's sequence numbers, record
9831 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9832 	 * from the latest proposal of the tcplw@cray.com list (Braden
9833 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9834 	 * with our earlier PAWS tests, so this check should be solely
9835 	 * predicated on the sequence space of this segment. 3) That we
9836 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9837 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9838 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9839 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9840 	 * p.869. In such cases, we can still calculate the RTT correctly
9841 	 * when RCV.NXT == Last.ACK.Sent.
9842 	 */
9843 	if ((to->to_flags & TOF_TS) != 0 &&
9844 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9845 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9846 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9847 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9848 		tp->ts_recent = to->to_tsval;
9849 	}
9850 	/*
9851 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9852 	 * is on (half-synchronized state), then queue data for later
9853 	 * processing; else drop segment and return.
9854 	 */
9855 	if ((thflags & TH_ACK) == 0) {
9856 		if (tp->t_flags & TF_NEEDSYN) {
9857 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9858 			    tiwin, thflags, nxt_pkt));
9859 		} else if (tp->t_flags & TF_ACKNOW) {
9860 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9861 			bbr->r_wanted_output = 1;
9862 			return (ret_val);
9863 		} else {
9864 			ctf_do_drop(m, NULL);
9865 			return (0);
9866 		}
9867 	}
9868 	/*
9869 	 * Ack processing.
9870 	 */
9871 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9872 		return (ret_val);
9873 	}
9874 	if (sbavail(&so->so_snd)) {
9875 		if (ctf_progress_timeout_check(tp, true)) {
9876 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9877 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9878 			return (1);
9879 		}
9880 	}
9881 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9882 	    tiwin, thflags, nxt_pkt));
9883 }
9884 
9885 static void
9886 bbr_stop_all_timers(struct tcpcb *tp)
9887 {
9888 	struct tcp_bbr *bbr;
9889 
9890 	/*
9891 	 * Assure no timers are running.
9892 	 */
9893 	if (tcp_timer_active(tp, TT_PERSIST)) {
9894 		/* We enter in persists, set the flag appropriately */
9895 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9896 		bbr->rc_in_persist = 1;
9897 	}
9898 }
9899 
9900 static void
9901 bbr_google_mode_on(struct tcp_bbr *bbr)
9902 {
9903 	bbr->rc_use_google = 1;
9904 	bbr->rc_no_pacing = 0;
9905 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9906 	bbr->r_use_policer = bbr_policer_detection_enabled;
9907 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9908 	bbr->bbr_use_rack_cheat = 0;
9909 	bbr->r_ctl.rc_incr_tmrs = 0;
9910 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9911 	bbr->r_ctl.rc_inc_ip_oh = 0;
9912 	bbr->r_ctl.rc_inc_enet_oh = 0;
9913 	reset_time(&bbr->r_ctl.rc_delrate,
9914 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9915 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9916 			 (11 * USECS_IN_SECOND));
9917 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9918 }
9919 
9920 static void
9921 bbr_google_mode_off(struct tcp_bbr *bbr)
9922 {
9923 	bbr->rc_use_google = 0;
9924 	bbr->r_ctl.bbr_google_discount = 0;
9925 	bbr->no_pacing_until = bbr_no_pacing_until;
9926 	bbr->r_use_policer = 0;
9927 	if (bbr->no_pacing_until)
9928 		bbr->rc_no_pacing = 1;
9929 	else
9930 		bbr->rc_no_pacing = 0;
9931 	if (bbr_use_rack_resend_cheat)
9932 		bbr->bbr_use_rack_cheat = 1;
9933 	else
9934 		bbr->bbr_use_rack_cheat = 0;
9935 	if (bbr_incr_timers)
9936 		bbr->r_ctl.rc_incr_tmrs = 1;
9937 	else
9938 		bbr->r_ctl.rc_incr_tmrs = 0;
9939 	if (bbr_include_tcp_oh)
9940 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9941 	else
9942 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9943 	if (bbr_include_ip_oh)
9944 		bbr->r_ctl.rc_inc_ip_oh = 1;
9945 	else
9946 		bbr->r_ctl.rc_inc_ip_oh = 0;
9947 	if (bbr_include_enet_oh)
9948 		bbr->r_ctl.rc_inc_enet_oh = 1;
9949 	else
9950 		bbr->r_ctl.rc_inc_enet_oh = 0;
9951 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9952 	reset_time(&bbr->r_ctl.rc_delrate,
9953 		   bbr_num_pktepo_for_del_limit);
9954 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9955 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9956 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9957 }
9958 /*
9959  * Return 0 on success, non-zero on failure
9960  * which indicates the error (usually no memory).
9961  */
9962 static int
9963 bbr_init(struct tcpcb *tp)
9964 {
9965 	struct inpcb *inp = tptoinpcb(tp);
9966 	struct tcp_bbr *bbr = NULL;
9967 	uint32_t cts;
9968 
9969 	tp->t_fb_ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
9970 	if (tp->t_fb_ptr == NULL) {
9971 		/*
9972 		 * We need to allocate memory but cant. The INP and INP_INFO
9973 		 * locks and they are recursive (happens during setup. So a
9974 		 * scheme to drop the locks fails :(
9975 		 *
9976 		 */
9977 		return (ENOMEM);
9978 	}
9979 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9980 	bbr->rtt_valid = 0;
9981 	inp->inp_flags2 |= INP_CANNOT_DO_ECN;
9982 	inp->inp_flags2 |= INP_SUPPORTS_MBUFQ;
9983 	TAILQ_INIT(&bbr->r_ctl.rc_map);
9984 	TAILQ_INIT(&bbr->r_ctl.rc_free);
9985 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
9986 	bbr->rc_tp = tp;
9987 	bbr->rc_inp = inp;
9988 	cts = tcp_get_usecs(&bbr->rc_tv);
9989 	tp->t_acktime = 0;
9990 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
9991 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
9992 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
9993 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
9994 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
9995 	bbr->r_ctl.rc_min_to = bbr_min_to;
9996 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
9997 	bbr->r_ctl.bbr_lost_at_state = 0;
9998 	bbr->r_ctl.rc_lost_at_startup = 0;
9999 	bbr->rc_all_timers_stopped = 0;
10000 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
10001 	bbr->r_ctl.rc_pkt_epoch_del = 0;
10002 	bbr->r_ctl.rc_pkt_epoch = 0;
10003 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
10004 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
10005 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
10006 	bbr->r_ctl.rc_went_idle_time = cts;
10007 	bbr->rc_pacer_started = cts;
10008 	bbr->r_ctl.rc_pkt_epoch_time = cts;
10009 	bbr->r_ctl.rc_rcvtime = cts;
10010 	bbr->r_ctl.rc_bbr_state_time = cts;
10011 	bbr->r_ctl.rc_del_time = cts;
10012 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
10013 	bbr->r_ctl.last_in_probertt = cts;
10014 	bbr->skip_gain = 0;
10015 	bbr->gain_is_limited = 0;
10016 	bbr->no_pacing_until = bbr_no_pacing_until;
10017 	if (bbr->no_pacing_until)
10018 		bbr->rc_no_pacing = 1;
10019 	if (bbr_use_google_algo) {
10020 		bbr->rc_no_pacing = 0;
10021 		bbr->rc_use_google = 1;
10022 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
10023 		bbr->r_use_policer = bbr_policer_detection_enabled;
10024 	} else {
10025 		bbr->rc_use_google = 0;
10026 		bbr->r_ctl.bbr_google_discount = 0;
10027 		bbr->r_use_policer = 0;
10028 	}
10029 	if (bbr_ts_limiting)
10030 		bbr->rc_use_ts_limit = 1;
10031 	else
10032 		bbr->rc_use_ts_limit = 0;
10033 	if (bbr_ts_can_raise)
10034 		bbr->ts_can_raise = 1;
10035 	else
10036 		bbr->ts_can_raise = 0;
10037 	if (V_tcp_delack_enabled == 1)
10038 		tp->t_delayed_ack = 2;
10039 	else if (V_tcp_delack_enabled == 0)
10040 		tp->t_delayed_ack = 0;
10041 	else if (V_tcp_delack_enabled < 100)
10042 		tp->t_delayed_ack = V_tcp_delack_enabled;
10043 	else
10044 		tp->t_delayed_ack = 2;
10045 	if (bbr->rc_use_google == 0)
10046 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10047 	else
10048 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10049 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10050 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10051 	bbr->rc_init_win = bbr_def_init_win;
10052 	if (tp->t_flags & TF_REQ_TSTMP)
10053 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10054 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10055 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10056 	bbr->r_init_rtt = 1;
10057 
10058 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10059 	if (bbr_allow_hdwr_pacing)
10060 		bbr->bbr_hdw_pace_ena = 1;
10061 	else
10062 		bbr->bbr_hdw_pace_ena = 0;
10063 	if (bbr_sends_full_iwnd)
10064 		bbr->bbr_init_win_cheat = 1;
10065 	else
10066 		bbr->bbr_init_win_cheat = 0;
10067 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10068 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10069 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10070 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10071 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10072 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10073 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10074 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10075 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10076 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10077 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10078 	bbr->r_ctl.rc_rtt_shrinks = cts;
10079 	if (bbr->rc_use_google) {
10080 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10081 				  FILTER_TYPE_MAX,
10082 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10083 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10084 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10085 	} else {
10086 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10087 				  FILTER_TYPE_MAX,
10088 				  bbr_num_pktepo_for_del_limit);
10089 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10090 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10091 	}
10092 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10093 	if (bbr_uses_idle_restart)
10094 		bbr->rc_use_idle_restart = 1;
10095 	else
10096 		bbr->rc_use_idle_restart = 0;
10097 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10098 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10099 	if (bbr_resends_use_tso)
10100 		bbr->rc_resends_use_tso = 1;
10101 #ifdef NETFLIX_PEAKRATE
10102 	tp->t_peakrate_thr = tp->t_maxpeakrate;
10103 #endif
10104 	if (tp->snd_una != tp->snd_max) {
10105 		/* Create a send map for the current outstanding data */
10106 		struct bbr_sendmap *rsm;
10107 
10108 		rsm = bbr_alloc(bbr);
10109 		if (rsm == NULL) {
10110 			uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10111 			tp->t_fb_ptr = NULL;
10112 			return (ENOMEM);
10113 		}
10114 		rsm->r_rtt_not_allowed = 1;
10115 		rsm->r_tim_lastsent[0] = cts;
10116 		rsm->r_rtr_cnt = 1;
10117 		rsm->r_rtr_bytes = 0;
10118 		rsm->r_start = tp->snd_una;
10119 		rsm->r_end = tp->snd_max;
10120 		rsm->r_dupack = 0;
10121 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10122 		rsm->r_ts_valid = 0;
10123 		rsm->r_del_ack_ts = tp->ts_recent;
10124 		rsm->r_del_time = cts;
10125 		if (bbr->r_ctl.r_app_limited_until)
10126 			rsm->r_app_limited = 1;
10127 		else
10128 			rsm->r_app_limited = 0;
10129 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10130 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10131 		rsm->r_in_tmap = 1;
10132 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10133 			rsm->r_bbr_state = bbr_state_val(bbr);
10134 		else
10135 			rsm->r_bbr_state = 8;
10136 	}
10137 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10138 		bbr->bbr_use_rack_cheat = 1;
10139 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10140 		bbr->r_ctl.rc_incr_tmrs = 1;
10141 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10142 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10143 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10144 		bbr->r_ctl.rc_inc_ip_oh = 1;
10145 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10146 		bbr->r_ctl.rc_inc_enet_oh = 1;
10147 
10148 	bbr_log_type_statechange(bbr, cts, __LINE__);
10149 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10150 	    (tp->t_srtt)) {
10151 		uint32_t rtt;
10152 
10153 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10154 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10155 	}
10156 	/* announce the settings and state */
10157 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10158 	tcp_bbr_tso_size_check(bbr, cts);
10159 	/*
10160 	 * Now call the generic function to start a timer. This will place
10161 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10162 	 * flags.
10163 	 */
10164 	bbr_stop_all_timers(tp);
10165 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10166 	return (0);
10167 }
10168 
10169 /*
10170  * Return 0 if we can accept the connection. Return
10171  * non-zero if we can't handle the connection. A EAGAIN
10172  * means you need to wait until the connection is up.
10173  * a EADDRNOTAVAIL means we can never handle the connection
10174  * (no SACK).
10175  */
10176 static int
10177 bbr_handoff_ok(struct tcpcb *tp)
10178 {
10179 	if ((tp->t_state == TCPS_CLOSED) ||
10180 	    (tp->t_state == TCPS_LISTEN)) {
10181 		/* Sure no problem though it may not stick */
10182 		return (0);
10183 	}
10184 	if ((tp->t_state == TCPS_SYN_SENT) ||
10185 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10186 		/*
10187 		 * We really don't know you have to get to ESTAB or beyond
10188 		 * to tell.
10189 		 */
10190 		return (EAGAIN);
10191 	}
10192 	if (tp->t_flags & TF_SENTFIN)
10193 		return (EINVAL);
10194 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10195 		return (0);
10196 	}
10197 	/*
10198 	 * If we reach here we don't do SACK on this connection so we can
10199 	 * never do rack.
10200 	 */
10201 	return (EINVAL);
10202 }
10203 
10204 static void
10205 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10206 {
10207 	if (tp->t_fb_ptr) {
10208 		struct inpcb *inp = tptoinpcb(tp);
10209 		uint32_t calc;
10210 		struct tcp_bbr *bbr;
10211 		struct bbr_sendmap *rsm;
10212 
10213 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10214 		if (bbr->r_ctl.crte)
10215 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10216 		bbr_log_flowend(bbr);
10217 		bbr->rc_tp = NULL;
10218 		/* Backout any flags2 we applied */
10219 		inp->inp_flags2 &= ~INP_CANNOT_DO_ECN;
10220 		inp->inp_flags2 &= ~INP_SUPPORTS_MBUFQ;
10221 		inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
10222 		if (bbr->bbr_hdrw_pacing)
10223 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10224 		else
10225 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10226 		if (bbr->r_ctl.crte != NULL) {
10227 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10228 			bbr->r_ctl.crte = NULL;
10229 		}
10230 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10231 		while (rsm) {
10232 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10233 			uma_zfree(bbr_zone, rsm);
10234 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10235 		}
10236 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10237 		while (rsm) {
10238 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10239 			uma_zfree(bbr_zone, rsm);
10240 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10241 		}
10242 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10243 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10244 			BBR_STAT_INC(bbr_dynamic_rwnd);
10245 		else
10246 			BBR_STAT_INC(bbr_static_rwnd);
10247 		bbr->r_ctl.rc_free_cnt = 0;
10248 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10249 		tp->t_fb_ptr = NULL;
10250 	}
10251 	/* Make sure snd_nxt is correctly set */
10252 	tp->snd_nxt = tp->snd_max;
10253 }
10254 
10255 static void
10256 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10257 {
10258 	switch (tp->t_state) {
10259 	case TCPS_SYN_SENT:
10260 		bbr->r_state = TCPS_SYN_SENT;
10261 		bbr->r_substate = bbr_do_syn_sent;
10262 		break;
10263 	case TCPS_SYN_RECEIVED:
10264 		bbr->r_state = TCPS_SYN_RECEIVED;
10265 		bbr->r_substate = bbr_do_syn_recv;
10266 		break;
10267 	case TCPS_ESTABLISHED:
10268 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10269 		bbr->r_state = TCPS_ESTABLISHED;
10270 		bbr->r_substate = bbr_do_established;
10271 		break;
10272 	case TCPS_CLOSE_WAIT:
10273 		bbr->r_state = TCPS_CLOSE_WAIT;
10274 		bbr->r_substate = bbr_do_close_wait;
10275 		break;
10276 	case TCPS_FIN_WAIT_1:
10277 		bbr->r_state = TCPS_FIN_WAIT_1;
10278 		bbr->r_substate = bbr_do_fin_wait_1;
10279 		break;
10280 	case TCPS_CLOSING:
10281 		bbr->r_state = TCPS_CLOSING;
10282 		bbr->r_substate = bbr_do_closing;
10283 		break;
10284 	case TCPS_LAST_ACK:
10285 		bbr->r_state = TCPS_LAST_ACK;
10286 		bbr->r_substate = bbr_do_lastack;
10287 		break;
10288 	case TCPS_FIN_WAIT_2:
10289 		bbr->r_state = TCPS_FIN_WAIT_2;
10290 		bbr->r_substate = bbr_do_fin_wait_2;
10291 		break;
10292 	case TCPS_LISTEN:
10293 	case TCPS_CLOSED:
10294 	case TCPS_TIME_WAIT:
10295 	default:
10296 		break;
10297 	};
10298 }
10299 
10300 static void
10301 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10302 {
10303 	/*
10304 	 * Now what state are we going into now? Is there adjustments
10305 	 * needed?
10306 	 */
10307 	int32_t old_state;
10308 
10309 	old_state = bbr_state_val(bbr);
10310 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10311 		/* Save the lowest srtt we saw in our end of the sub-state */
10312 		bbr->rc_hit_state_1 = 0;
10313 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10314 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10315 	}
10316 	bbr->rc_bbr_substate++;
10317 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10318 		/* Cycle back to first state-> gain */
10319 		bbr->rc_bbr_substate = 0;
10320 	}
10321 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10322 		/*
10323 		 * We enter the gain(5/4) cycle (possibly less if
10324 		 * shallow buffer detection is enabled)
10325 		 */
10326 		if (bbr->skip_gain) {
10327 			/*
10328 			 * Hardware pacing has set our rate to
10329 			 * the max and limited our b/w just
10330 			 * do level i.e. no gain.
10331 			 */
10332 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10333 		} else if (bbr->gain_is_limited &&
10334 			   bbr->bbr_hdrw_pacing &&
10335 			   bbr->r_ctl.crte) {
10336 			/*
10337 			 * We can't gain above the hardware pacing
10338 			 * rate which is less than our rate + the gain
10339 			 * calculate the gain needed to reach the hardware
10340 			 * pacing rate..
10341 			 */
10342 			uint64_t bw, rate, gain_calc;
10343 
10344 			bw = bbr_get_bw(bbr);
10345 			rate = bbr->r_ctl.crte->rate;
10346 			if ((rate > bw) &&
10347 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10348 				gain_calc = (rate * BBR_UNIT) / bw;
10349 				if (gain_calc < BBR_UNIT)
10350 					gain_calc = BBR_UNIT;
10351 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10352 			} else {
10353 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10354 			}
10355 		} else
10356 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10357 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10358 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10359 		} else
10360 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10361 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10362 		bbr->rc_hit_state_1 = 1;
10363 		bbr->r_ctl.rc_exta_time_gd = 0;
10364 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10365 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10366 		if (bbr_state_drain_2_tar) {
10367 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10368 		} else
10369 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10370 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10371 	} else {
10372 		/* All other cycles hit here 2-7 */
10373 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10374 			if (bbr_sub_drain_slam_cwnd &&
10375 			    (bbr->rc_use_google == 0) &&
10376 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10377 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10378 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10379 			}
10380 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10381 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10382 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10383 			else
10384 				bbr->r_ctl.rc_exta_time_gd = 0;
10385 			if (bbr->r_ctl.rc_exta_time_gd) {
10386 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10387 				/* Now chop up the time for each state (div by 7) */
10388 				bbr->r_ctl.rc_level_state_extra /= 7;
10389 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10390 					/* Add a randomization */
10391 					bbr_randomize_extra_state_time(bbr);
10392 				}
10393 			}
10394 		}
10395 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10396 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10397 	}
10398 	if (bbr->rc_use_google) {
10399 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10400 	}
10401 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10402 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10403 	if (dolog)
10404 		bbr_log_type_statechange(bbr, cts, line);
10405 
10406 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10407 		uint32_t time_in;
10408 
10409 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10410 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10411 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10412 		} else {
10413 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10414 		}
10415 	}
10416 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10417 	bbr_set_state_target(bbr, __LINE__);
10418 	if (bbr_sub_drain_slam_cwnd &&
10419 	    (bbr->rc_use_google == 0) &&
10420 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10421 		/* Slam down the cwnd */
10422 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10423 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10424 		if (bbr_sub_drain_app_limit) {
10425 			/* Go app limited if we are on a long drain */
10426 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10427 							  ctf_flight_size(bbr->rc_tp,
10428 							      (bbr->r_ctl.rc_sacked +
10429 							       bbr->r_ctl.rc_lost_bytes)));
10430 		}
10431 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10432 	}
10433 	if (bbr->rc_lt_use_bw) {
10434 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10435 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10436 	}
10437 	/* Google changes TSO size every cycle */
10438 	if (bbr->rc_use_google)
10439 		tcp_bbr_tso_size_check(bbr, cts);
10440 	bbr->r_ctl.gain_epoch = cts;
10441 	bbr->r_ctl.rc_bbr_state_time = cts;
10442 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10443 }
10444 
10445 static void
10446 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10447 {
10448 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10449 	    (google_allow_early_out == 1) &&
10450 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10451 		/* We have reached out target flight size possibly early */
10452 		goto change_state;
10453 	}
10454 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10455 		return;
10456 	}
10457 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10458 		/*
10459 		 * Must be a rttProp movement forward before
10460 		 * we can change states.
10461 		 */
10462 		return;
10463 	}
10464 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10465 		/*
10466 		 * The needed time has passed but for
10467 		 * the gain cycle extra rules apply:
10468 		 * 1) If we have seen loss, we exit
10469 		 * 2) If we have not reached the target
10470 		 *    we stay in GAIN (gain-to-target).
10471 		 */
10472 		if (google_consider_lost && losses)
10473 			goto change_state;
10474 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10475 			return;
10476 		}
10477 	}
10478 change_state:
10479 	/* For gain we must reach our target, all others last 1 rttProp */
10480 	bbr_substate_change(bbr, cts, __LINE__, 1);
10481 }
10482 
10483 static void
10484 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10485 {
10486 	uint32_t flight, bbr_cur_cycle_time;
10487 
10488 	if (bbr->rc_use_google) {
10489 		bbr_set_probebw_google_gains(bbr, cts, losses);
10490 		return;
10491 	}
10492 	if (cts == 0) {
10493 		/*
10494 		 * Never alow cts to be 0 we
10495 		 * do this so we can judge if
10496 		 * we have set a timestamp.
10497 		 */
10498 		cts = 1;
10499 	}
10500 	if (bbr_state_is_pkt_epoch)
10501 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10502 	else
10503 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10504 
10505 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10506 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10507 			flight = ctf_flight_size(bbr->rc_tp,
10508 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10509 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10510 				/* Keep it slam down */
10511 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10512 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10513 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10514 				}
10515 				if (bbr_sub_drain_app_limit) {
10516 					/* Go app limited if we are on a long drain */
10517 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10518 				}
10519 			}
10520 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10521 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10522 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10523 				/*
10524 				 * Still here after the same time as
10525 				 * the gain. We need to drain harder
10526 				 * for the next srtt. Reduce by a set amount
10527 				 * the gain drop is capped at DRAIN states
10528 				 * value (88).
10529 				 */
10530 				bbr->r_ctl.flightsize_at_drain = flight;
10531 				if (bbr_drain_drop_mul &&
10532 				    bbr_drain_drop_div &&
10533 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10534 					/* Use your specific drop value (def 4/5 = 20%) */
10535 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10536 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10537 				} else {
10538 					/* You get drop of 20% */
10539 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10540 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10541 				}
10542 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10543 					/* Reduce our gain again to the bottom  */
10544 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10545 				}
10546 				bbr_log_exit_gain(bbr, cts, 4);
10547 				/*
10548 				 * Extend out so we wait another
10549 				 * epoch before dropping again.
10550 				 */
10551 				bbr->r_ctl.gain_epoch = cts;
10552 			}
10553 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10554 				if (bbr_sub_drain_slam_cwnd &&
10555 				    (bbr->rc_use_google == 0) &&
10556 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10557 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10558 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10559 				}
10560 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10561 				bbr_log_exit_gain(bbr, cts, 3);
10562 			}
10563 		} else {
10564 			/* Its a gain  */
10565 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10566 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10567 				goto change_state;
10568 			}
10569 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10570 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10571 			     bbr->rc_tp->snd_wnd)) {
10572 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10573 				bbr_log_exit_gain(bbr, cts, 2);
10574 			}
10575 		}
10576 		/**
10577 		 * We fall through and return always one of two things has
10578 		 * occurred.
10579 		 * 1) We are still not at target
10580 		 *    <or>
10581 		 * 2) We reached the target and set rc_bbr_state_atflight
10582 		 *    which means we no longer hit this block
10583 		 *    next time we are called.
10584 		 */
10585 		return;
10586 	}
10587 change_state:
10588 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10589 		return;
10590 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10591 		/* Less than a full time-period has passed */
10592 		return;
10593 	}
10594 	if (bbr->r_ctl.rc_level_state_extra &&
10595 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10596 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10597 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10598 		/* Less than a full time-period + extra has passed */
10599 		return;
10600 	}
10601 	if (bbr_gain_gets_extra_too &&
10602 	    bbr->r_ctl.rc_level_state_extra &&
10603 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10604 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10605 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10606 		/* Less than a full time-period + extra has passed */
10607 		return;
10608 	}
10609 	bbr_substate_change(bbr, cts, __LINE__, 1);
10610 }
10611 
10612 static uint32_t
10613 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10614 {
10615 	uint32_t mss, tar;
10616 
10617 	if (bbr->rc_use_google) {
10618 		/* Google just uses the cwnd target */
10619 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10620 	} else {
10621 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10622 			  bbr->r_ctl.rc_pace_max_segs);
10623 		/* Get the base cwnd with gain rounded to a mss */
10624 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10625 						      gain), mss);
10626 		/* Make sure it is within our min */
10627 		if (tar < get_min_cwnd(bbr))
10628 			return (get_min_cwnd(bbr));
10629 	}
10630 	return (tar);
10631 }
10632 
10633 static void
10634 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10635 {
10636 	uint32_t tar, meth;
10637 
10638 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10639 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10640 		/* Special case using old probe-rtt method */
10641 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10642 		meth = 1;
10643 	} else {
10644 		/* Non-probe-rtt case and reduced probe-rtt  */
10645 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10646 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10647 			/* For gain cycle we use the hptsi gain */
10648 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10649 			meth = 2;
10650 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10651 			/*
10652 			 * If configured, or for google all other states
10653 			 * get BBR_UNIT.
10654 			 */
10655 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10656 			meth = 3;
10657 		} else {
10658 			/*
10659 			 * Or we set a target based on the pacing gain
10660 			 * for non-google mode and default (non-configured).
10661 			 * Note we don't set a target goal below drain (192).
10662 			 */
10663 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10664 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10665 				meth = 4;
10666 			} else {
10667 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10668 				meth = 5;
10669 			}
10670 		}
10671 	}
10672 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10673 	bbr->r_ctl.rc_target_at_state = tar;
10674 }
10675 
10676 static void
10677 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10678 {
10679 	/* Change to probe_rtt */
10680 	uint32_t time_in;
10681 
10682 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10683 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10684 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10685 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10686 					  + bbr->r_ctl.rc_delivered);
10687 	/* Setup so we force feed the filter */
10688 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10689 		bbr->rc_prtt_set_ts = 1;
10690 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10691 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10692 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10693 	}
10694 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10695 	bbr->r_ctl.rc_rtt_shrinks = cts;
10696 	bbr->r_ctl.last_in_probertt = cts;
10697 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10698 	bbr->r_ctl.rc_bbr_state_time = cts;
10699 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10700 	/* We need to force the filter to update */
10701 
10702 	if ((bbr_sub_drain_slam_cwnd) &&
10703 	    bbr->rc_hit_state_1 &&
10704 	    (bbr->rc_use_google == 0) &&
10705 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10706 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10707 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10708 	} else
10709 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10710 	/* Update the lost */
10711 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10712 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10713 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10714 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10715 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10716 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10717 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10718 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10719 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10720 	} else {
10721 		/*
10722 		 * We bring it down slowly by using a hptsi gain that is
10723 		 * probably 75%. This will slowly float down our outstanding
10724 		 * without tampering with the cwnd.
10725 		 */
10726 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10727 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10728 		bbr_set_state_target(bbr, __LINE__);
10729 		if (bbr_prtt_slam_cwnd &&
10730 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10731 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10732 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10733 		}
10734 	}
10735 	if (ctf_flight_size(bbr->rc_tp,
10736 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10737 	    bbr->r_ctl.rc_target_at_state) {
10738 		/* We are at target */
10739 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10740 	} else {
10741 		/* We need to come down to reach target before our time begins */
10742 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10743 	}
10744 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10745 	BBR_STAT_INC(bbr_enter_probertt);
10746 	bbr_log_exit_gain(bbr, cts, 0);
10747 	bbr_log_type_statechange(bbr, cts, line);
10748 }
10749 
10750 static void
10751 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10752 {
10753 	/*
10754 	 * Sanity check on probe-rtt intervals.
10755 	 * In crazy situations where we are competing
10756 	 * against new-reno flows with huge buffers
10757 	 * our rtt-prop interval could come to dominate
10758 	 * things if we can't get through a full set
10759 	 * of cycles, we need to adjust it.
10760 	 */
10761 	if (bbr_can_adjust_probertt &&
10762 	    (bbr->rc_use_google == 0)) {
10763 		uint16_t val = 0;
10764 		uint32_t cur_rttp, fval, newval, baseval;
10765 
10766 		/* Are we to small and go into probe-rtt to often? */
10767 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10768 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10769 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10770 		if (bbr_is_ratio == 0) {
10771 			if (fval > bbr_rtt_probe_limit)
10772 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10773 			else
10774 				newval = cur_rttp;
10775 		} else {
10776 			int mul;
10777 
10778 			mul = fval / bbr_rtt_probe_limit;
10779 			newval = cur_rttp * mul;
10780 		}
10781 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10782 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10783 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10784 			val = 1;
10785 		} else {
10786 			/*
10787 			 * No adjustments were made
10788 			 * do we need to shrink it?
10789 			 */
10790 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10791 				if (cur_rttp <= bbr_rtt_probe_limit) {
10792 					/*
10793 					 * Things have calmed down lets
10794 					 * shrink all the way to default
10795 					 */
10796 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10797 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10798 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10799 					cur_rttp = bbr_rtt_probe_limit;
10800 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10801 					val = 2;
10802 				} else {
10803 					/*
10804 					 * Well does some adjustment make sense?
10805 					 */
10806 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10807 						/* We can reduce interval time some */
10808 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10809 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10810 						val = 3;
10811 					}
10812 				}
10813 			}
10814 		}
10815 		if (val)
10816 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10817 	}
10818 }
10819 
10820 static void
10821 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10822 {
10823 	/* Exit probe-rtt */
10824 
10825 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10826 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10827 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10828 	}
10829 	bbr_log_exit_gain(bbr, cts, 1);
10830 	bbr->rc_hit_state_1 = 0;
10831 	bbr->r_ctl.rc_rtt_shrinks = cts;
10832 	bbr->r_ctl.last_in_probertt = cts;
10833 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10834 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10835 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10836 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10837 					  bbr->r_ctl.rc_delivered);
10838 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10839 		uint32_t time_in;
10840 
10841 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10842 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10843 	}
10844 	if (bbr->rc_filled_pipe) {
10845 		/* Switch to probe_bw */
10846 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10847 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10848 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10849 		bbr_substate_change(bbr, cts, __LINE__, 0);
10850 		bbr_log_type_statechange(bbr, cts, __LINE__);
10851 	} else {
10852 		/* Back to startup */
10853 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10854 		bbr->r_ctl.rc_bbr_state_time = cts;
10855 		/*
10856 		 * We don't want to give a complete free 3
10857 		 * measurements until we exit, so we use
10858 		 * the number of pe's we were in probe-rtt
10859 		 * to add to the startup_epoch. That way
10860 		 * we will still retain the old state.
10861 		 */
10862 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10863 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10864 		/* Make sure to use the lower pg when shifting back in */
10865 		if (bbr->r_ctl.rc_lost &&
10866 		    bbr_use_lower_gain_in_startup &&
10867 		    (bbr->rc_use_google == 0))
10868 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10869 		else
10870 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10871 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10872 		/* Probably not needed but set it anyway */
10873 		bbr_set_state_target(bbr, __LINE__);
10874 		bbr_log_type_statechange(bbr, cts, __LINE__);
10875 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10876 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10877 	}
10878 	bbr_check_probe_rtt_limits(bbr, cts);
10879 }
10880 
10881 static int32_t inline
10882 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10883 {
10884 	if ((bbr->rc_past_init_win == 1) &&
10885 	    (bbr->rc_in_persist == 0) &&
10886 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10887 		return (1);
10888 	}
10889 	if (bbr_can_force_probertt &&
10890 	    (bbr->rc_in_persist == 0) &&
10891 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10892 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10893 		return (1);
10894 	}
10895 	return (0);
10896 }
10897 
10898 static int32_t
10899 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10900 {
10901 	uint64_t btlbw, gain;
10902 	if (pkt_epoch == 0) {
10903 		/*
10904 		 * Need to be on a pkt-epoch to continue.
10905 		 */
10906 		return (0);
10907 	}
10908 	btlbw = bbr_get_full_bw(bbr);
10909 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10910 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10911 	if (btlbw >= gain) {
10912 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10913 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10914 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10915 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10916 	}
10917 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10918 		return (1);
10919 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10920 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10921 	return(0);
10922 }
10923 
10924 static int32_t inline
10925 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10926 {
10927 	/* Have we gained 25% in the last 3 packet based epoch's? */
10928 	uint64_t btlbw, gain;
10929 	int do_exit;
10930 	int delta, rtt_gain;
10931 
10932 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10933 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10934 		/*
10935 		 * This qualifies as a RTT_PROBE session since we drop the
10936 		 * data outstanding to nothing and waited more than
10937 		 * bbr_rtt_probe_time.
10938 		 */
10939 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10940 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10941 	}
10942 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10943 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10944 		return (0);
10945 	}
10946 	if (bbr->rc_use_google)
10947 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10948 
10949 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10950 	    (bbr_use_lower_gain_in_startup)) {
10951 		/* Drop to a lower gain 1.5 x since we saw loss */
10952 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10953 	}
10954 	if (pkt_epoch == 0) {
10955 		/*
10956 		 * Need to be on a pkt-epoch to continue.
10957 		 */
10958 		return (0);
10959 	}
10960 	if (bbr_rtt_gain_thresh) {
10961 		/*
10962 		 * Do we allow a flow to stay
10963 		 * in startup with no loss and no
10964 		 * gain in rtt over a set threshold?
10965 		 */
10966 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
10967 		    bbr->r_ctl.startup_last_srtt &&
10968 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
10969 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
10970 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
10971 		} else
10972 			rtt_gain = 0;
10973 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
10974 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
10975 			/* First time or new lower value */
10976 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
10977 
10978 		if ((bbr->r_ctl.rc_lost == 0) &&
10979 		    (rtt_gain < bbr_rtt_gain_thresh)) {
10980 			/*
10981 			 * No loss, and we are under
10982 			 * our gain threhold for
10983 			 * increasing RTT.
10984 			 */
10985 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10986 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
10987 			bbr_log_startup_event(bbr, cts, rtt_gain,
10988 					      delta, bbr->r_ctl.startup_last_srtt, 10);
10989 			return (0);
10990 		}
10991 	}
10992 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
10993 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
10994 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
10995 		/*
10996 		 * We only assess if we have a new measurement when
10997 		 * we have no loss and are not in recovery.
10998 		 * Drag up by one our last_startup epoch so we will hold
10999 		 * the number of non-gain we have already accumulated.
11000 		 */
11001 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
11002 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
11003 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11004 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
11005 		return (0);
11006 	}
11007 	/* Case where we reduced the lost (bad retransmit) */
11008 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
11009 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11010 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
11011 	btlbw = bbr_get_full_bw(bbr);
11012 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
11013 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11014 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11015 	else
11016 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
11017 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
11018 	do_exit = 0;
11019 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
11020 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
11021 	if (btlbw >= gain) {
11022 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
11023 		/* Update the lost so we won't exit in next set of tests */
11024 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11025 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11026 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11027 	}
11028 	if ((bbr->rc_loss_exit &&
11029 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11030 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11031 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11032 		/*
11033 		 * If we had no gain,  we had loss and that loss was above
11034 		 * our threshould, the rwnd is not constrained, and we have
11035 		 * had at least 3 packet epochs exit. Note that this is
11036 		 * switched off by sysctl. Google does not do this by the
11037 		 * way.
11038 		 */
11039 		if ((ctf_flight_size(bbr->rc_tp,
11040 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11041 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11042 			do_exit = 1;
11043 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11044 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11045 		} else {
11046 			/* Just record an updated loss value */
11047 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11048 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11049 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11050 		}
11051 	} else
11052 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11053 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11054 	    do_exit) {
11055 		/* Return 1 to exit the startup state. */
11056 		return (1);
11057 	}
11058 	/* Stay in startup */
11059 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11060 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11061 	return (0);
11062 }
11063 
11064 static void
11065 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11066 {
11067 	/*
11068 	 * A tick occurred in the rtt epoch do we need to do anything?
11069 	 */
11070 #ifdef BBR_INVARIANTS
11071 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11072 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11073 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11074 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11075 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11076 		/* Debug code? */
11077 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11078 	}
11079 #endif
11080 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11081 		/* Do we exit the startup state? */
11082 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11083 			uint32_t time_in;
11084 
11085 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11086 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11087 			bbr->rc_filled_pipe = 1;
11088 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11089 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11090 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11091 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11092 			} else
11093 				time_in = 0;
11094 			if (bbr->rc_no_pacing)
11095 				bbr->rc_no_pacing = 0;
11096 			bbr->r_ctl.rc_bbr_state_time = cts;
11097 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11098 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11099 			bbr_set_state_target(bbr, __LINE__);
11100 			if ((bbr->rc_use_google == 0) &&
11101 			    bbr_slam_cwnd_in_main_drain) {
11102 				/* Here we don't have to worry about probe-rtt */
11103 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11104 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11105 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11106 			}
11107 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11108 			bbr_log_type_statechange(bbr, cts, __LINE__);
11109 			if (ctf_flight_size(bbr->rc_tp,
11110 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11111 			    bbr->r_ctl.rc_target_at_state) {
11112 				/*
11113 				 * Switch to probe_bw if we are already
11114 				 * there
11115 				 */
11116 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11117 				bbr_substate_change(bbr, cts, __LINE__, 0);
11118 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11119 				bbr_log_type_statechange(bbr, cts, __LINE__);
11120 			}
11121 		}
11122 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11123 		uint32_t inflight;
11124 		struct tcpcb *tp;
11125 
11126 		tp = bbr->rc_tp;
11127 		inflight = ctf_flight_size(tp,
11128 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11129 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11130 			/* We have reached a flight of the cwnd target */
11131 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11132 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11133 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11134 			bbr_set_state_target(bbr, __LINE__);
11135 			/*
11136 			 * Rig it so we don't do anything crazy and
11137 			 * start fresh with a new randomization.
11138 			 */
11139 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11140 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11141 			bbr_substate_change(bbr, cts, __LINE__, 1);
11142 		}
11143 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11144 		/* Has in-flight reached the bdp (or less)? */
11145 		uint32_t inflight;
11146 		struct tcpcb *tp;
11147 
11148 		tp = bbr->rc_tp;
11149 		inflight = ctf_flight_size(tp,
11150 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11151 		if ((bbr->rc_use_google == 0) &&
11152 		    bbr_slam_cwnd_in_main_drain &&
11153 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11154 			/*
11155 			 * Here we don't have to worry about probe-rtt
11156 			 * re-slam it, but keep it slammed down.
11157 			 */
11158 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11159 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11160 		}
11161 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11162 			/* We have drained */
11163 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11164 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11165 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11166 				uint32_t time_in;
11167 
11168 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11169 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11170 			}
11171 			if ((bbr->rc_use_google == 0) &&
11172 			    bbr_slam_cwnd_in_main_drain &&
11173 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11174 				/* Restore the cwnd */
11175 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11176 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11177 			}
11178 			/* Setup probe-rtt has being done now RRS-HERE */
11179 			bbr->r_ctl.rc_rtt_shrinks = cts;
11180 			bbr->r_ctl.last_in_probertt = cts;
11181 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11182 			/* Randomly pick a sub-state */
11183 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11184 			bbr_substate_change(bbr, cts, __LINE__, 0);
11185 			bbr_log_type_statechange(bbr, cts, __LINE__);
11186 		}
11187 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11188 		uint32_t flight;
11189 
11190 		flight = ctf_flight_size(bbr->rc_tp,
11191 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11192 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11193 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11194 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11195 			/*
11196 			 * We must keep cwnd at the desired MSS.
11197 			 */
11198 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11199 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11200 		} else if ((bbr_prtt_slam_cwnd) &&
11201 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11202 			/* Re-slam it */
11203 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11204 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11205 		}
11206 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11207 			/* Has outstanding reached our target? */
11208 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11209 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11210 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11211 				/* If time is exactly 0, be 1usec off */
11212 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11213 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11214 				if (bbr->rc_use_google == 0) {
11215 					/*
11216 					 * Restore any lowering that as occurred to
11217 					 * reach here
11218 					 */
11219 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11220 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11221 					else
11222 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11223 				}
11224 			}
11225 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11226 			    (bbr->rc_use_google == 0) &&
11227 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11228 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11229 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11230 				/*
11231 				 * We have doddled with our current hptsi
11232 				 * gain an srtt and have still not made it
11233 				 * to target, or we have increased our flight.
11234 				 * Lets reduce the gain by xx%
11235 				 * flooring the reduce at DRAIN (based on
11236 				 * mul/div)
11237 				 */
11238 				int red;
11239 
11240 				bbr->r_ctl.flightsize_at_drain = flight;
11241 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11242 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11243 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11244 					/* Reduce our gain again */
11245 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11246 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11247 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11248 					/* one more chance before we give up */
11249 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11250 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11251 				} else {
11252 					/* At the very bottom */
11253 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11254 				}
11255 			}
11256 		}
11257 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11258 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11259 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11260 			/* Time to exit probe RTT normally */
11261 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11262 		}
11263 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11264 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11265 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11266 			/*
11267 			 * This qualifies as a RTT_PROBE session since we
11268 			 * drop the data outstanding to nothing and waited
11269 			 * more than bbr_rtt_probe_time.
11270 			 */
11271 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11272 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11273 		}
11274 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11275 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11276 		} else {
11277 			bbr_set_probebw_gains(bbr, cts, losses);
11278 		}
11279 	}
11280 }
11281 
11282 static void
11283 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11284 {
11285 	int32_t epoch = 0;
11286 
11287 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11288 		bbr_set_epoch(bbr, cts, line);
11289 		/* At each epoch doe lt bw sampling */
11290 		epoch = 1;
11291 	}
11292 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11293 }
11294 
11295 static int
11296 bbr_do_segment_nounlock(struct mbuf *m, struct tcphdr *th, struct socket *so,
11297     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos,
11298     int32_t nxt_pkt, struct timeval *tv)
11299 {
11300 	struct inpcb *inp = tptoinpcb(tp);
11301 	int32_t thflags, retval;
11302 	uint32_t cts, lcts;
11303 	uint32_t tiwin;
11304 	struct tcpopt to;
11305 	struct tcp_bbr *bbr;
11306 	struct bbr_sendmap *rsm;
11307 	struct timeval ltv;
11308 	int32_t did_out = 0;
11309 	uint16_t nsegs;
11310 	int32_t prev_state;
11311 	uint32_t lost;
11312 
11313 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11314 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11315 	/* add in our stats */
11316 	kern_prefetch(bbr, &prev_state);
11317 	prev_state = 0;
11318 	thflags = tcp_get_flags(th);
11319 	/*
11320 	 * If this is either a state-changing packet or current state isn't
11321 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11322 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11323 	 * caller may have unnecessarily acquired a write lock due to a
11324 	 * race.
11325 	 */
11326 	INP_WLOCK_ASSERT(tptoinpcb(tp));
11327 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11328 	    __func__));
11329 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11330 	    __func__));
11331 
11332 	tp->t_rcvtime = ticks;
11333 	/*
11334 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11335 	 * the scale is zero.
11336 	 */
11337 	tiwin = th->th_win << tp->snd_scale;
11338 #ifdef STATS
11339 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11340 #endif
11341 
11342 	if (m->m_flags & M_TSTMP) {
11343 		/* Prefer the hardware timestamp if present */
11344 		struct timespec ts;
11345 
11346 		mbuf_tstmp2timespec(m, &ts);
11347 		bbr->rc_tv.tv_sec = ts.tv_sec;
11348 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11349 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11350 	} else if (m->m_flags & M_TSTMP_LRO) {
11351 		/* Next the arrival timestamp */
11352 		struct timespec ts;
11353 
11354 		mbuf_tstmp2timespec(m, &ts);
11355 		bbr->rc_tv.tv_sec = ts.tv_sec;
11356 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11357 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11358 	} else {
11359 		/*
11360 		 * Ok just get the current time.
11361 		 */
11362 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11363 	}
11364 	/*
11365 	 * Parse options on any incoming segment.
11366 	 */
11367 	tcp_dooptions(&to, (u_char *)(th + 1),
11368 	    (th->th_off << 2) - sizeof(struct tcphdr),
11369 	    (thflags & TH_SYN) ? TO_SYN : 0);
11370 
11371 	/*
11372 	 * If timestamps were negotiated during SYN/ACK and a
11373 	 * segment without a timestamp is received, silently drop
11374 	 * the segment, unless it is a RST segment or missing timestamps are
11375 	 * tolerated.
11376 	 * See section 3.2 of RFC 7323.
11377 	 */
11378 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11379 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11380 		retval = 0;
11381 		m_freem(m);
11382 		goto done_with_input;
11383 	}
11384 	/*
11385 	 * If echoed timestamp is later than the current time, fall back to
11386 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11387 	 * were used when this connection was established.
11388 	 */
11389 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11390 		to.to_tsecr -= tp->ts_offset;
11391 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11392 			to.to_tsecr = 0;
11393 	}
11394 	/*
11395 	 * If its the first time in we need to take care of options and
11396 	 * verify we can do SACK for rack!
11397 	 */
11398 	if (bbr->r_state == 0) {
11399 		/*
11400 		 * Process options only when we get SYN/ACK back. The SYN
11401 		 * case for incoming connections is handled in tcp_syncache.
11402 		 * According to RFC1323 the window field in a SYN (i.e., a
11403 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11404 		 * this is traditional behavior, may need to be cleaned up.
11405 		 */
11406 		if (bbr->rc_inp == NULL) {
11407 			bbr->rc_inp = inp;
11408 		}
11409 		/*
11410 		 * We need to init rc_inp here since its not init'd when
11411 		 * bbr_init is called
11412 		 */
11413 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11414 			if ((to.to_flags & TOF_SCALE) &&
11415 			    (tp->t_flags & TF_REQ_SCALE)) {
11416 				tp->t_flags |= TF_RCVD_SCALE;
11417 				tp->snd_scale = to.to_wscale;
11418 			} else
11419 				tp->t_flags &= ~TF_REQ_SCALE;
11420 			/*
11421 			 * Initial send window.  It will be updated with the
11422 			 * next incoming segment to the scaled value.
11423 			 */
11424 			tp->snd_wnd = th->th_win;
11425 			if ((to.to_flags & TOF_TS) &&
11426 			    (tp->t_flags & TF_REQ_TSTMP)) {
11427 				tp->t_flags |= TF_RCVD_TSTMP;
11428 				tp->ts_recent = to.to_tsval;
11429 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11430 			} else
11431 			    tp->t_flags &= ~TF_REQ_TSTMP;
11432 			if (to.to_flags & TOF_MSS)
11433 				tcp_mss(tp, to.to_mss);
11434 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11435 			    (to.to_flags & TOF_SACKPERM) == 0)
11436 				tp->t_flags &= ~TF_SACK_PERMIT;
11437 			if (IS_FASTOPEN(tp->t_flags)) {
11438 				if (to.to_flags & TOF_FASTOPEN) {
11439 					uint16_t mss;
11440 
11441 					if (to.to_flags & TOF_MSS)
11442 						mss = to.to_mss;
11443 					else
11444 						if ((inp->inp_vflag & INP_IPV6) != 0)
11445 							mss = TCP6_MSS;
11446 						else
11447 							mss = TCP_MSS;
11448 					tcp_fastopen_update_cache(tp, mss,
11449 					    to.to_tfo_len, to.to_tfo_cookie);
11450 				} else
11451 					tcp_fastopen_disable_path(tp);
11452 			}
11453 		}
11454 		/*
11455 		 * At this point we are at the initial call. Here we decide
11456 		 * if we are doing RACK or not. We do this by seeing if
11457 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11458 		 * we switch to the default code.
11459 		 */
11460 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11461 			/* Bail */
11462 			tcp_switch_back_to_default(tp);
11463 			(*tp->t_fb->tfb_tcp_do_segment) (m, th, so, tp, drop_hdrlen,
11464 			    tlen, iptos);
11465 			return (1);
11466 		}
11467 		/* Set the flag */
11468 		bbr->r_is_v6 = (inp->inp_vflag & INP_IPV6) != 0;
11469 		tcp_set_hpts(inp);
11470 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11471 	}
11472 	if (thflags & TH_ACK) {
11473 		/* Track ack types */
11474 		if (to.to_flags & TOF_SACK)
11475 			BBR_STAT_INC(bbr_acks_with_sacks);
11476 		else
11477 			BBR_STAT_INC(bbr_plain_acks);
11478 	}
11479 	/*
11480 	 * This is the one exception case where we set the rack state
11481 	 * always. All other times (timers etc) we must have a rack-state
11482 	 * set (so we assure we have done the checks above for SACK).
11483 	 */
11484 	if (thflags & TH_FIN)
11485 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11486 	if (bbr->r_state != tp->t_state)
11487 		bbr_set_state(tp, bbr, tiwin);
11488 
11489 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11490 		kern_prefetch(rsm, &prev_state);
11491 	prev_state = bbr->r_state;
11492 	bbr->rc_ack_was_delayed = 0;
11493 	lost = bbr->r_ctl.rc_lost;
11494 	bbr->rc_is_pkt_epoch_now = 0;
11495 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11496 		/* Get the real time into lcts and figure the real delay */
11497 		lcts = tcp_get_usecs(&ltv);
11498 		if (TSTMP_GT(lcts, cts)) {
11499 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11500 			bbr->rc_ack_was_delayed = 1;
11501 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11502 				     bbr->r_ctl.highest_hdwr_delay))
11503 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11504 		} else {
11505 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11506 			bbr->rc_ack_was_delayed = 0;
11507 		}
11508 	} else {
11509 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11510 		bbr->rc_ack_was_delayed = 0;
11511 	}
11512 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11513 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11514 		retval = 0;
11515 		m_freem(m);
11516 		goto done_with_input;
11517 	}
11518 	/*
11519 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11520 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11521 	 */
11522 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11523 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11524 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11525 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11526 		return (1);
11527 	}
11528 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11529 		bbr->r_ctl.rc_high_rwnd = tiwin;
11530 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11531 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11532 	bbr->rtt_valid = 0;
11533 	if (to.to_flags & TOF_TS) {
11534 		bbr->rc_ts_valid = 1;
11535 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11536 	} else {
11537 		bbr->rc_ts_valid = 0;
11538 		bbr->r_ctl.last_inbound_ts = 0;
11539 	}
11540 	retval = (*bbr->r_substate) (m, th, so,
11541 	    tp, &to, drop_hdrlen,
11542 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11543 	if (nxt_pkt == 0)
11544 		BBR_STAT_INC(bbr_rlock_left_ret0);
11545 	else
11546 		BBR_STAT_INC(bbr_rlock_left_ret1);
11547 	if (retval == 0) {
11548 		/*
11549 		 * If retval is 1 the tcb is unlocked and most likely the tp
11550 		 * is gone.
11551 		 */
11552 		INP_WLOCK_ASSERT(inp);
11553 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11554 		if (bbr->rc_is_pkt_epoch_now)
11555 			bbr_set_pktepoch(bbr, cts, __LINE__);
11556 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11557 		if (nxt_pkt == 0) {
11558 			if (bbr->r_wanted_output != 0) {
11559 				bbr->rc_output_starts_timer = 0;
11560 				did_out = 1;
11561 				if (tcp_output(tp) < 0)
11562 					return (1);
11563 			} else
11564 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11565 		}
11566 		if ((nxt_pkt == 0) &&
11567 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11568 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11569 		     (tp->t_flags & TF_DELACK) ||
11570 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11571 		      (tp->t_state <= TCPS_CLOSING)))) {
11572 			/*
11573 			 * We could not send (probably in the hpts but
11574 			 * stopped the timer)?
11575 			 */
11576 			if ((tp->snd_max == tp->snd_una) &&
11577 			    ((tp->t_flags & TF_DELACK) == 0) &&
11578 			    (tcp_in_hpts(bbr->rc_inp)) &&
11579 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11580 				/*
11581 				 * keep alive not needed if we are hptsi
11582 				 * output yet
11583 				 */
11584 				;
11585 			} else {
11586 				if (tcp_in_hpts(bbr->rc_inp)) {
11587 					tcp_hpts_remove(bbr->rc_inp);
11588 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11589 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11590 						uint32_t del;
11591 
11592 						del = lcts - bbr->rc_pacer_started;
11593 						if (bbr->r_ctl.rc_last_delay_val > del) {
11594 							BBR_STAT_INC(bbr_force_timer_start);
11595 							bbr->r_ctl.rc_last_delay_val -= del;
11596 							bbr->rc_pacer_started = lcts;
11597 						} else {
11598 							/* We are late */
11599 							bbr->r_ctl.rc_last_delay_val = 0;
11600 							BBR_STAT_INC(bbr_force_output);
11601 							if (tcp_output(tp) < 0)
11602 								return (1);
11603 						}
11604 					}
11605 				}
11606 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11607 				    0);
11608 			}
11609 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11610 			/* Do we have the correct timer running? */
11611 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11612 		}
11613 		/* Do we have a new state */
11614 		if (bbr->r_state != tp->t_state)
11615 			bbr_set_state(tp, bbr, tiwin);
11616 done_with_input:
11617 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11618 		if (did_out)
11619 			bbr->r_wanted_output = 0;
11620 	}
11621 	return (retval);
11622 }
11623 
11624 static void
11625 bbr_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
11626     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11627 {
11628 	struct timeval tv;
11629 	int retval;
11630 
11631 	/* First lets see if we have old packets */
11632 	if (tp->t_in_pkt) {
11633 		if (ctf_do_queued_segments(so, tp, 1)) {
11634 			m_freem(m);
11635 			return;
11636 		}
11637 	}
11638 	if (m->m_flags & M_TSTMP_LRO) {
11639 		mbuf_tstmp2timeval(m, &tv);
11640 	} else {
11641 		/* Should not be should we kassert instead? */
11642 		tcp_get_usecs(&tv);
11643 	}
11644 	retval = bbr_do_segment_nounlock(m, th, so, tp,
11645 					 drop_hdrlen, tlen, iptos, 0, &tv);
11646 	if (retval == 0) {
11647 		INP_WUNLOCK(tptoinpcb(tp));
11648 	}
11649 }
11650 
11651 /*
11652  * Return how much data can be sent without violating the
11653  * cwnd or rwnd.
11654  */
11655 
11656 static inline uint32_t
11657 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11658     uint32_t avail, int32_t sb_offset, uint32_t cts)
11659 {
11660 	uint32_t len;
11661 
11662 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11663 		/* We never want to go over our peers rcv-window */
11664 		len = 0;
11665 	} else {
11666 		uint32_t flight;
11667 
11668 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11669 		if (flight >= sendwin) {
11670 			/*
11671 			 * We have in flight what we are allowed by cwnd (if
11672 			 * it was rwnd blocking it would have hit above out
11673 			 * >= tp->snd_wnd).
11674 			 */
11675 			return (0);
11676 		}
11677 		len = sendwin - flight;
11678 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11679 			/* We would send too much (beyond the rwnd) */
11680 			len = tp->snd_wnd - ctf_outstanding(tp);
11681 		}
11682 		if ((len + sb_offset) > avail) {
11683 			/*
11684 			 * We don't have that much in the SB, how much is
11685 			 * there?
11686 			 */
11687 			len = avail - sb_offset;
11688 		}
11689 	}
11690 	return (len);
11691 }
11692 
11693 static inline void
11694 bbr_do_error_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11695 {
11696 #ifdef NETFLIX_STATS
11697 	KMOD_TCPSTAT_INC(tcps_sndpack_error);
11698 	KMOD_TCPSTAT_ADD(tcps_sndbyte_error, len);
11699 #endif
11700 }
11701 
11702 static inline void
11703 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11704 {
11705 	if (error) {
11706 		bbr_do_error_accounting(tp, bbr, rsm, len, error);
11707 		return;
11708 	}
11709 	if (rsm) {
11710 		if (rsm->r_flags & BBR_TLP) {
11711 			/*
11712 			 * TLP should not count in retran count, but in its
11713 			 * own bin
11714 			 */
11715 #ifdef NETFLIX_STATS
11716 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11717 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11718 #endif
11719 		} else {
11720 			/* Retransmit */
11721 			tp->t_sndrexmitpack++;
11722 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11723 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11724 #ifdef STATS
11725 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11726 			    len);
11727 #endif
11728 		}
11729 		/*
11730 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11731 		 * sub-state
11732 		 */
11733 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11734 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11735 			/* Non probe_bw log in 1, 2, or 4. */
11736 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11737 		} else {
11738 			/*
11739 			 * Log our probe state 3, and log also 5-13 to show
11740 			 * us the recovery sub-state for the send. This
11741 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11742 			 */
11743 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11744 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11745 		}
11746 		/* Place in both 16's the totals of retransmitted */
11747 		counter_u64_add(bbr_state_lost[16], len);
11748 		counter_u64_add(bbr_state_resend[16], len);
11749 		/* Place in 17's the total sent */
11750 		counter_u64_add(bbr_state_resend[17], len);
11751 		counter_u64_add(bbr_state_lost[17], len);
11752 
11753 	} else {
11754 		/* New sends */
11755 		KMOD_TCPSTAT_INC(tcps_sndpack);
11756 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11757 		/* Place in 17's the total sent */
11758 		counter_u64_add(bbr_state_resend[17], len);
11759 		counter_u64_add(bbr_state_lost[17], len);
11760 #ifdef STATS
11761 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11762 		    len);
11763 #endif
11764 	}
11765 }
11766 
11767 static void
11768 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11769 {
11770 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11771 		/*
11772 		 * Limit the cwnd to not be above N x the target plus whats
11773 		 * is outstanding. The target is based on the current b/w
11774 		 * estimate.
11775 		 */
11776 		uint32_t target;
11777 
11778 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11779 		target += ctf_outstanding(tp);
11780 		target *= bbr_target_cwnd_mult_limit;
11781 		if (tp->snd_cwnd > target)
11782 			tp->snd_cwnd = target;
11783 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11784 	}
11785 }
11786 
11787 static int
11788 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11789 {
11790 	/*
11791 	 * "adv" is the amount we could increase the window, taking into
11792 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11793 	 */
11794 	int32_t adv;
11795 	int32_t oldwin;
11796 
11797 	adv = recwin;
11798 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11799 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11800 		if (adv > oldwin)
11801 			adv -= oldwin;
11802 		else {
11803 			/* We can't increase the window */
11804 			adv = 0;
11805 		}
11806 	} else
11807 		oldwin = 0;
11808 
11809 	/*
11810 	 * If the new window size ends up being the same as or less
11811 	 * than the old size when it is scaled, then don't force
11812 	 * a window update.
11813 	 */
11814 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11815 		return (0);
11816 
11817 	if (adv >= (2 * maxseg) &&
11818 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11819 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11820 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11821 		return (1);
11822 	}
11823 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11824 		return (1);
11825 	return (0);
11826 }
11827 
11828 /*
11829  * Return 0 on success and a errno on failure to send.
11830  * Note that a 0 return may not mean we sent anything
11831  * if the TCB was on the hpts. A non-zero return
11832  * does indicate the error we got from ip[6]_output.
11833  */
11834 static int
11835 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11836 {
11837 	struct socket *so;
11838 	int32_t len;
11839 	uint32_t cts;
11840 	uint32_t recwin, sendwin;
11841 	int32_t sb_offset;
11842 	int32_t flags, abandon, error = 0;
11843 	struct tcp_log_buffer *lgb = NULL;
11844 	struct mbuf *m;
11845 	struct mbuf *mb;
11846 	uint32_t if_hw_tsomaxsegcount = 0;
11847 	uint32_t if_hw_tsomaxsegsize = 0;
11848 	uint32_t if_hw_tsomax = 0;
11849 	struct ip *ip = NULL;
11850 #ifdef TCPDEBUG
11851 	struct ipovly *ipov = NULL;
11852 #endif
11853 	struct tcp_bbr *bbr;
11854 	struct tcphdr *th;
11855 	struct udphdr *udp = NULL;
11856 	u_char opt[TCP_MAXOLEN];
11857 	unsigned ipoptlen, optlen, hdrlen;
11858 	unsigned ulen;
11859 	uint32_t bbr_seq;
11860 	uint32_t delay_calc=0;
11861 	uint8_t doing_tlp = 0;
11862 	uint8_t local_options;
11863 #ifdef BBR_INVARIANTS
11864 	uint8_t doing_retran_from = 0;
11865 	uint8_t picked_up_retran = 0;
11866 #endif
11867 	uint8_t wanted_cookie = 0;
11868 	uint8_t more_to_rxt=0;
11869 	int32_t prefetch_so_done = 0;
11870 	int32_t prefetch_rsm = 0;
11871 	uint32_t tot_len = 0;
11872 	uint32_t maxseg, pace_max_segs, p_maxseg;
11873 	int32_t csum_flags = 0;
11874  	int32_t hw_tls;
11875 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11876 	unsigned ipsec_optlen = 0;
11877 
11878 #endif
11879 	volatile int32_t sack_rxmit;
11880 	struct bbr_sendmap *rsm = NULL;
11881 	int32_t tso, mtu;
11882 	struct tcpopt to;
11883 	int32_t slot = 0;
11884 	struct inpcb *inp;
11885 	struct sockbuf *sb;
11886 	uint32_t hpts_calling;
11887 #ifdef INET6
11888 	struct ip6_hdr *ip6 = NULL;
11889 	int32_t isipv6;
11890 #endif
11891 	uint8_t app_limited = BBR_JR_SENT_DATA;
11892 	uint8_t filled_all = 0;
11893 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11894 	/* We take a cache hit here */
11895 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11896 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11897 	inp = bbr->rc_inp;
11898 	so = inp->inp_socket;
11899 	sb = &so->so_snd;
11900  	if (sb->sb_flags & SB_TLS_IFNET)
11901  		hw_tls = 1;
11902  	else
11903  		hw_tls = 0;
11904 	kern_prefetch(sb, &maxseg);
11905 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11906 	if (bbr_minseg(bbr) < maxseg) {
11907 		tcp_bbr_tso_size_check(bbr, cts);
11908 	}
11909 	/* Remove any flags that indicate we are pacing on the inp  */
11910 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11911 	p_maxseg = min(maxseg, pace_max_segs);
11912 	INP_WLOCK_ASSERT(inp);
11913 #ifdef TCP_OFFLOAD
11914 	if (tp->t_flags & TF_TOE)
11915 		return (tcp_offload_output(tp));
11916 #endif
11917 
11918 #ifdef INET6
11919 	if (bbr->r_state) {
11920 		/* Use the cache line loaded if possible */
11921 		isipv6 = bbr->r_is_v6;
11922 	} else {
11923 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11924 	}
11925 #endif
11926 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11927 	    tcp_in_hpts(inp)) {
11928 		/*
11929 		 * We are on the hpts for some timer but not hptsi output.
11930 		 * Possibly remove from the hpts so we can send/recv etc.
11931 		 */
11932 		if ((tp->t_flags & TF_ACKNOW) == 0) {
11933 			/*
11934 			 * No immediate demand right now to send an ack, but
11935 			 * the user may have read, making room for new data
11936 			 * (a window update). If so we may want to cancel
11937 			 * whatever timer is running (KEEP/DEL-ACK?) and
11938 			 * continue to send out a window update. Or we may
11939 			 * have gotten more data into the socket buffer to
11940 			 * send.
11941 			 */
11942 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
11943 				      (long)TCP_MAXWIN << tp->rcv_scale);
11944 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
11945 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
11946 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
11947 			    (tp->snd_max - tp->snd_una))) {
11948 				/*
11949 				 * Nothing new to send and no window update
11950 				 * is needed to send. Lets just return and
11951 				 * let the timer-run off.
11952 				 */
11953 				return (0);
11954 			}
11955 		}
11956 		tcp_hpts_remove(inp);
11957 		bbr_timer_cancel(bbr, __LINE__, cts);
11958 	}
11959 	if (bbr->r_ctl.rc_last_delay_val) {
11960 		/* Calculate a rough delay for early escape to sending  */
11961 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11962 			delay_calc = cts - bbr->rc_pacer_started;
11963 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11964 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11965 		else
11966 			delay_calc = 0;
11967 	}
11968 	/* Mark that we have called bbr_output(). */
11969 	if ((bbr->r_timer_override) ||
11970 	    (tp->t_state < TCPS_ESTABLISHED)) {
11971 		/* Timeouts or early states are exempt */
11972 		if (tcp_in_hpts(inp))
11973 			tcp_hpts_remove(inp);
11974 	} else if (tcp_in_hpts(inp)) {
11975 		if ((bbr->r_ctl.rc_last_delay_val) &&
11976 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11977 		    delay_calc) {
11978 			/*
11979 			 * We were being paced for output and the delay has
11980 			 * already exceeded when we were supposed to be
11981 			 * called, lets go ahead and pull out of the hpts
11982 			 * and call output.
11983 			 */
11984 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
11985 			bbr->r_ctl.rc_last_delay_val = 0;
11986 			tcp_hpts_remove(inp);
11987 		} else if (tp->t_state == TCPS_CLOSED) {
11988 			bbr->r_ctl.rc_last_delay_val = 0;
11989 			tcp_hpts_remove(inp);
11990 		} else {
11991 			/*
11992 			 * On the hpts, you shall not pass! even if ACKNOW
11993 			 * is on, we will when the hpts fires, unless of
11994 			 * course we are overdue.
11995 			 */
11996 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
11997 			return (0);
11998 		}
11999 	}
12000 	bbr->rc_cwnd_limited = 0;
12001 	if (bbr->r_ctl.rc_last_delay_val) {
12002 		/* recalculate the real delay and deal with over/under  */
12003 		if (SEQ_GT(cts, bbr->rc_pacer_started))
12004 			delay_calc = cts - bbr->rc_pacer_started;
12005 		else
12006 			delay_calc = 0;
12007 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
12008 			/* Setup the delay which will be added in */
12009 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
12010 		else {
12011 			/*
12012 			 * We are early setup to adjust
12013 			 * our slot time.
12014 			 */
12015 			uint64_t merged_val;
12016 
12017 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
12018 			bbr->r_agg_early_set = 1;
12019 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
12020 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
12021 					/* Nope our previous late cancels out the early */
12022 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
12023 					bbr->r_agg_early_set = 0;
12024 					bbr->r_ctl.rc_agg_early = 0;
12025 				} else {
12026 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
12027 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
12028 				}
12029 			}
12030 			merged_val = bbr->rc_pacer_started;
12031 			merged_val <<= 32;
12032 			merged_val |= bbr->r_ctl.rc_last_delay_val;
12033 			bbr_log_pacing_delay_calc(bbr, inp->inp_hpts_calls,
12034 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12035 						 bbr->r_agg_early_set, 3);
12036 			bbr->r_ctl.rc_last_delay_val = 0;
12037 			BBR_STAT_INC(bbr_early);
12038 			delay_calc = 0;
12039 		}
12040 	} else {
12041 		/* We were not delayed due to hptsi */
12042 		if (bbr->r_agg_early_set)
12043 			bbr->r_ctl.rc_agg_early = 0;
12044 		bbr->r_agg_early_set = 0;
12045 		delay_calc = 0;
12046 	}
12047 	if (delay_calc) {
12048 		/*
12049 		 * We had a hptsi delay which means we are falling behind on
12050 		 * sending at the expected rate. Calculate an extra amount
12051 		 * of data we can send, if any, to put us back on track.
12052 		 */
12053 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12054 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12055 		else
12056 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12057 	}
12058 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12059 	if ((tp->snd_una == tp->snd_max) &&
12060 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12061 	    (sbavail(sb))) {
12062 		/*
12063 		 * Ok we have been idle with nothing outstanding
12064 		 * we possibly need to start fresh with either a new
12065 		 * suite of states or a fast-ramp up.
12066 		 */
12067 		bbr_restart_after_idle(bbr,
12068 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12069 	}
12070 	/*
12071 	 * Now was there a hptsi delay where we are behind? We only count
12072 	 * being behind if: a) We are not in recovery. b) There was a delay.
12073 	 * <and> c) We had room to send something.
12074 	 *
12075 	 */
12076 	hpts_calling = inp->inp_hpts_calls;
12077 	inp->inp_hpts_calls = 0;
12078 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12079 		int retval;
12080 
12081 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12082 		if (retval != 0) {
12083 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12084 			/*
12085 			 * If timers want tcp_drop(), then pass error out,
12086 			 * otherwise suppress it.
12087 			 */
12088 			return (retval < 0 ? retval : 0);
12089 		}
12090 	}
12091 	bbr->rc_inp->inp_flags2 &= ~INP_MBUF_QUEUE_READY;
12092 	if (hpts_calling &&
12093 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12094 		bbr->r_ctl.rc_last_delay_val = 0;
12095 	}
12096 	bbr->r_timer_override = 0;
12097 	bbr->r_wanted_output = 0;
12098 	/*
12099 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12100 	 * SYN|ACK and those sent by the retransmit timer.
12101 	 */
12102 	if (IS_FASTOPEN(tp->t_flags) &&
12103 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12104 	     (tp->t_state == TCPS_SYN_SENT)) &&
12105 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12106 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12107 		len = 0;
12108 		goto just_return_nolock;
12109 	}
12110 	/*
12111 	 * Before sending anything check for a state update. For hpts
12112 	 * calling without input this is important. If its input calling
12113 	 * then this was already done.
12114 	 */
12115 	if (bbr->rc_use_google == 0)
12116 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12117 again:
12118 	/*
12119 	 * If we've recently taken a timeout, snd_max will be greater than
12120 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12121 	 * for historic reasons the persist timer still uses it. This means
12122 	 * we have to look at it. All retransmissions that are not persits
12123 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12124 	 * end of this routine we pull snd_nxt always up to snd_max.
12125 	 */
12126 	doing_tlp = 0;
12127 #ifdef BBR_INVARIANTS
12128 	doing_retran_from = picked_up_retran = 0;
12129 #endif
12130 	error = 0;
12131 	tso = 0;
12132 	slot = 0;
12133 	mtu = 0;
12134 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12135 	sb_offset = tp->snd_max - tp->snd_una;
12136 	flags = tcp_outflags[tp->t_state];
12137 	sack_rxmit = 0;
12138 	len = 0;
12139 	rsm = NULL;
12140 	if (flags & TH_RST) {
12141 		SOCKBUF_LOCK(sb);
12142 		goto send;
12143 	}
12144 recheck_resend:
12145 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12146 		/* We need to always have one in reserve */
12147 		rsm = bbr_alloc(bbr);
12148 		if (rsm == NULL) {
12149 			error = ENOMEM;
12150 			/* Lie to get on the hpts */
12151 			tot_len = tp->t_maxseg;
12152 			if (hpts_calling)
12153 				/* Retry in a ms */
12154 				slot = 1001;
12155 			goto just_return_nolock;
12156 		}
12157 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12158 		bbr->r_ctl.rc_free_cnt++;
12159 		rsm = NULL;
12160 	}
12161 	/* What do we send, a resend? */
12162 	if (bbr->r_ctl.rc_resend == NULL) {
12163 		/* Check for rack timeout */
12164 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12165 		if (bbr->r_ctl.rc_resend) {
12166 #ifdef BBR_INVARIANTS
12167 			picked_up_retran = 1;
12168 #endif
12169 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12170 		}
12171 	}
12172 	if (bbr->r_ctl.rc_resend) {
12173 		rsm = bbr->r_ctl.rc_resend;
12174 #ifdef BBR_INVARIANTS
12175 		doing_retran_from = 1;
12176 #endif
12177 		/* Remove any TLP flags its a RACK or T-O */
12178 		rsm->r_flags &= ~BBR_TLP;
12179 		bbr->r_ctl.rc_resend = NULL;
12180 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12181 #ifdef BBR_INVARIANTS
12182 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12183 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12184 			goto recheck_resend;
12185 #else
12186 			/* TSNH */
12187 			rsm = NULL;
12188 			goto recheck_resend;
12189 #endif
12190 		}
12191 		if (rsm->r_flags & BBR_HAS_SYN) {
12192 			/* Only retransmit a SYN by itself */
12193 			len = 0;
12194 			if ((flags & TH_SYN) == 0) {
12195 				/* Huh something is wrong */
12196 				rsm->r_start++;
12197 				if (rsm->r_start == rsm->r_end) {
12198 					/* Clean it up, somehow we missed the ack? */
12199 					bbr_log_syn(tp, NULL);
12200 				} else {
12201 					/* TFO with data? */
12202 					rsm->r_flags &= ~BBR_HAS_SYN;
12203 					len = rsm->r_end - rsm->r_start;
12204 				}
12205 			} else {
12206 				/* Retransmitting SYN */
12207 				rsm = NULL;
12208 				SOCKBUF_LOCK(sb);
12209 				goto send;
12210 			}
12211 		} else
12212 			len = rsm->r_end - rsm->r_start;
12213 		if ((bbr->rc_resends_use_tso == 0) &&
12214 		    (len > maxseg)) {
12215 			len = maxseg;
12216 			more_to_rxt = 1;
12217 		}
12218 		sb_offset = rsm->r_start - tp->snd_una;
12219 		if (len > 0) {
12220 			sack_rxmit = 1;
12221 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12222 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12223 			    min(len, maxseg));
12224 		} else {
12225 			/* I dont think this can happen */
12226 			rsm = NULL;
12227 			goto recheck_resend;
12228 		}
12229 		BBR_STAT_INC(bbr_resends_set);
12230 	} else if (bbr->r_ctl.rc_tlp_send) {
12231 		/*
12232 		 * Tail loss probe
12233 		 */
12234 		doing_tlp = 1;
12235 		rsm = bbr->r_ctl.rc_tlp_send;
12236 		bbr->r_ctl.rc_tlp_send = NULL;
12237 		sack_rxmit = 1;
12238 		len = rsm->r_end - rsm->r_start;
12239 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12240 			len = maxseg;
12241 
12242 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12243 #ifdef BBR_INVARIANTS
12244 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12245 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12246 #else
12247 			/* TSNH */
12248 			rsm = NULL;
12249 			goto recheck_resend;
12250 #endif
12251 		}
12252 		sb_offset = rsm->r_start - tp->snd_una;
12253 		BBR_STAT_INC(bbr_tlp_set);
12254 	}
12255 	/*
12256 	 * Enforce a connection sendmap count limit if set
12257 	 * as long as we are not retransmiting.
12258 	 */
12259 	if ((rsm == NULL) &&
12260 	    (V_tcp_map_entries_limit > 0) &&
12261 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12262 		BBR_STAT_INC(bbr_alloc_limited);
12263 		if (!bbr->alloc_limit_reported) {
12264 			bbr->alloc_limit_reported = 1;
12265 			BBR_STAT_INC(bbr_alloc_limited_conns);
12266 		}
12267 		goto just_return_nolock;
12268 	}
12269 #ifdef BBR_INVARIANTS
12270 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12271 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12272 		    tp, bbr, rsm, sb_offset, len);
12273 	}
12274 #endif
12275 	/*
12276 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12277 	 * state flags.
12278 	 */
12279 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12280 		flags |= TH_FIN;
12281 	if (tp->t_flags & TF_NEEDSYN)
12282 		flags |= TH_SYN;
12283 
12284 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12285 		/* we are retransmitting the fin */
12286 		len--;
12287 		if (len) {
12288 			/*
12289 			 * When retransmitting data do *not* include the
12290 			 * FIN. This could happen from a TLP probe if we
12291 			 * allowed data with a FIN.
12292 			 */
12293 			flags &= ~TH_FIN;
12294 		}
12295 	} else if (rsm) {
12296 		if (flags & TH_FIN)
12297 			flags &= ~TH_FIN;
12298 	}
12299 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12300 		void *end_rsm;
12301 
12302 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12303 		if (end_rsm)
12304 			kern_prefetch(end_rsm, &prefetch_rsm);
12305 		prefetch_rsm = 1;
12306 	}
12307 	SOCKBUF_LOCK(sb);
12308 	/*
12309 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12310 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12311 	 * negative length.  This can also occur when TCP opens up its
12312 	 * congestion window while receiving additional duplicate acks after
12313 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12314 	 * the fast-retransmit.
12315 	 *
12316 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12317 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12318 	 * up 0.
12319 	 *
12320 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12321 	 * in which case len is already set.
12322 	 */
12323 	if (sack_rxmit == 0) {
12324 		uint32_t avail;
12325 
12326 		avail = sbavail(sb);
12327 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12328 			sb_offset = tp->snd_max - tp->snd_una;
12329 		else
12330 			sb_offset = 0;
12331 		if (bbr->rc_tlp_new_data) {
12332 			/* TLP is forcing out new data */
12333 			uint32_t tlplen;
12334 
12335 			doing_tlp = 1;
12336 			tlplen = maxseg;
12337 
12338 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12339 				tlplen = (uint32_t)(avail - sb_offset);
12340 			}
12341 			if (tlplen > tp->snd_wnd) {
12342 				len = tp->snd_wnd;
12343 			} else {
12344 				len = tlplen;
12345 			}
12346 			bbr->rc_tlp_new_data = 0;
12347 		} else {
12348 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12349 			if ((len < p_maxseg) &&
12350 			    (bbr->rc_in_persist == 0) &&
12351 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12352 			    ((avail - sb_offset) >= p_maxseg)) {
12353 				/*
12354 				 * We are not completing whats in the socket
12355 				 * buffer (i.e. there is at least a segment
12356 				 * waiting to send) and we have 2 or more
12357 				 * segments outstanding. There is no sense
12358 				 * of sending a little piece. Lets defer and
12359 				 * and wait until we can send a whole
12360 				 * segment.
12361 				 */
12362 				len = 0;
12363 			}
12364 			if (bbr->rc_in_persist) {
12365 				/*
12366 				 * We are in persists, figure out if
12367 				 * a retransmit is available (maybe the previous
12368 				 * persists we sent) or if we have to send new
12369 				 * data.
12370 				 */
12371 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12372 				if (rsm) {
12373 					len = rsm->r_end - rsm->r_start;
12374 					if (rsm->r_flags & BBR_HAS_FIN)
12375 						len--;
12376 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12377 						len = maxseg;
12378 					if (len > 1)
12379 						BBR_STAT_INC(bbr_persist_reneg);
12380 					/*
12381 					 * XXXrrs we could force the len to
12382 					 * 1 byte here to cause the chunk to
12383 					 * split apart.. but that would then
12384 					 * mean we always retransmit it as
12385 					 * one byte even after the window
12386 					 * opens.
12387 					 */
12388 					sack_rxmit = 1;
12389 					sb_offset = rsm->r_start - tp->snd_una;
12390 				} else {
12391 					/*
12392 					 * First time through in persists or peer
12393 					 * acked our one byte. Though we do have
12394 					 * to have something in the sb.
12395 					 */
12396 					len = 1;
12397 					sb_offset = 0;
12398 					if (avail == 0)
12399 					    len = 0;
12400 				}
12401 			}
12402 		}
12403 	}
12404 	if (prefetch_so_done == 0) {
12405 		kern_prefetch(so, &prefetch_so_done);
12406 		prefetch_so_done = 1;
12407 	}
12408 	/*
12409 	 * Lop off SYN bit if it has already been sent.  However, if this is
12410 	 * SYN-SENT state and if segment contains data and if we don't know
12411 	 * that foreign host supports TAO, suppress sending segment.
12412 	 */
12413 	if ((flags & TH_SYN) && (rsm == NULL) &&
12414 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12415 		if (tp->t_state != TCPS_SYN_RECEIVED)
12416 			flags &= ~TH_SYN;
12417 		/*
12418 		 * When sending additional segments following a TFO SYN|ACK,
12419 		 * do not include the SYN bit.
12420 		 */
12421 		if (IS_FASTOPEN(tp->t_flags) &&
12422 		    (tp->t_state == TCPS_SYN_RECEIVED))
12423 			flags &= ~TH_SYN;
12424 		sb_offset--, len++;
12425 		if (sbavail(sb) == 0)
12426 			len = 0;
12427 	} else if ((flags & TH_SYN) && rsm) {
12428 		/*
12429 		 * Subtract one from the len for the SYN being
12430 		 * retransmitted.
12431 		 */
12432 		len--;
12433 	}
12434 	/*
12435 	 * Be careful not to send data and/or FIN on SYN segments. This
12436 	 * measure is needed to prevent interoperability problems with not
12437 	 * fully conformant TCP implementations.
12438 	 */
12439 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12440 		len = 0;
12441 		flags &= ~TH_FIN;
12442 	}
12443 	/*
12444 	 * On TFO sockets, ensure no data is sent in the following cases:
12445 	 *
12446 	 *  - When retransmitting SYN|ACK on a passively-created socket
12447 	 *  - When retransmitting SYN on an actively created socket
12448 	 *  - When sending a zero-length cookie (cookie request) on an
12449 	 *    actively created socket
12450 	 *  - When the socket is in the CLOSED state (RST is being sent)
12451 	 */
12452 	if (IS_FASTOPEN(tp->t_flags) &&
12453 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12454 	     ((tp->t_state == TCPS_SYN_SENT) &&
12455 	      (tp->t_tfo_client_cookie_len == 0)) ||
12456 	     (flags & TH_RST))) {
12457 		len = 0;
12458 		sack_rxmit = 0;
12459 		rsm = NULL;
12460 	}
12461 	/* Without fast-open there should never be data sent on a SYN */
12462 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12463 		len = 0;
12464 	if (len <= 0) {
12465 		/*
12466 		 * If FIN has been sent but not acked, but we haven't been
12467 		 * called to retransmit, len will be < 0.  Otherwise, window
12468 		 * shrank after we sent into it.  If window shrank to 0,
12469 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12470 		 * window, and set the persist timer if it isn't already
12471 		 * going.  If the window didn't close completely, just wait
12472 		 * for an ACK.
12473 		 *
12474 		 * We also do a general check here to ensure that we will
12475 		 * set the persist timer when we have data to send, but a
12476 		 * 0-byte window. This makes sure the persist timer is set
12477 		 * even if the packet hits one of the "goto send" lines
12478 		 * below.
12479 		 */
12480 		len = 0;
12481 		if ((tp->snd_wnd == 0) &&
12482 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12483 		    (tp->snd_una == tp->snd_max) &&
12484 		    (sb_offset < (int)sbavail(sb))) {
12485 			/*
12486 			 * Not enough room in the rwnd to send
12487 			 * a paced segment out.
12488 			 */
12489 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12490 		}
12491 	} else if ((rsm == NULL) &&
12492 		   (doing_tlp == 0) &&
12493 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12494 		/*
12495 		 * We are not sending a full segment for
12496 		 * some reason. Should we not send anything (think
12497 		 * sws or persists)?
12498 		 */
12499 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12500 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12501 		    (len < (int)(sbavail(sb) - sb_offset))) {
12502 			/*
12503 			 * Here the rwnd is less than
12504 			 * the pacing size, this is not a retransmit,
12505 			 * we are established and
12506 			 * the send is not the last in the socket buffer
12507 			 * lets not send, and possibly enter persists.
12508 			 */
12509 			len = 0;
12510 			if (tp->snd_max == tp->snd_una)
12511 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12512 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12513 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12514 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12515 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12516 			   (len < bbr_minseg(bbr))) {
12517 			/*
12518 			 * Here we are not retransmitting, and
12519 			 * the cwnd is not so small that we could
12520 			 * not send at least a min size (rxt timer
12521 			 * not having gone off), We have 2 segments or
12522 			 * more already in flight, its not the tail end
12523 			 * of the socket buffer  and the cwnd is blocking
12524 			 * us from sending out minimum pacing segment size.
12525 			 * Lets not send anything.
12526 			 */
12527 			bbr->rc_cwnd_limited = 1;
12528 			len = 0;
12529 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12530 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12531 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12532 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12533 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12534 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12535 			/*
12536 			 * Here we have a send window but we have
12537 			 * filled it up and we can't send another pacing segment.
12538 			 * We also have in flight more than 2 segments
12539 			 * and we are not completing the sb i.e. we allow
12540 			 * the last bytes of the sb to go out even if
12541 			 * its not a full pacing segment.
12542 			 */
12543 			len = 0;
12544 		}
12545 	}
12546 	/* len will be >= 0 after this point. */
12547 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12548 	tcp_sndbuf_autoscale(tp, so, sendwin);
12549 	/*
12550 	 *
12551 	 */
12552 	if (bbr->rc_in_persist &&
12553 	    len &&
12554 	    (rsm == NULL) &&
12555 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12556 		/*
12557 		 * We are in persist, not doing a retransmit and don't have enough space
12558 		 * yet to send a full TSO. So is it at the end of the sb
12559 		 * if so we need to send else nuke to 0 and don't send.
12560 		 */
12561 		int sbleft;
12562 		if (sbavail(sb) > sb_offset)
12563 			sbleft = sbavail(sb) - sb_offset;
12564 		else
12565 			sbleft = 0;
12566 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12567 			/* not at end of sb lets not send */
12568 			len = 0;
12569 		}
12570 	}
12571 	/*
12572 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12573 	 * hardware).
12574 	 *
12575 	 * TSO may only be used if we are in a pure bulk sending state.  The
12576 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12577 	 * options prevent using TSO.  With TSO the TCP header is the same
12578 	 * (except for the sequence number) for all generated packets.  This
12579 	 * makes it impossible to transmit any options which vary per
12580 	 * generated segment or packet.
12581 	 *
12582 	 * IPv4 handling has a clear separation of ip options and ip header
12583 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12584 	 * does the right thing below to provide length of just ip options
12585 	 * and thus checking for ipoptlen is enough to decide if ip options
12586 	 * are present.
12587 	 */
12588 #ifdef INET6
12589 	if (isipv6)
12590 		ipoptlen = ip6_optlen(inp);
12591 	else
12592 #endif
12593 	if (inp->inp_options)
12594 		ipoptlen = inp->inp_options->m_len -
12595 		    offsetof(struct ipoption, ipopt_list);
12596 	else
12597 		ipoptlen = 0;
12598 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12599 	/*
12600 	 * Pre-calculate here as we save another lookup into the darknesses
12601 	 * of IPsec that way and can actually decide if TSO is ok.
12602 	 */
12603 #ifdef INET6
12604 	if (isipv6 && IPSEC_ENABLED(ipv6))
12605 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12606 #ifdef INET
12607 	else
12608 #endif
12609 #endif				/* INET6 */
12610 #ifdef INET
12611 	if (IPSEC_ENABLED(ipv4))
12612 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12613 #endif				/* INET */
12614 #endif				/* IPSEC */
12615 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12616 	ipoptlen += ipsec_optlen;
12617 #endif
12618 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12619 	    (len > maxseg) &&
12620 	    (tp->t_port == 0) &&
12621 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12622 	    tp->rcv_numsacks == 0 &&
12623 	    ipoptlen == 0)
12624 		tso = 1;
12625 
12626 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12627 	    (long)TCP_MAXWIN << tp->rcv_scale);
12628 	/*
12629 	 * Sender silly window avoidance.   We transmit under the following
12630 	 * conditions when len is non-zero:
12631 	 *
12632 	 * - We have a full segment (or more with TSO) - This is the last
12633 	 * buffer in a write()/send() and we are either idle or running
12634 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12635 	 * then 1/2 the maximum send window's worth of data (receiver may be
12636 	 * limited the window size) - we need to retransmit
12637 	 */
12638 	if (rsm)
12639 		goto send;
12640 	if (len) {
12641 		if (sack_rxmit)
12642 			goto send;
12643 		if (len >= p_maxseg)
12644 			goto send;
12645 		/*
12646 		 * NOTE! on localhost connections an 'ack' from the remote
12647 		 * end may occur synchronously with the output and cause us
12648 		 * to flush a buffer queued with moretocome.  XXX
12649 		 *
12650 		 */
12651 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12652 		    ((tp->t_flags & TF_NODELAY) ||
12653 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12654 		    (tp->t_flags & TF_NOPUSH) == 0) {
12655 			goto send;
12656 		}
12657 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12658 			goto send;
12659 		}
12660 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12661 			goto send;
12662 		}
12663 	}
12664 	/*
12665 	 * Sending of standalone window updates.
12666 	 *
12667 	 * Window updates are important when we close our window due to a
12668 	 * full socket buffer and are opening it again after the application
12669 	 * reads data from it.  Once the window has opened again and the
12670 	 * remote end starts to send again the ACK clock takes over and
12671 	 * provides the most current window information.
12672 	 *
12673 	 * We must avoid the silly window syndrome whereas every read from
12674 	 * the receive buffer, no matter how small, causes a window update
12675 	 * to be sent.  We also should avoid sending a flurry of window
12676 	 * updates when the socket buffer had queued a lot of data and the
12677 	 * application is doing small reads.
12678 	 *
12679 	 * Prevent a flurry of pointless window updates by only sending an
12680 	 * update when we can increase the advertized window by more than
12681 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12682 	 * full or is very small be more aggressive and send an update
12683 	 * whenever we can increase by two mss sized segments. In all other
12684 	 * situations the ACK's to new incoming data will carry further
12685 	 * window increases.
12686 	 *
12687 	 * Don't send an independent window update if a delayed ACK is
12688 	 * pending (it will get piggy-backed on it) or the remote side
12689 	 * already has done a half-close and won't send more data.  Skip
12690 	 * this if the connection is in T/TCP half-open state.
12691 	 */
12692 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12693 	    !(tp->t_flags & TF_DELACK) &&
12694 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12695 		/* Check to see if we should do a window update */
12696 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12697 			goto send;
12698 	}
12699 	/*
12700 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12701 	 * is also a catch-all for the retransmit timer timeout case.
12702 	 */
12703 	if (tp->t_flags & TF_ACKNOW) {
12704 		goto send;
12705 	}
12706 	if (flags & TH_RST) {
12707 		/* Always send a RST if one is due */
12708 		goto send;
12709 	}
12710 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12711 		goto send;
12712 	}
12713 	/*
12714 	 * If our state indicates that FIN should be sent and we have not
12715 	 * yet done so, then we need to send.
12716 	 */
12717 	if (flags & TH_FIN &&
12718 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12719 		goto send;
12720 	}
12721 	/*
12722 	 * No reason to send a segment, just return.
12723 	 */
12724 just_return:
12725 	SOCKBUF_UNLOCK(sb);
12726 just_return_nolock:
12727 	if (tot_len)
12728 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12729 	if (bbr->rc_no_pacing)
12730 		slot = 0;
12731 	if (tot_len == 0) {
12732 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12733 		    tp->snd_wnd) {
12734 			BBR_STAT_INC(bbr_rwnd_limited);
12735 			app_limited = BBR_JR_RWND_LIMITED;
12736 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12737 			if ((bbr->rc_in_persist == 0) &&
12738 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12739 			    (tp->snd_max == tp->snd_una) &&
12740 			    sbavail(&so->so_snd)) {
12741 				/* No send window.. we must enter persist */
12742 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12743 			}
12744 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12745 			BBR_STAT_INC(bbr_app_limited);
12746 			app_limited = BBR_JR_APP_LIMITED;
12747 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12748 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12749 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12750 			BBR_STAT_INC(bbr_cwnd_limited);
12751  			app_limited = BBR_JR_CWND_LIMITED;
12752 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12753 									bbr->r_ctl.rc_lost_bytes)));
12754 			bbr->rc_cwnd_limited = 1;
12755 		} else {
12756 			BBR_STAT_INC(bbr_app_limited);
12757 			app_limited = BBR_JR_APP_LIMITED;
12758 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12759 		}
12760 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12761 		bbr->r_agg_early_set = 0;
12762 		bbr->r_ctl.rc_agg_early = 0;
12763 		bbr->r_ctl.rc_last_delay_val = 0;
12764 	} else if (bbr->rc_use_google == 0)
12765 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12766 	/* Are we app limited? */
12767 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12768 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12769 		/**
12770 		 * We are application limited.
12771 		 */
12772 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12773 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12774 	}
12775 	if (tot_len == 0)
12776 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12777 	/* Dont update the time if we did not send */
12778 	bbr->r_ctl.rc_last_delay_val = 0;
12779 	bbr->rc_output_starts_timer = 1;
12780 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12781 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12782 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12783 		/* Make sure snd_nxt is drug up */
12784 		tp->snd_nxt = tp->snd_max;
12785 	}
12786 	return (error);
12787 
12788 send:
12789 	if (doing_tlp == 0) {
12790 		/*
12791 		 * Data not a TLP, and its not the rxt firing. If it is the
12792 		 * rxt firing, we want to leave the tlp_in_progress flag on
12793 		 * so we don't send another TLP. It has to be a rack timer
12794 		 * or normal send (response to acked data) to clear the tlp
12795 		 * in progress flag.
12796 		 */
12797 		bbr->rc_tlp_in_progress = 0;
12798 		bbr->rc_tlp_rtx_out = 0;
12799 	} else {
12800 		/*
12801 		 * Its a TLP.
12802 		 */
12803 		bbr->rc_tlp_in_progress = 1;
12804 	}
12805 	bbr_timer_cancel(bbr, __LINE__, cts);
12806 	if (rsm == NULL) {
12807 		if (sbused(sb) > 0) {
12808 			/*
12809 			 * This is sub-optimal. We only send a stand alone
12810 			 * FIN on its own segment.
12811 			 */
12812 			if (flags & TH_FIN) {
12813 				flags &= ~TH_FIN;
12814 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12815 					/* Lets not send this */
12816 					slot = 0;
12817 					goto just_return;
12818 				}
12819 			}
12820 		}
12821 	} else {
12822 		/*
12823 		 * We do *not* send a FIN on a retransmit if it has data.
12824 		 * The if clause here where len > 1 should never come true.
12825 		 */
12826 		if ((len > 0) &&
12827 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12828 		    (flags & TH_FIN))) {
12829 			flags &= ~TH_FIN;
12830 			len--;
12831 		}
12832 	}
12833 	SOCKBUF_LOCK_ASSERT(sb);
12834 	if (len > 0) {
12835 		if ((tp->snd_una == tp->snd_max) &&
12836 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12837 			/*
12838 			 * This qualifies as a RTT_PROBE session since we
12839 			 * drop the data outstanding to nothing and waited
12840 			 * more than bbr_rtt_probe_time.
12841 			 */
12842 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12843 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12844 		}
12845 		if (len >= maxseg)
12846 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12847 		else
12848 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12849 	}
12850 	/*
12851 	 * Before ESTABLISHED, force sending of initial options unless TCP
12852 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12853 	 * plus TCP options always fit in a single mbuf, leaving room for a
12854 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12855 	 * + optlen <= MCLBYTES
12856 	 */
12857 	optlen = 0;
12858 #ifdef INET6
12859 	if (isipv6)
12860 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12861 	else
12862 #endif
12863 		hdrlen = sizeof(struct tcpiphdr);
12864 
12865 	/*
12866 	 * Compute options for segment. We only have to care about SYN and
12867 	 * established connection segments.  Options for SYN-ACK segments
12868 	 * are handled in TCP syncache.
12869 	 */
12870 	to.to_flags = 0;
12871 	local_options = 0;
12872 	if ((tp->t_flags & TF_NOOPT) == 0) {
12873 		/* Maximum segment size. */
12874 		if (flags & TH_SYN) {
12875 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12876 			if (tp->t_port)
12877 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12878 			to.to_flags |= TOF_MSS;
12879 			/*
12880 			 * On SYN or SYN|ACK transmits on TFO connections,
12881 			 * only include the TFO option if it is not a
12882 			 * retransmit, as the presence of the TFO option may
12883 			 * have caused the original SYN or SYN|ACK to have
12884 			 * been dropped by a middlebox.
12885 			 */
12886 			if (IS_FASTOPEN(tp->t_flags) &&
12887 			    (tp->t_rxtshift == 0)) {
12888 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12889 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12890 					to.to_tfo_cookie =
12891 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12892 					to.to_flags |= TOF_FASTOPEN;
12893 					wanted_cookie = 1;
12894 				} else if (tp->t_state == TCPS_SYN_SENT) {
12895 					to.to_tfo_len =
12896 					    tp->t_tfo_client_cookie_len;
12897 					to.to_tfo_cookie =
12898 					    tp->t_tfo_cookie.client;
12899 					to.to_flags |= TOF_FASTOPEN;
12900 					wanted_cookie = 1;
12901 				}
12902 			}
12903 		}
12904 		/* Window scaling. */
12905 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12906 			to.to_wscale = tp->request_r_scale;
12907 			to.to_flags |= TOF_SCALE;
12908 		}
12909 		/* Timestamps. */
12910 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12911 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12912 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12913 			to.to_tsecr = tp->ts_recent;
12914 			to.to_flags |= TOF_TS;
12915 			local_options += TCPOLEN_TIMESTAMP + 2;
12916 		}
12917 		/* Set receive buffer autosizing timestamp. */
12918 		if (tp->rfbuf_ts == 0 &&
12919 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12920 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12921 		/* Selective ACK's. */
12922 		if (flags & TH_SYN)
12923 			to.to_flags |= TOF_SACKPERM;
12924 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12925 		    tp->rcv_numsacks > 0) {
12926 			to.to_flags |= TOF_SACK;
12927 			to.to_nsacks = tp->rcv_numsacks;
12928 			to.to_sacks = (u_char *)tp->sackblks;
12929 		}
12930 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
12931 		/* TCP-MD5 (RFC2385). */
12932 		if (tp->t_flags & TF_SIGNATURE)
12933 			to.to_flags |= TOF_SIGNATURE;
12934 #endif				/* TCP_SIGNATURE */
12935 
12936 		/* Processing the options. */
12937 		hdrlen += (optlen = tcp_addoptions(&to, opt));
12938 		/*
12939 		 * If we wanted a TFO option to be added, but it was unable
12940 		 * to fit, ensure no data is sent.
12941 		 */
12942 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
12943 		    !(to.to_flags & TOF_FASTOPEN))
12944 			len = 0;
12945 	}
12946 	if (tp->t_port) {
12947 		if (V_tcp_udp_tunneling_port == 0) {
12948 			/* The port was removed?? */
12949 			SOCKBUF_UNLOCK(&so->so_snd);
12950 			return (EHOSTUNREACH);
12951 		}
12952 		hdrlen += sizeof(struct udphdr);
12953 	}
12954 #ifdef INET6
12955 	if (isipv6)
12956 		ipoptlen = ip6_optlen(inp);
12957 	else
12958 #endif
12959 	if (inp->inp_options)
12960 		ipoptlen = inp->inp_options->m_len -
12961 		    offsetof(struct ipoption, ipopt_list);
12962 	else
12963 		ipoptlen = 0;
12964 	ipoptlen = 0;
12965 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12966 	ipoptlen += ipsec_optlen;
12967 #endif
12968 	if (bbr->rc_last_options != local_options) {
12969 		/*
12970 		 * Cache the options length this generally does not change
12971 		 * on a connection. We use this to calculate TSO.
12972 		 */
12973 		bbr->rc_last_options = local_options;
12974 	}
12975 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
12976 	p_maxseg = min(maxseg, pace_max_segs);
12977 	/*
12978 	 * Adjust data length if insertion of options will bump the packet
12979 	 * length beyond the t_maxseg length. Clear the FIN bit because we
12980 	 * cut off the tail of the segment.
12981 	 */
12982 	if (len > maxseg) {
12983 		if (len != 0 && (flags & TH_FIN)) {
12984 			flags &= ~TH_FIN;
12985 		}
12986 		if (tso) {
12987 			uint32_t moff;
12988 			int32_t max_len;
12989 
12990 			/* extract TSO information */
12991 			if_hw_tsomax = tp->t_tsomax;
12992 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
12993 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
12994 			KASSERT(ipoptlen == 0,
12995 			    ("%s: TSO can't do IP options", __func__));
12996 
12997 			/*
12998 			 * Check if we should limit by maximum payload
12999 			 * length:
13000 			 */
13001 			if (if_hw_tsomax != 0) {
13002 				/* compute maximum TSO length */
13003 				max_len = (if_hw_tsomax - hdrlen -
13004 				    max_linkhdr);
13005 				if (max_len <= 0) {
13006 					len = 0;
13007 				} else if (len > max_len) {
13008 					len = max_len;
13009 				}
13010 			}
13011 			/*
13012 			 * Prevent the last segment from being fractional
13013 			 * unless the send sockbuf can be emptied:
13014 			 */
13015 			if ((sb_offset + len) < sbavail(sb)) {
13016 				moff = len % (uint32_t)maxseg;
13017 				if (moff != 0) {
13018 					len -= moff;
13019 				}
13020 			}
13021 			/*
13022 			 * In case there are too many small fragments don't
13023 			 * use TSO:
13024 			 */
13025 			if (len <= maxseg) {
13026 				len = maxseg;
13027 				tso = 0;
13028 			}
13029 		} else {
13030 			/* Not doing TSO */
13031 			if (optlen + ipoptlen >= tp->t_maxseg) {
13032 				/*
13033 				 * Since we don't have enough space to put
13034 				 * the IP header chain and the TCP header in
13035 				 * one packet as required by RFC 7112, don't
13036 				 * send it. Also ensure that at least one
13037 				 * byte of the payload can be put into the
13038 				 * TCP segment.
13039 				 */
13040 				SOCKBUF_UNLOCK(&so->so_snd);
13041 				error = EMSGSIZE;
13042 				sack_rxmit = 0;
13043 				goto out;
13044 			}
13045 			len = maxseg;
13046 		}
13047 	} else {
13048 		/* Not doing TSO */
13049 		if_hw_tsomaxsegcount = 0;
13050 		tso = 0;
13051 	}
13052 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13053 	    ("%s: len > IP_MAXPACKET", __func__));
13054 #ifdef DIAGNOSTIC
13055 #ifdef INET6
13056 	if (max_linkhdr + hdrlen > MCLBYTES)
13057 #else
13058 	if (max_linkhdr + hdrlen > MHLEN)
13059 #endif
13060 		panic("tcphdr too big");
13061 #endif
13062 	/*
13063 	 * This KASSERT is here to catch edge cases at a well defined place.
13064 	 * Before, those had triggered (random) panic conditions further
13065 	 * down.
13066 	 */
13067 #ifdef BBR_INVARIANTS
13068 	if (sack_rxmit) {
13069 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13070 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13071 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13072 		}
13073 	}
13074 #endif
13075 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13076 	if ((len == 0) &&
13077 	    (flags & TH_FIN) &&
13078 	    (sbused(sb))) {
13079 		/*
13080 		 * We have outstanding data, don't send a fin by itself!.
13081 		 */
13082 		slot = 0;
13083 		goto just_return;
13084 	}
13085 	/*
13086 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13087 	 * and initialize the header from the template for sends on this
13088 	 * connection.
13089 	 */
13090 	if (len) {
13091 		uint32_t moff;
13092 
13093 		/*
13094 		 * We place a limit on sending with hptsi.
13095 		 */
13096 		if ((rsm == NULL) && len > pace_max_segs)
13097 			len = pace_max_segs;
13098 		if (len <= maxseg)
13099 			tso = 0;
13100 #ifdef INET6
13101 		if (MHLEN < hdrlen + max_linkhdr)
13102 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13103 		else
13104 #endif
13105 			m = m_gethdr(M_NOWAIT, MT_DATA);
13106 
13107 		if (m == NULL) {
13108 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13109 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13110 			SOCKBUF_UNLOCK(sb);
13111 			error = ENOBUFS;
13112 			sack_rxmit = 0;
13113 			goto out;
13114 		}
13115 		m->m_data += max_linkhdr;
13116 		m->m_len = hdrlen;
13117 		/*
13118 		 * Start the m_copy functions from the closest mbuf to the
13119 		 * sb_offset in the socket buffer chain.
13120 		 */
13121 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13122 #ifdef BBR_INVARIANTS
13123 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13124 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13125 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13126 				    doing_retran_from,
13127 				    picked_up_retran,
13128 				    doing_tlp);
13129 
13130 #endif
13131 			/*
13132 			 * In this messed up situation we have two choices,
13133 			 * a) pretend the send worked, and just start timers
13134 			 * and what not (not good since that may lead us
13135 			 * back here a lot). <or> b) Send the lowest segment
13136 			 * in the map. <or> c) Drop the connection. Lets do
13137 			 * <b> which if it continues to happen will lead to
13138 			 * <c> via timeouts.
13139 			 */
13140 			BBR_STAT_INC(bbr_offset_recovery);
13141 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13142 			sb_offset = 0;
13143 			if (rsm == NULL) {
13144 				sack_rxmit = 0;
13145 				len = sbavail(sb);
13146 			} else {
13147 				sack_rxmit = 1;
13148 				if (rsm->r_start != tp->snd_una) {
13149 					/*
13150 					 * Things are really messed up, <c>
13151 					 * is the only thing to do.
13152 					 */
13153 					BBR_STAT_INC(bbr_offset_drop);
13154 					SOCKBUF_UNLOCK(sb);
13155 					(void)m_free(m);
13156 					return (-EFAULT); /* tcp_drop() */
13157 				}
13158 				len = rsm->r_end - rsm->r_start;
13159 			}
13160 			if (len > sbavail(sb))
13161 				len = sbavail(sb);
13162 			if (len > maxseg)
13163 				len = maxseg;
13164 		}
13165 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13166 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13167 			m_copydata(mb, moff, (int)len,
13168 			    mtod(m, caddr_t)+hdrlen);
13169 			if (rsm == NULL)
13170 				sbsndptr_adv(sb, mb, len);
13171 			m->m_len += len;
13172 		} else {
13173 			struct sockbuf *msb;
13174 
13175 			if (rsm)
13176 				msb = NULL;
13177 			else
13178 				msb = sb;
13179 #ifdef BBR_INVARIANTS
13180 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13181 				if (rsm) {
13182 					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 ",
13183 					    tp, bbr, len, moff,
13184 					    sbavail(sb), rsm,
13185 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13186 					    doing_retran_from,
13187 					    picked_up_retran,
13188 					    doing_tlp, sack_rxmit);
13189 				} else {
13190 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13191 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13192 				}
13193 			}
13194 #endif
13195 			m->m_next = tcp_m_copym(
13196 				mb, moff, &len,
13197 				if_hw_tsomaxsegcount,
13198 				if_hw_tsomaxsegsize, msb,
13199 				((rsm == NULL) ? hw_tls : 0)
13200 #ifdef NETFLIX_COPY_ARGS
13201 				, &filled_all
13202 #endif
13203 				);
13204 			if (len <= maxseg) {
13205 				/*
13206 				 * Must have ran out of mbufs for the copy
13207 				 * shorten it to no longer need tso. Lets
13208 				 * not put on sendalot since we are low on
13209 				 * mbufs.
13210 				 */
13211 				tso = 0;
13212 			}
13213 			if (m->m_next == NULL) {
13214 				SOCKBUF_UNLOCK(sb);
13215 				(void)m_free(m);
13216 				error = ENOBUFS;
13217 				sack_rxmit = 0;
13218 				goto out;
13219 			}
13220 		}
13221 #ifdef BBR_INVARIANTS
13222 		if (tso && len < maxseg) {
13223 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13224 			    tp, len, maxseg);
13225 		}
13226 		if (tso && if_hw_tsomaxsegcount) {
13227 			int32_t seg_cnt = 0;
13228 			struct mbuf *foo;
13229 
13230 			foo = m;
13231 			while (foo) {
13232 				seg_cnt++;
13233 				foo = foo->m_next;
13234 			}
13235 			if (seg_cnt > if_hw_tsomaxsegcount) {
13236 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13237 			}
13238 		}
13239 #endif
13240 		/*
13241 		 * If we're sending everything we've got, set PUSH. (This
13242 		 * will keep happy those implementations which only give
13243 		 * data to the user when a buffer fills or a PUSH comes in.)
13244 		 */
13245 		if (sb_offset + len == sbused(sb) &&
13246 		    sbused(sb) &&
13247 		    !(flags & TH_SYN)) {
13248 			flags |= TH_PUSH;
13249 		}
13250 		SOCKBUF_UNLOCK(sb);
13251 	} else {
13252 		SOCKBUF_UNLOCK(sb);
13253 		if (tp->t_flags & TF_ACKNOW)
13254 			KMOD_TCPSTAT_INC(tcps_sndacks);
13255 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13256 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13257 		else
13258 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13259 
13260 		m = m_gethdr(M_NOWAIT, MT_DATA);
13261 		if (m == NULL) {
13262 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13263 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13264 			error = ENOBUFS;
13265 			/* Fudge the send time since we could not send */
13266 			sack_rxmit = 0;
13267 			goto out;
13268 		}
13269 #ifdef INET6
13270 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13271 		    MHLEN >= hdrlen) {
13272 			M_ALIGN(m, hdrlen);
13273 		} else
13274 #endif
13275 			m->m_data += max_linkhdr;
13276 		m->m_len = hdrlen;
13277 	}
13278 	SOCKBUF_UNLOCK_ASSERT(sb);
13279 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13280 #ifdef MAC
13281 	mac_inpcb_create_mbuf(inp, m);
13282 #endif
13283 #ifdef INET6
13284 	if (isipv6) {
13285 		ip6 = mtod(m, struct ip6_hdr *);
13286 		if (tp->t_port) {
13287 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13288 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13289 			udp->uh_dport = tp->t_port;
13290 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13291 			udp->uh_ulen = htons(ulen);
13292 			th = (struct tcphdr *)(udp + 1);
13293 		} else {
13294 			th = (struct tcphdr *)(ip6 + 1);
13295 		}
13296 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13297 	} else
13298 #endif				/* INET6 */
13299 	{
13300 		ip = mtod(m, struct ip *);
13301 #ifdef TCPDEBUG
13302 		ipov = (struct ipovly *)ip;
13303 #endif
13304 		if (tp->t_port) {
13305 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13306 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13307 			udp->uh_dport = tp->t_port;
13308 			ulen = hdrlen + len - sizeof(struct ip);
13309 			udp->uh_ulen = htons(ulen);
13310 			th = (struct tcphdr *)(udp + 1);
13311 		} else {
13312 			th = (struct tcphdr *)(ip + 1);
13313 		}
13314 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13315 	}
13316 	/*
13317 	 * If we are doing retransmissions, then snd_nxt will not reflect
13318 	 * the first unsent octet.  For ACK only packets, we do not want the
13319 	 * sequence number of the retransmitted packet, we want the sequence
13320 	 * number of the next unsent octet.  So, if there is no data (and no
13321 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13322 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13323 	 * one byte beyond the right edge of the window, so use snd_nxt in
13324 	 * that case, since we know we aren't doing a retransmission.
13325 	 * (retransmit and persist are mutually exclusive...)
13326 	 */
13327 	if (sack_rxmit == 0) {
13328 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13329 			/* New data (including new persists) */
13330 			th->th_seq = htonl(tp->snd_max);
13331 			bbr_seq = tp->snd_max;
13332 		} else if (flags & TH_SYN) {
13333 			/* Syn's always send from iss */
13334 			th->th_seq = htonl(tp->iss);
13335 			bbr_seq = tp->iss;
13336 		} else if (flags & TH_FIN) {
13337 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13338 				/*
13339 				 * If we sent the fin already its 1 minus
13340 				 * snd_max
13341 				 */
13342 				th->th_seq = (htonl(tp->snd_max - 1));
13343 				bbr_seq = (tp->snd_max - 1);
13344 			} else {
13345 				/* First time FIN use snd_max */
13346 				th->th_seq = htonl(tp->snd_max);
13347 				bbr_seq = tp->snd_max;
13348 			}
13349 		} else {
13350 			/*
13351 			 * len == 0 and not persist we use snd_max, sending
13352 			 * an ack unless we have sent the fin then its 1
13353 			 * minus.
13354 			 */
13355 			/*
13356 			 * XXXRRS Question if we are in persists and we have
13357 			 * nothing outstanding to send and we have not sent
13358 			 * a FIN, we will send an ACK. In such a case it
13359 			 * might be better to send (tp->snd_una - 1) which
13360 			 * would force the peer to ack.
13361 			 */
13362 			if (tp->t_flags & TF_SENTFIN) {
13363 				th->th_seq = htonl(tp->snd_max - 1);
13364 				bbr_seq = (tp->snd_max - 1);
13365 			} else {
13366 				th->th_seq = htonl(tp->snd_max);
13367 				bbr_seq = tp->snd_max;
13368 			}
13369 		}
13370 	} else {
13371 		/* All retransmits use the rsm to guide the send */
13372 		th->th_seq = htonl(rsm->r_start);
13373 		bbr_seq = rsm->r_start;
13374 	}
13375 	th->th_ack = htonl(tp->rcv_nxt);
13376 	if (optlen) {
13377 		bcopy(opt, th + 1, optlen);
13378 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13379 	}
13380 	tcp_set_flags(th, flags);
13381 	/*
13382 	 * Calculate receive window.  Don't shrink window, but avoid silly
13383 	 * window syndrome.
13384 	 */
13385 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13386 				  recwin < maxseg)))
13387 		recwin = 0;
13388 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13389 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13390 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13391 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13392 		recwin = TCP_MAXWIN << tp->rcv_scale;
13393 
13394 	/*
13395 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13396 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13397 	 * handled in syncache.
13398 	 */
13399 	if (flags & TH_SYN)
13400 		th->th_win = htons((u_short)
13401 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13402 	else {
13403 		/* Avoid shrinking window with window scaling. */
13404 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13405 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13406 	}
13407 	/*
13408 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13409 	 * window.  This may cause the remote transmitter to stall.  This
13410 	 * flag tells soreceive() to disable delayed acknowledgements when
13411 	 * draining the buffer.  This can occur if the receiver is
13412 	 * attempting to read more data than can be buffered prior to
13413 	 * transmitting on the connection.
13414 	 */
13415 	if (th->th_win == 0) {
13416 		tp->t_sndzerowin++;
13417 		tp->t_flags |= TF_RXWIN0SENT;
13418 	} else
13419 		tp->t_flags &= ~TF_RXWIN0SENT;
13420 	/*
13421 	 * We don't support urgent data, but drag along
13422 	 * the pointer in case of a stack switch.
13423 	 */
13424 	tp->snd_up = tp->snd_una;
13425 
13426 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13427 	if (to.to_flags & TOF_SIGNATURE) {
13428 		/*
13429 		 * Calculate MD5 signature and put it into the place
13430 		 * determined before. NOTE: since TCP options buffer doesn't
13431 		 * point into mbuf's data, calculate offset and use it.
13432 		 */
13433 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13434 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13435 			/*
13436 			 * Do not send segment if the calculation of MD5
13437 			 * digest has failed.
13438 			 */
13439 			goto out;
13440 		}
13441 	}
13442 #endif
13443 
13444 	/*
13445 	 * Put TCP length in extended header, and then checksum extended
13446 	 * header and data.
13447 	 */
13448 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13449 #ifdef INET6
13450 	if (isipv6) {
13451 		/*
13452 		 * ip6_plen is not need to be filled now, and will be filled
13453 		 * in ip6_output.
13454 		 */
13455 		if (tp->t_port) {
13456 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13457 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13458 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13459 			th->th_sum = htons(0);
13460 			UDPSTAT_INC(udps_opackets);
13461 		} else {
13462 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13463 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13464 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13465 			    optlen + len, IPPROTO_TCP, 0);
13466 		}
13467 	}
13468 #endif
13469 #if defined(INET6) && defined(INET)
13470 	else
13471 #endif
13472 #ifdef INET
13473 	{
13474 		if (tp->t_port) {
13475 			m->m_pkthdr.csum_flags = CSUM_UDP;
13476 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13477 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13478 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13479 			th->th_sum = htons(0);
13480 			UDPSTAT_INC(udps_opackets);
13481 		} else {
13482 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13483 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13484 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13485 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13486 			    IPPROTO_TCP + len + optlen));
13487 		}
13488 		/* IP version must be set here for ipv4/ipv6 checking later */
13489 		KASSERT(ip->ip_v == IPVERSION,
13490 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13491 	}
13492 #endif
13493 
13494 	/*
13495 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13496 	 * header checksum is always provided. XXX: Fixme: This is currently
13497 	 * not the case for IPv6.
13498 	 */
13499 	if (tso) {
13500 		KASSERT(len > maxseg,
13501 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13502 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13503 		csum_flags |= CSUM_TSO;
13504 		m->m_pkthdr.tso_segsz = maxseg;
13505 	}
13506 	KASSERT(len + hdrlen == m_length(m, NULL),
13507 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13508 	    __func__, len, hdrlen, m_length(m, NULL)));
13509 
13510 #ifdef TCP_HHOOK
13511 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13512 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13513 #endif
13514 #ifdef TCPDEBUG
13515 	/*
13516 	 * Trace.
13517 	 */
13518 	if (so->so_options & SO_DEBUG) {
13519 		u_short save = 0;
13520 
13521 #ifdef INET6
13522 		if (!isipv6)
13523 #endif
13524 		{
13525 			save = ipov->ih_len;
13526 			ipov->ih_len = htons(m->m_pkthdr.len	/* - hdrlen +
13527 			      * (th->th_off << 2) */ );
13528 		}
13529 		tcp_trace(TA_OUTPUT, tp->t_state, tp, mtod(m, void *), th, 0);
13530 #ifdef INET6
13531 		if (!isipv6)
13532 #endif
13533 			ipov->ih_len = save;
13534 	}
13535 #endif				/* TCPDEBUG */
13536 
13537 	/* Log to the black box */
13538 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
13539 		union tcp_log_stackspecific log;
13540 
13541 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13542 		/* Record info on type of transmission */
13543 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13544 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13545 		log.u_bbr.flex3 = maxseg;
13546 		log.u_bbr.flex4 = delay_calc;
13547 		/* Encode filled_all into the upper flex5 bit */
13548 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13549 		log.u_bbr.flex5 <<= 1;
13550 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13551 		log.u_bbr.flex5 <<= 29;
13552 		if (filled_all)
13553 			log.u_bbr.flex5 |= 0x80000000;
13554 		log.u_bbr.flex5 |= tp->t_maxseg;
13555 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13556 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13557 		/* lets poke in the low and the high here for debugging */
13558 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13559 		if (rsm || sack_rxmit) {
13560 			if (doing_tlp)
13561 				log.u_bbr.flex8 = 2;
13562 			else
13563 				log.u_bbr.flex8 = 1;
13564 		} else {
13565 			log.u_bbr.flex8 = 0;
13566 		}
13567 		lgb = tcp_log_event_(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13568 		    len, &log, false, NULL, NULL, 0, tv);
13569 	} else {
13570 		lgb = NULL;
13571 	}
13572 	/*
13573 	 * Fill in IP length and desired time to live and send to IP level.
13574 	 * There should be a better way to handle ttl and tos; we could keep
13575 	 * them in the template, but need a way to checksum without them.
13576 	 */
13577 	/*
13578 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13579 	 * because in6_cksum() need it.
13580 	 */
13581 #ifdef INET6
13582 	if (isipv6) {
13583 		/*
13584 		 * we separately set hoplimit for every segment, since the
13585 		 * user might want to change the value via setsockopt. Also,
13586 		 * desired default hop limit might be changed via Neighbor
13587 		 * Discovery.
13588 		 */
13589 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13590 
13591 		/*
13592 		 * Set the packet size here for the benefit of DTrace
13593 		 * probes. ip6_output() will set it properly; it's supposed
13594 		 * to include the option header lengths as well.
13595 		 */
13596 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13597 
13598 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13599 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13600 		else
13601 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13602 
13603 		if (tp->t_state == TCPS_SYN_SENT)
13604 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13605 
13606 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13607 		/* TODO: IPv6 IP6TOS_ECT bit on */
13608 		error = ip6_output(m, inp->in6p_outputopts,
13609 		    &inp->inp_route6,
13610 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13611 		    NULL, NULL, inp);
13612 
13613 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13614 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13615 	}
13616 #endif				/* INET6 */
13617 #if defined(INET) && defined(INET6)
13618 	else
13619 #endif
13620 #ifdef INET
13621 	{
13622 		ip->ip_len = htons(m->m_pkthdr.len);
13623 #ifdef INET6
13624 		if (isipv6)
13625 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13626 #endif				/* INET6 */
13627 		/*
13628 		 * If we do path MTU discovery, then we set DF on every
13629 		 * packet. This might not be the best thing to do according
13630 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13631 		 * the problem so it affects only the first tcp connection
13632 		 * with a host.
13633 		 *
13634 		 * NB: Don't set DF on small MTU/MSS to have a safe
13635 		 * fallback.
13636 		 */
13637 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13638 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13639 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13640 				ip->ip_off |= htons(IP_DF);
13641 			}
13642 		} else {
13643 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13644 		}
13645 
13646 		if (tp->t_state == TCPS_SYN_SENT)
13647 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13648 
13649 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13650 
13651 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13652 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13653 		    inp);
13654 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13655 			mtu = inp->inp_route.ro_nh->nh_mtu;
13656 	}
13657 #endif				/* INET */
13658 out:
13659 
13660 	if (lgb) {
13661 		lgb->tlb_errno = error;
13662 		lgb = NULL;
13663 	}
13664 	/*
13665 	 * In transmit state, time the transmission and arrange for the
13666 	 * retransmit.  In persist state, just set snd_max.
13667 	 */
13668 	if (error == 0) {
13669 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13670 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13671 		    (tp->t_flags & TF_SACK_PERMIT) &&
13672 		    tp->rcv_numsacks > 0)
13673 			tcp_clean_dsack_blocks(tp);
13674 		/* We sent an ack clear the bbr_segs_rcvd count */
13675 		bbr->output_error_seen = 0;
13676 		bbr->oerror_cnt = 0;
13677 		bbr->bbr_segs_rcvd = 0;
13678 		if (len == 0)
13679 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13680 		/* Do accounting for new sends */
13681 		if ((len > 0) && (rsm == NULL)) {
13682 			int idx;
13683 			if (tp->snd_una == tp->snd_max) {
13684 				/*
13685 				 * Special case to match google, when
13686 				 * nothing is in flight the delivered
13687 				 * time does get updated to the current
13688 				 * time (see tcp_rate_bsd.c).
13689 				 */
13690 				bbr->r_ctl.rc_del_time = cts;
13691 			}
13692 			if (len >= maxseg) {
13693 				idx = (len / maxseg) + 3;
13694 				if (idx >= TCP_MSS_ACCT_ATIMER)
13695 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13696 				else
13697 					counter_u64_add(bbr_out_size[idx], 1);
13698 			} else {
13699 				/* smaller than a MSS */
13700 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13701 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13702 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13703 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13704 			}
13705 		}
13706 	}
13707 	abandon = 0;
13708 	/*
13709 	 * We must do the send accounting before we log the output,
13710 	 * otherwise the state of the rsm could change and we account to the
13711 	 * wrong bucket.
13712 	 */
13713 	if (len > 0) {
13714 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13715 		if (error == 0) {
13716 			if (tp->snd_una == tp->snd_max)
13717 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13718 		}
13719 	}
13720 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13721 	    cts, mb, &abandon, rsm, 0, sb);
13722 	if (abandon) {
13723 		/*
13724 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13725 		 * sent we should hit this condition.
13726 		 */
13727 		return (0);
13728 	}
13729 	if (bbr->rc_in_persist == 0) {
13730 		/*
13731 		 * Advance snd_nxt over sequence space of this segment.
13732 		 */
13733 		if (error)
13734 			/* We don't log or do anything with errors */
13735 			goto skip_upd;
13736 
13737 		if (tp->snd_una == tp->snd_max &&
13738 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13739 			/*
13740 			 * Update the time we just added data since none was
13741 			 * outstanding.
13742 			 */
13743 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13744 			bbr->rc_tp->t_acktime  = ticks;
13745 		}
13746 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13747 			if (flags & TH_SYN) {
13748 				/*
13749 				 * Smack the snd_max to iss + 1
13750 				 * if its a FO we will add len below.
13751 				 */
13752 				tp->snd_max = tp->iss + 1;
13753 			}
13754 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13755 				tp->snd_max++;
13756 				tp->t_flags |= TF_SENTFIN;
13757 			}
13758 		}
13759 		if (sack_rxmit == 0)
13760 			tp->snd_max += len;
13761 skip_upd:
13762 		if ((error == 0) && len)
13763 			tot_len += len;
13764 	} else {
13765 		/* Persists case */
13766 		int32_t xlen = len;
13767 
13768 		if (error)
13769 			goto nomore;
13770 
13771 		if (flags & TH_SYN)
13772 			++xlen;
13773 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13774 			++xlen;
13775 			tp->t_flags |= TF_SENTFIN;
13776 		}
13777 		if (xlen && (tp->snd_una == tp->snd_max)) {
13778 			/*
13779 			 * Update the time we just added data since none was
13780 			 * outstanding.
13781 			 */
13782 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13783 			bbr->rc_tp->t_acktime = ticks;
13784 		}
13785 		if (sack_rxmit == 0)
13786 			tp->snd_max += xlen;
13787 		tot_len += (len + optlen + ipoptlen);
13788 	}
13789 nomore:
13790 	if (error) {
13791 		/*
13792 		 * Failures do not advance the seq counter above. For the
13793 		 * case of ENOBUFS we will fall out and become ack-clocked.
13794 		 * capping the cwnd at the current flight.
13795 		 * Everything else will just have to retransmit with the timer
13796 		 * (no pacer).
13797 		 */
13798 		SOCKBUF_UNLOCK_ASSERT(sb);
13799 		BBR_STAT_INC(bbr_saw_oerr);
13800 		/* Clear all delay/early tracks */
13801 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13802 		bbr->r_ctl.rc_agg_early = 0;
13803 		bbr->r_agg_early_set = 0;
13804 		bbr->output_error_seen = 1;
13805 		if (bbr->oerror_cnt < 0xf)
13806 			bbr->oerror_cnt++;
13807 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13808 			/* drop the session */
13809 			return (-ENETDOWN);
13810 		}
13811 		switch (error) {
13812 		case ENOBUFS:
13813 			/*
13814 			 * Make this guy have to get ack's to send
13815 			 * more but lets make sure we don't
13816 			 * slam him below a T-O (1MSS).
13817 			 */
13818 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13819 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13820 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13821 				if (tp->snd_cwnd < maxseg)
13822 					tp->snd_cwnd = maxseg;
13823 			}
13824 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13825 			BBR_STAT_INC(bbr_saw_enobuf);
13826 			if (bbr->bbr_hdrw_pacing)
13827 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13828 			else
13829 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13830 			/*
13831 			 * Here even in the enobuf's case we want to do our
13832 			 * state update. The reason being we may have been
13833 			 * called by the input function. If so we have had
13834 			 * things change.
13835 			 */
13836 			error = 0;
13837 			goto enobufs;
13838 		case EMSGSIZE:
13839 			/*
13840 			 * For some reason the interface we used initially
13841 			 * to send segments changed to another or lowered
13842 			 * its MTU. If TSO was active we either got an
13843 			 * interface without TSO capabilits or TSO was
13844 			 * turned off. If we obtained mtu from ip_output()
13845 			 * then update it and try again.
13846 			 */
13847 			/* Turn on tracing (or try to) */
13848 			{
13849 				int old_maxseg;
13850 
13851 				old_maxseg = tp->t_maxseg;
13852 				BBR_STAT_INC(bbr_saw_emsgsiz);
13853 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13854 				if (mtu != 0)
13855 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13856 				if (old_maxseg <= tp->t_maxseg) {
13857 					/* Huh it did not shrink? */
13858 					tp->t_maxseg = old_maxseg - 40;
13859 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13860 				}
13861 				/*
13862 				 * Nuke all other things that can interfere
13863 				 * with slot
13864 				 */
13865 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13866 					slot = bbr_get_pacing_delay(bbr,
13867 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13868 					    (tot_len + len), cts, 0);
13869 					if (slot < bbr_error_base_paceout)
13870 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13871 				} else
13872 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13873 				bbr->rc_output_starts_timer = 1;
13874 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13875 				    tot_len);
13876 				return (error);
13877 			}
13878 		case EPERM:
13879 			tp->t_softerror = error;
13880 			/* Fall through */
13881 		case EHOSTDOWN:
13882 		case EHOSTUNREACH:
13883 		case ENETDOWN:
13884 		case ENETUNREACH:
13885 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13886 				tp->t_softerror = error;
13887 			}
13888 			/* FALLTHROUGH */
13889 		default:
13890 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13891 			bbr->rc_output_starts_timer = 1;
13892 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13893 			return (error);
13894 		}
13895 #ifdef STATS
13896 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13897 		    len &&
13898 		    (rsm == NULL) &&
13899 	    (bbr->rc_in_persist == 0)) {
13900 		tp->gput_seq = bbr_seq;
13901 		tp->gput_ack = bbr_seq +
13902 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13903 		tp->gput_ts = cts;
13904 		tp->t_flags |= TF_GPUTINPROG;
13905 #endif
13906 	}
13907 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13908 	if ((bbr->bbr_hdw_pace_ena) &&
13909 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13910 	    (bbr->rc_past_init_win) &&
13911 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13912 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13913 	    (inp->inp_route.ro_nh &&
13914 	     inp->inp_route.ro_nh->nh_ifp)) {
13915 		/*
13916 		 * We are past the initial window and
13917 		 * have at least one measurement so we
13918 		 * could use hardware pacing if its available.
13919 		 * We have an interface and we have not attempted
13920 		 * to setup hardware pacing, lets try to now.
13921 		 */
13922 		uint64_t rate_wanted;
13923 		int err = 0;
13924 
13925 		rate_wanted = bbr_get_hardware_rate(bbr);
13926 		bbr->bbr_attempt_hdwr_pace = 1;
13927 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13928 						      inp->inp_route.ro_nh->nh_ifp,
13929 						      rate_wanted,
13930 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
13931 						      &err, NULL);
13932 		if (bbr->r_ctl.crte) {
13933 			bbr_type_log_hdwr_pacing(bbr,
13934 						 bbr->r_ctl.crte->ptbl->rs_ifp,
13935 						 rate_wanted,
13936 						 bbr->r_ctl.crte->rate,
13937 						 __LINE__, cts, err);
13938 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
13939 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
13940 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
13941 			bbr->bbr_hdrw_pacing = 1;
13942 			/* Now what is our gain status? */
13943 			if (bbr->r_ctl.crte->rate < rate_wanted) {
13944 				/* We have a problem */
13945 				bbr_setup_less_of_rate(bbr, cts,
13946 						       bbr->r_ctl.crte->rate, rate_wanted);
13947 			} else {
13948 				/* We are good */
13949 				bbr->gain_is_limited = 0;
13950 				bbr->skip_gain = 0;
13951 			}
13952 			tcp_bbr_tso_size_check(bbr, cts);
13953 		} else {
13954 			bbr_type_log_hdwr_pacing(bbr,
13955 						 inp->inp_route.ro_nh->nh_ifp,
13956 						 rate_wanted,
13957 						 0,
13958 						 __LINE__, cts, err);
13959 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
13960 		}
13961 	}
13962 	if (bbr->bbr_hdrw_pacing) {
13963 		/*
13964 		 * Worry about cases where the route
13965 		 * changes or something happened that we
13966 		 * lost our hardware pacing possibly during
13967 		 * the last ip_output call.
13968 		 */
13969 		if (inp->inp_snd_tag == NULL) {
13970 			/* A change during ip output disabled hw pacing? */
13971 			bbr->bbr_hdrw_pacing = 0;
13972 		} else if ((inp->inp_route.ro_nh == NULL) ||
13973 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
13974 			/*
13975 			 * We had an interface or route change,
13976 			 * detach from the current hdwr pacing
13977 			 * and setup to re-attempt next go
13978 			 * round.
13979 			 */
13980 			bbr->bbr_hdrw_pacing = 0;
13981 			bbr->bbr_attempt_hdwr_pace = 0;
13982 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
13983 			tcp_bbr_tso_size_check(bbr, cts);
13984 		}
13985 	}
13986 	/*
13987 	 * Data sent (as far as we can tell). If this advertises a larger
13988 	 * window than any other segment, then remember the size of the
13989 	 * advertised window. Any pending ACK has now been sent.
13990 	 */
13991 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
13992 		tp->rcv_adv = tp->rcv_nxt + recwin;
13993 
13994 	tp->last_ack_sent = tp->rcv_nxt;
13995 	if ((error == 0) &&
13996 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
13997 	    (doing_tlp == 0) &&
13998 	    (tso == 0) &&
13999 	    (len > 0) &&
14000 	    ((flags & TH_RST) == 0) &&
14001 	    ((flags & TH_SYN) == 0) &&
14002 	    (IN_RECOVERY(tp->t_flags) == 0) &&
14003 	    (bbr->rc_in_persist == 0) &&
14004 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
14005 		/*
14006 		 * For non-tso we need to goto again until we have sent out
14007 		 * enough data to match what we are hptsi out every hptsi
14008 		 * interval.
14009 		 */
14010 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14011 			/* Make sure snd_nxt is drug up */
14012 			tp->snd_nxt = tp->snd_max;
14013 		}
14014 		if (rsm != NULL) {
14015 			rsm = NULL;
14016 			goto skip_again;
14017 		}
14018 		rsm = NULL;
14019 		sack_rxmit = 0;
14020 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14021 		goto again;
14022 	}
14023 skip_again:
14024 	if ((error == 0) && (flags & TH_FIN))
14025 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
14026 	if ((error == 0) && (flags & TH_RST))
14027 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
14028 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
14029 		/*
14030 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
14031 		 * what we have sent so far
14032 		 */
14033 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
14034 		if (bbr->rc_no_pacing)
14035 			slot = 0;
14036 	}
14037 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
14038 enobufs:
14039 	if (bbr->rc_use_google == 0)
14040 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
14041 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
14042 							bbr->r_ctl.rc_lost_bytes)));
14043 	bbr->rc_output_starts_timer = 1;
14044 	if (bbr->bbr_use_rack_cheat &&
14045 	    (more_to_rxt ||
14046 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
14047 		/* Rack cheats and shotguns out all rxt's 1ms apart */
14048 		if (slot > 1000)
14049 			slot = 1000;
14050 	}
14051 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
14052 		/*
14053 		 * We don't change the tso size until some number of sends
14054 		 * to give the hardware commands time to get down
14055 		 * to the interface.
14056 		 */
14057 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14058 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14059 			bbr->hw_pacing_set = 1;
14060 			tcp_bbr_tso_size_check(bbr, cts);
14061 		}
14062 	}
14063 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14064 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14065 		/* Make sure snd_nxt is drug up */
14066 		tp->snd_nxt = tp->snd_max;
14067 	}
14068 	return (error);
14069 
14070 }
14071 
14072 /*
14073  * See bbr_output_wtime() for return values.
14074  */
14075 static int
14076 bbr_output(struct tcpcb *tp)
14077 {
14078 	int32_t ret;
14079 	struct timeval tv;
14080 
14081 	NET_EPOCH_ASSERT();
14082 
14083 	INP_WLOCK_ASSERT(tptoinpcb(tp));
14084 	(void)tcp_get_usecs(&tv);
14085 	ret = bbr_output_wtime(tp, &tv);
14086 	return (ret);
14087 }
14088 
14089 static void
14090 bbr_mtu_chg(struct tcpcb *tp)
14091 {
14092 	struct tcp_bbr *bbr;
14093 	struct bbr_sendmap *rsm, *frsm = NULL;
14094 	uint32_t maxseg;
14095 
14096 	/*
14097 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14098 	 * over the current size as SACK_PASS so a retransmit will occur.
14099 	 */
14100 
14101 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14102 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14103 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14104 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14105 		/* Don't mess with ones acked (by sack?) */
14106 		if (rsm->r_flags & BBR_ACKED)
14107 			continue;
14108 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14109 			/*
14110 			 * We mark sack-passed on all the previous large
14111 			 * sends we did. This will force them to retransmit.
14112 			 */
14113 			rsm->r_flags |= BBR_SACK_PASSED;
14114 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14115 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14116 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14117 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14118 				rsm->r_flags |= BBR_MARKED_LOST;
14119 			}
14120 			if (frsm == NULL)
14121 				frsm = rsm;
14122 		}
14123 	}
14124 	if (frsm) {
14125 		bbr->r_ctl.rc_resend = frsm;
14126 	}
14127 }
14128 
14129 static int
14130 bbr_pru_options(struct tcpcb *tp, int flags)
14131 {
14132 	if (flags & PRUS_OOB)
14133 		return (EOPNOTSUPP);
14134 	return (0);
14135 }
14136 
14137 struct tcp_function_block __tcp_bbr = {
14138 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14139 	.tfb_tcp_output = bbr_output,
14140 	.tfb_do_queued_segments = ctf_do_queued_segments,
14141 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14142 	.tfb_tcp_do_segment = bbr_do_segment,
14143 	.tfb_tcp_ctloutput = bbr_ctloutput,
14144 	.tfb_tcp_fb_init = bbr_init,
14145 	.tfb_tcp_fb_fini = bbr_fini,
14146 	.tfb_tcp_timer_stop_all = bbr_stopall,
14147 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14148 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14149 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14150 	.tfb_pru_options = bbr_pru_options,
14151 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14152 };
14153 
14154 /*
14155  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14156  * socket option arguments.  When it re-acquires the lock after the copy, it
14157  * has to revalidate that the connection is still valid for the socket
14158  * option.
14159  */
14160 static int
14161 bbr_set_sockopt(struct inpcb *inp, struct sockopt *sopt)
14162 {
14163 	struct epoch_tracker et;
14164 	struct tcpcb *tp;
14165 	struct tcp_bbr *bbr;
14166 	int32_t error = 0, optval;
14167 
14168 	switch (sopt->sopt_level) {
14169 	case IPPROTO_IPV6:
14170 	case IPPROTO_IP:
14171 		return (tcp_default_ctloutput(inp, sopt));
14172 	}
14173 
14174 	switch (sopt->sopt_name) {
14175 	case TCP_RACK_PACE_MAX_SEG:
14176 	case TCP_RACK_MIN_TO:
14177 	case TCP_RACK_REORD_THRESH:
14178 	case TCP_RACK_REORD_FADE:
14179 	case TCP_RACK_TLP_THRESH:
14180 	case TCP_RACK_PKT_DELAY:
14181 	case TCP_BBR_ALGORITHM:
14182 	case TCP_BBR_TSLIMITS:
14183 	case TCP_BBR_IWINTSO:
14184 	case TCP_BBR_RECFORCE:
14185 	case TCP_BBR_STARTUP_PG:
14186 	case TCP_BBR_DRAIN_PG:
14187 	case TCP_BBR_RWND_IS_APP:
14188 	case TCP_BBR_PROBE_RTT_INT:
14189 	case TCP_BBR_PROBE_RTT_GAIN:
14190 	case TCP_BBR_PROBE_RTT_LEN:
14191 	case TCP_BBR_STARTUP_LOSS_EXIT:
14192 	case TCP_BBR_USEDEL_RATE:
14193 	case TCP_BBR_MIN_RTO:
14194 	case TCP_BBR_MAX_RTO:
14195 	case TCP_BBR_PACE_PER_SEC:
14196 	case TCP_DELACK:
14197 	case TCP_BBR_PACE_DEL_TAR:
14198 	case TCP_BBR_SEND_IWND_IN_TSO:
14199 	case TCP_BBR_EXTRA_STATE:
14200 	case TCP_BBR_UTTER_MAX_TSO:
14201 	case TCP_BBR_MIN_TOPACEOUT:
14202 	case TCP_BBR_FLOOR_MIN_TSO:
14203 	case TCP_BBR_TSTMP_RAISES:
14204 	case TCP_BBR_POLICER_DETECT:
14205 	case TCP_BBR_USE_RACK_CHEAT:
14206 	case TCP_DATA_AFTER_CLOSE:
14207 	case TCP_BBR_HDWR_PACE:
14208 	case TCP_BBR_PACE_SEG_MAX:
14209 	case TCP_BBR_PACE_SEG_MIN:
14210 	case TCP_BBR_PACE_CROSS:
14211 	case TCP_BBR_PACE_OH:
14212 #ifdef NETFLIX_PEAKRATE
14213 	case TCP_MAXPEAKRATE:
14214 #endif
14215 	case TCP_BBR_TMR_PACE_OH:
14216 	case TCP_BBR_RACK_RTT_USE:
14217 	case TCP_BBR_RETRAN_WTSO:
14218 		break;
14219 	default:
14220 		return (tcp_default_ctloutput(inp, sopt));
14221 		break;
14222 	}
14223 	INP_WUNLOCK(inp);
14224 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14225 	if (error)
14226 		return (error);
14227 	INP_WLOCK(inp);
14228 	if (inp->inp_flags & INP_DROPPED) {
14229 		INP_WUNLOCK(inp);
14230 		return (ECONNRESET);
14231 	}
14232 	tp = intotcpcb(inp);
14233 	if (tp->t_fb != &__tcp_bbr) {
14234 		INP_WUNLOCK(inp);
14235 		return (ENOPROTOOPT);
14236 	}
14237 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14238 	switch (sopt->sopt_name) {
14239 	case TCP_BBR_PACE_PER_SEC:
14240 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14241 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14242 		break;
14243 	case TCP_BBR_PACE_DEL_TAR:
14244 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14245 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14246 		break;
14247 	case TCP_BBR_PACE_SEG_MAX:
14248 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14249 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14250 		break;
14251 	case TCP_BBR_PACE_SEG_MIN:
14252 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14253 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14254 		break;
14255 	case TCP_BBR_PACE_CROSS:
14256 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14257 		bbr->r_ctl.bbr_cross_over = optval;
14258 		break;
14259 	case TCP_BBR_ALGORITHM:
14260 		BBR_OPTS_INC(tcp_bbr_algorithm);
14261 		if (optval && (bbr->rc_use_google == 0)) {
14262 			/* Turn on the google mode */
14263 			bbr_google_mode_on(bbr);
14264 			if ((optval > 3) && (optval < 500)) {
14265 				/*
14266 				 * Must be at least greater than .3%
14267 				 * and must be less than 50.0%.
14268 				 */
14269 				bbr->r_ctl.bbr_google_discount = optval;
14270 			}
14271 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14272 			/* Turn off the google mode */
14273 			bbr_google_mode_off(bbr);
14274 		}
14275 		break;
14276 	case TCP_BBR_TSLIMITS:
14277 		BBR_OPTS_INC(tcp_bbr_tslimits);
14278 		if (optval == 1)
14279 			bbr->rc_use_ts_limit = 1;
14280 		else if (optval == 0)
14281 			bbr->rc_use_ts_limit = 0;
14282 		else
14283 			error = EINVAL;
14284 		break;
14285 
14286 	case TCP_BBR_IWINTSO:
14287 		BBR_OPTS_INC(tcp_bbr_iwintso);
14288 		if ((optval >= 0) && (optval < 128)) {
14289 			uint32_t twin;
14290 
14291 			bbr->rc_init_win = optval;
14292 			twin = bbr_initial_cwnd(bbr, tp);
14293 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14294 				tp->snd_cwnd = twin;
14295 			else
14296 				error = EBUSY;
14297 		} else
14298 			error = EINVAL;
14299 		break;
14300 	case TCP_BBR_STARTUP_PG:
14301 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14302 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14303 			bbr->r_ctl.rc_startup_pg = optval;
14304 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14305 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14306 			}
14307 		} else
14308 			error = EINVAL;
14309 		break;
14310 	case TCP_BBR_DRAIN_PG:
14311 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14312 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14313 			bbr->r_ctl.rc_drain_pg = optval;
14314 		else
14315 			error = EINVAL;
14316 		break;
14317 	case TCP_BBR_PROBE_RTT_LEN:
14318 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14319 		if (optval <= 1)
14320 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14321 		else
14322 			error = EINVAL;
14323 		break;
14324 	case TCP_BBR_PROBE_RTT_GAIN:
14325 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14326 		if (optval <= BBR_UNIT)
14327 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14328 		else
14329 			error = EINVAL;
14330 		break;
14331 	case TCP_BBR_PROBE_RTT_INT:
14332 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14333 		if (optval > 1000)
14334 			bbr->r_ctl.rc_probertt_int = optval;
14335 		else
14336 			error = EINVAL;
14337 		break;
14338 	case TCP_BBR_MIN_TOPACEOUT:
14339 		BBR_OPTS_INC(tcp_bbr_topaceout);
14340 		if (optval == 0) {
14341 			bbr->no_pacing_until = 0;
14342 			bbr->rc_no_pacing = 0;
14343 		} else if (optval <= 0x00ff) {
14344 			bbr->no_pacing_until = optval;
14345 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14346 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14347 				/* Turn on no pacing */
14348 				bbr->rc_no_pacing = 1;
14349 			}
14350 		} else
14351 			error = EINVAL;
14352 		break;
14353 	case TCP_BBR_STARTUP_LOSS_EXIT:
14354 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14355 		bbr->rc_loss_exit = optval;
14356 		break;
14357 	case TCP_BBR_USEDEL_RATE:
14358 		error = EINVAL;
14359 		break;
14360 	case TCP_BBR_MIN_RTO:
14361 		BBR_OPTS_INC(tcp_bbr_min_rto);
14362 		bbr->r_ctl.rc_min_rto_ms = optval;
14363 		break;
14364 	case TCP_BBR_MAX_RTO:
14365 		BBR_OPTS_INC(tcp_bbr_max_rto);
14366 		bbr->rc_max_rto_sec = optval;
14367 		break;
14368 	case TCP_RACK_MIN_TO:
14369 		/* Minimum time between rack t-o's in ms */
14370 		BBR_OPTS_INC(tcp_rack_min_to);
14371 		bbr->r_ctl.rc_min_to = optval;
14372 		break;
14373 	case TCP_RACK_REORD_THRESH:
14374 		/* RACK reorder threshold (shift amount) */
14375 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14376 		if ((optval > 0) && (optval < 31))
14377 			bbr->r_ctl.rc_reorder_shift = optval;
14378 		else
14379 			error = EINVAL;
14380 		break;
14381 	case TCP_RACK_REORD_FADE:
14382 		/* Does reordering fade after ms time */
14383 		BBR_OPTS_INC(tcp_rack_reord_fade);
14384 		bbr->r_ctl.rc_reorder_fade = optval;
14385 		break;
14386 	case TCP_RACK_TLP_THRESH:
14387 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14388 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14389 		if (optval)
14390 			bbr->rc_tlp_threshold = optval;
14391 		else
14392 			error = EINVAL;
14393 		break;
14394 	case TCP_BBR_USE_RACK_CHEAT:
14395 		BBR_OPTS_INC(tcp_use_rackcheat);
14396 		if (bbr->rc_use_google) {
14397 			error = EINVAL;
14398 			break;
14399 		}
14400 		BBR_OPTS_INC(tcp_rack_cheat);
14401 		if (optval)
14402 			bbr->bbr_use_rack_cheat = 1;
14403 		else
14404 			bbr->bbr_use_rack_cheat = 0;
14405 		break;
14406 	case TCP_BBR_FLOOR_MIN_TSO:
14407 		BBR_OPTS_INC(tcp_utter_max_tso);
14408 		if ((optval >= 0) && (optval < 40))
14409 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14410 		else
14411 			error = EINVAL;
14412 		break;
14413 	case TCP_BBR_UTTER_MAX_TSO:
14414 		BBR_OPTS_INC(tcp_utter_max_tso);
14415 		if ((optval >= 0) && (optval < 0xffff))
14416 			bbr->r_ctl.bbr_utter_max = optval;
14417 		else
14418 			error = EINVAL;
14419 		break;
14420 
14421 	case TCP_BBR_EXTRA_STATE:
14422 		BBR_OPTS_INC(tcp_extra_state);
14423 		if (optval)
14424 			bbr->rc_use_idle_restart = 1;
14425 		else
14426 			bbr->rc_use_idle_restart = 0;
14427 		break;
14428 	case TCP_BBR_SEND_IWND_IN_TSO:
14429 		BBR_OPTS_INC(tcp_iwnd_tso);
14430 		if (optval) {
14431 			bbr->bbr_init_win_cheat = 1;
14432 			if (bbr->rc_past_init_win == 0) {
14433 				uint32_t cts;
14434 				cts = tcp_get_usecs(&bbr->rc_tv);
14435 				tcp_bbr_tso_size_check(bbr, cts);
14436 			}
14437 		} else
14438 			bbr->bbr_init_win_cheat = 0;
14439 		break;
14440 	case TCP_BBR_HDWR_PACE:
14441 		BBR_OPTS_INC(tcp_hdwr_pacing);
14442 		if (optval){
14443 			bbr->bbr_hdw_pace_ena = 1;
14444 			bbr->bbr_attempt_hdwr_pace = 0;
14445 		} else {
14446 			bbr->bbr_hdw_pace_ena = 0;
14447 #ifdef RATELIMIT
14448 			if (bbr->r_ctl.crte != NULL) {
14449 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14450 				bbr->r_ctl.crte = NULL;
14451 			}
14452 #endif
14453 		}
14454 		break;
14455 
14456 	case TCP_DELACK:
14457 		BBR_OPTS_INC(tcp_delack);
14458 		if (optval < 100) {
14459 			if (optval == 0) /* off */
14460 				tp->t_delayed_ack = 0;
14461 			else if (optval == 1) /* on which is 2 */
14462 				tp->t_delayed_ack = 2;
14463 			else /* higher than 2 and less than 100 */
14464 				tp->t_delayed_ack = optval;
14465 			if (tp->t_flags & TF_DELACK) {
14466 				tp->t_flags &= ~TF_DELACK;
14467 				tp->t_flags |= TF_ACKNOW;
14468 				NET_EPOCH_ENTER(et);
14469 				bbr_output(tp);
14470 				NET_EPOCH_EXIT(et);
14471 			}
14472 		} else
14473 			error = EINVAL;
14474 		break;
14475 	case TCP_RACK_PKT_DELAY:
14476 		/* RACK added ms i.e. rack-rtt + reord + N */
14477 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14478 		bbr->r_ctl.rc_pkt_delay = optval;
14479 		break;
14480 #ifdef NETFLIX_PEAKRATE
14481 	case TCP_MAXPEAKRATE:
14482 		BBR_OPTS_INC(tcp_maxpeak);
14483 		error = tcp_set_maxpeakrate(tp, optval);
14484 		if (!error)
14485 			tp->t_peakrate_thr = tp->t_maxpeakrate;
14486 		break;
14487 #endif
14488 	case TCP_BBR_RETRAN_WTSO:
14489 		BBR_OPTS_INC(tcp_retran_wtso);
14490 		if (optval)
14491 			bbr->rc_resends_use_tso = 1;
14492 		else
14493 			bbr->rc_resends_use_tso = 0;
14494 		break;
14495 	case TCP_DATA_AFTER_CLOSE:
14496 		BBR_OPTS_INC(tcp_data_ac);
14497 		if (optval)
14498 			bbr->rc_allow_data_af_clo = 1;
14499 		else
14500 			bbr->rc_allow_data_af_clo = 0;
14501 		break;
14502 	case TCP_BBR_POLICER_DETECT:
14503 		BBR_OPTS_INC(tcp_policer_det);
14504 		if (bbr->rc_use_google == 0)
14505 			error = EINVAL;
14506 		else if (optval)
14507 			bbr->r_use_policer = 1;
14508 		else
14509 			bbr->r_use_policer = 0;
14510 		break;
14511 
14512 	case TCP_BBR_TSTMP_RAISES:
14513 		BBR_OPTS_INC(tcp_ts_raises);
14514 		if (optval)
14515 			bbr->ts_can_raise = 1;
14516 		else
14517 			bbr->ts_can_raise = 0;
14518 		break;
14519 	case TCP_BBR_TMR_PACE_OH:
14520 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14521 		if (bbr->rc_use_google) {
14522 			error = EINVAL;
14523 		} else {
14524 			if (optval)
14525 				bbr->r_ctl.rc_incr_tmrs = 1;
14526 			else
14527 				bbr->r_ctl.rc_incr_tmrs = 0;
14528 		}
14529 		break;
14530 	case TCP_BBR_PACE_OH:
14531 		BBR_OPTS_INC(tcp_pacing_oh);
14532 		if (bbr->rc_use_google) {
14533 			error = EINVAL;
14534 		} else {
14535 			if (optval > (BBR_INCL_TCP_OH|
14536 				      BBR_INCL_IP_OH|
14537 				      BBR_INCL_ENET_OH)) {
14538 				error = EINVAL;
14539 				break;
14540 			}
14541 			if (optval & BBR_INCL_TCP_OH)
14542 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14543 			else
14544 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14545 			if (optval & BBR_INCL_IP_OH)
14546 				bbr->r_ctl.rc_inc_ip_oh = 1;
14547 			else
14548 				bbr->r_ctl.rc_inc_ip_oh = 0;
14549 			if (optval & BBR_INCL_ENET_OH)
14550 				bbr->r_ctl.rc_inc_enet_oh = 1;
14551 			else
14552 				bbr->r_ctl.rc_inc_enet_oh = 0;
14553 		}
14554 		break;
14555 	default:
14556 		return (tcp_default_ctloutput(inp, sopt));
14557 		break;
14558 	}
14559 #ifdef NETFLIX_STATS
14560 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14561 #endif
14562 	INP_WUNLOCK(inp);
14563 	return (error);
14564 }
14565 
14566 /*
14567  * return 0 on success, error-num on failure
14568  */
14569 static int
14570 bbr_get_sockopt(struct inpcb *inp, struct sockopt *sopt)
14571 {
14572 	struct tcpcb *tp;
14573 	struct tcp_bbr *bbr;
14574 	int32_t error, optval;
14575 
14576 	tp = intotcpcb(inp);
14577 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14578 	if (bbr == NULL) {
14579 		INP_WUNLOCK(inp);
14580 		return (EINVAL);
14581 	}
14582 	/*
14583 	 * Because all our options are either boolean or an int, we can just
14584 	 * pull everything into optval and then unlock and copy. If we ever
14585 	 * add a option that is not a int, then this will have quite an
14586 	 * impact to this routine.
14587 	 */
14588 	switch (sopt->sopt_name) {
14589 	case TCP_BBR_PACE_PER_SEC:
14590 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14591 		break;
14592 	case TCP_BBR_PACE_DEL_TAR:
14593 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14594 		break;
14595 	case TCP_BBR_PACE_SEG_MAX:
14596 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14597 		break;
14598 	case TCP_BBR_MIN_TOPACEOUT:
14599 		optval = bbr->no_pacing_until;
14600 		break;
14601 	case TCP_BBR_PACE_SEG_MIN:
14602 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14603 		break;
14604 	case TCP_BBR_PACE_CROSS:
14605 		optval = bbr->r_ctl.bbr_cross_over;
14606 		break;
14607 	case TCP_BBR_ALGORITHM:
14608 		optval = bbr->rc_use_google;
14609 		break;
14610 	case TCP_BBR_TSLIMITS:
14611 		optval = bbr->rc_use_ts_limit;
14612 		break;
14613 	case TCP_BBR_IWINTSO:
14614 		optval = bbr->rc_init_win;
14615 		break;
14616 	case TCP_BBR_STARTUP_PG:
14617 		optval = bbr->r_ctl.rc_startup_pg;
14618 		break;
14619 	case TCP_BBR_DRAIN_PG:
14620 		optval = bbr->r_ctl.rc_drain_pg;
14621 		break;
14622 	case TCP_BBR_PROBE_RTT_INT:
14623 		optval = bbr->r_ctl.rc_probertt_int;
14624 		break;
14625 	case TCP_BBR_PROBE_RTT_LEN:
14626 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14627 		break;
14628 	case TCP_BBR_PROBE_RTT_GAIN:
14629 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14630 		break;
14631 	case TCP_BBR_STARTUP_LOSS_EXIT:
14632 		optval = bbr->rc_loss_exit;
14633 		break;
14634 	case TCP_BBR_USEDEL_RATE:
14635 		error = EINVAL;
14636 		break;
14637 	case TCP_BBR_MIN_RTO:
14638 		optval = bbr->r_ctl.rc_min_rto_ms;
14639 		break;
14640 	case TCP_BBR_MAX_RTO:
14641 		optval = bbr->rc_max_rto_sec;
14642 		break;
14643 	case TCP_RACK_PACE_MAX_SEG:
14644 		/* Max segments in a pace */
14645 		optval = bbr->r_ctl.rc_pace_max_segs;
14646 		break;
14647 	case TCP_RACK_MIN_TO:
14648 		/* Minimum time between rack t-o's in ms */
14649 		optval = bbr->r_ctl.rc_min_to;
14650 		break;
14651 	case TCP_RACK_REORD_THRESH:
14652 		/* RACK reorder threshold (shift amount) */
14653 		optval = bbr->r_ctl.rc_reorder_shift;
14654 		break;
14655 	case TCP_RACK_REORD_FADE:
14656 		/* Does reordering fade after ms time */
14657 		optval = bbr->r_ctl.rc_reorder_fade;
14658 		break;
14659 	case TCP_BBR_USE_RACK_CHEAT:
14660 		/* Do we use the rack cheat for rxt */
14661 		optval = bbr->bbr_use_rack_cheat;
14662 		break;
14663 	case TCP_BBR_FLOOR_MIN_TSO:
14664 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14665 		break;
14666 	case TCP_BBR_UTTER_MAX_TSO:
14667 		optval = bbr->r_ctl.bbr_utter_max;
14668 		break;
14669 	case TCP_BBR_SEND_IWND_IN_TSO:
14670 		/* Do we send TSO size segments initially */
14671 		optval = bbr->bbr_init_win_cheat;
14672 		break;
14673 	case TCP_BBR_EXTRA_STATE:
14674 		optval = bbr->rc_use_idle_restart;
14675 		break;
14676 	case TCP_RACK_TLP_THRESH:
14677 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14678 		optval = bbr->rc_tlp_threshold;
14679 		break;
14680 	case TCP_RACK_PKT_DELAY:
14681 		/* RACK added ms i.e. rack-rtt + reord + N */
14682 		optval = bbr->r_ctl.rc_pkt_delay;
14683 		break;
14684 	case TCP_BBR_RETRAN_WTSO:
14685 		optval = bbr->rc_resends_use_tso;
14686 		break;
14687 	case TCP_DATA_AFTER_CLOSE:
14688 		optval = bbr->rc_allow_data_af_clo;
14689 		break;
14690 	case TCP_DELACK:
14691 		optval = tp->t_delayed_ack;
14692 		break;
14693 	case TCP_BBR_HDWR_PACE:
14694 		optval = bbr->bbr_hdw_pace_ena;
14695 		break;
14696 	case TCP_BBR_POLICER_DETECT:
14697 		optval = bbr->r_use_policer;
14698 		break;
14699 	case TCP_BBR_TSTMP_RAISES:
14700 		optval = bbr->ts_can_raise;
14701 		break;
14702 	case TCP_BBR_TMR_PACE_OH:
14703 		optval = bbr->r_ctl.rc_incr_tmrs;
14704 		break;
14705 	case TCP_BBR_PACE_OH:
14706 		optval = 0;
14707 		if (bbr->r_ctl.rc_inc_tcp_oh)
14708 			optval |= BBR_INCL_TCP_OH;
14709 		if (bbr->r_ctl.rc_inc_ip_oh)
14710 			optval |= BBR_INCL_IP_OH;
14711 		if (bbr->r_ctl.rc_inc_enet_oh)
14712 			optval |= BBR_INCL_ENET_OH;
14713 		break;
14714 	default:
14715 		return (tcp_default_ctloutput(inp, sopt));
14716 		break;
14717 	}
14718 	INP_WUNLOCK(inp);
14719 	error = sooptcopyout(sopt, &optval, sizeof optval);
14720 	return (error);
14721 }
14722 
14723 /*
14724  * return 0 on success, error-num on failure
14725  */
14726 static int
14727 bbr_ctloutput(struct inpcb *inp, struct sockopt *sopt)
14728 {
14729 	if (sopt->sopt_dir == SOPT_SET) {
14730 		return (bbr_set_sockopt(inp, sopt));
14731 	} else if (sopt->sopt_dir == SOPT_GET) {
14732 		return (bbr_get_sockopt(inp, sopt));
14733 	} else {
14734 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14735 	}
14736 }
14737 
14738 static const char *bbr_stack_names[] = {
14739 	__XSTRING(STACKNAME),
14740 #ifdef STACKALIAS
14741 	__XSTRING(STACKALIAS),
14742 #endif
14743 };
14744 
14745 static bool bbr_mod_inited = false;
14746 
14747 static int
14748 tcp_addbbr(module_t mod, int32_t type, void *data)
14749 {
14750 	int32_t err = 0;
14751 	int num_stacks;
14752 
14753 	switch (type) {
14754 	case MOD_LOAD:
14755 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14756 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14757 		    sizeof(struct bbr_sendmap),
14758 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14759 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14760 		    sizeof(struct tcp_bbr),
14761 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14762 		sysctl_ctx_init(&bbr_sysctl_ctx);
14763 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14764 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14765 		    OID_AUTO,
14766 #ifdef STACKALIAS
14767 		    __XSTRING(STACKALIAS),
14768 #else
14769 		    __XSTRING(STACKNAME),
14770 #endif
14771 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14772 		    "");
14773 		if (bbr_sysctl_root == NULL) {
14774 			printf("Failed to add sysctl node\n");
14775 			err = EFAULT;
14776 			goto free_uma;
14777 		}
14778 		bbr_init_sysctls();
14779 		num_stacks = nitems(bbr_stack_names);
14780 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14781 		    bbr_stack_names, &num_stacks);
14782 		if (err) {
14783 			printf("Failed to register %s stack name for "
14784 			    "%s module\n", bbr_stack_names[num_stacks],
14785 			    __XSTRING(MODNAME));
14786 			sysctl_ctx_free(&bbr_sysctl_ctx);
14787 	free_uma:
14788 			uma_zdestroy(bbr_zone);
14789 			uma_zdestroy(bbr_pcb_zone);
14790 			bbr_counter_destroy();
14791 			printf("Failed to register " __XSTRING(MODNAME)
14792 			    " module err:%d\n", err);
14793 			return (err);
14794 		}
14795 		tcp_lro_reg_mbufq();
14796 		bbr_mod_inited = true;
14797 		printf(__XSTRING(MODNAME) " is now available\n");
14798 		break;
14799 	case MOD_QUIESCE:
14800 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14801 		break;
14802 	case MOD_UNLOAD:
14803 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14804 		if (err == EBUSY)
14805 			break;
14806 		if (bbr_mod_inited) {
14807 			uma_zdestroy(bbr_zone);
14808 			uma_zdestroy(bbr_pcb_zone);
14809 			sysctl_ctx_free(&bbr_sysctl_ctx);
14810 			bbr_counter_destroy();
14811 			printf(__XSTRING(MODNAME)
14812 			    " is now no longer available\n");
14813 			bbr_mod_inited = false;
14814 		}
14815 		tcp_lro_dereg_mbufq();
14816 		err = 0;
14817 		break;
14818 	default:
14819 		return (EOPNOTSUPP);
14820 	}
14821 	return (err);
14822 }
14823 
14824 static moduledata_t tcp_bbr = {
14825 	.name = __XSTRING(MODNAME),
14826 	    .evhand = tcp_addbbr,
14827 	    .priv = 0
14828 };
14829 
14830 MODULE_VERSION(MODNAME, 1);
14831 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14832 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14833