xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision b7c0c8c18e0f12bc22e251fbcabad719b364a38a)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_ratelimit.h"
38 #include <sys/param.h>
39 #include <sys/arb.h>
40 #include <sys/module.h>
41 #include <sys/kernel.h>
42 #include <sys/libkern.h>
43 #ifdef TCP_HHOOK
44 #include <sys/hhook.h>
45 #endif
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/proc.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #ifdef STATS
54 #include <sys/qmath.h>
55 #include <sys/tree.h>
56 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
57 #endif
58 #include <sys/refcount.h>
59 #include <sys/queue.h>
60 #include <sys/eventhandler.h>
61 #include <sys/smp.h>
62 #include <sys/kthread.h>
63 #include <sys/lock.h>
64 #include <sys/mutex.h>
65 #include <sys/tim_filter.h>
66 #include <sys/time.h>
67 #include <sys/protosw.h>
68 #include <vm/uma.h>
69 #include <sys/kern_prefetch.h>
70 
71 #include <net/route.h>
72 #include <net/route/nhop.h>
73 #include <net/vnet.h>
74 
75 #define TCPSTATES		/* for logging */
76 
77 #include <netinet/in.h>
78 #include <netinet/in_kdtrace.h>
79 #include <netinet/in_pcb.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
82 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
83 #include <netinet/ip_var.h>
84 #include <netinet/ip6.h>
85 #include <netinet6/in6_pcb.h>
86 #include <netinet6/ip6_var.h>
87 #define	TCPOUTFLAGS
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/tcpip.h>
94 #include <netinet/tcp_hpts.h>
95 #include <netinet/cc/cc.h>
96 #include <netinet/tcp_log_buf.h>
97 #include <netinet/tcp_ratelimit.h>
98 #include <netinet/tcp_lro.h>
99 #ifdef TCP_OFFLOAD
100 #include <netinet/tcp_offload.h>
101 #endif
102 #ifdef INET6
103 #include <netinet6/tcp6_var.h>
104 #endif
105 #include <netinet/tcp_fastopen.h>
106 
107 #include <netipsec/ipsec_support.h>
108 #include <net/if.h>
109 #include <net/if_var.h>
110 #include <net/ethernet.h>
111 
112 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
113 #include <netipsec/ipsec.h>
114 #include <netipsec/ipsec6.h>
115 #endif				/* IPSEC */
116 
117 #include <netinet/udp.h>
118 #include <netinet/udp_var.h>
119 #include <machine/in_cksum.h>
120 
121 #ifdef MAC
122 #include <security/mac/mac_framework.h>
123 #endif
124 
125 #include "sack_filter.h"
126 #include "tcp_bbr.h"
127 #include "rack_bbr_common.h"
128 uma_zone_t bbr_zone;
129 uma_zone_t bbr_pcb_zone;
130 
131 struct sysctl_ctx_list bbr_sysctl_ctx;
132 struct sysctl_oid *bbr_sysctl_root;
133 
134 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
135 	(tv) = (value); \
136 	if ((u_long)(tv) < (u_long)(tvmin)) \
137 		(tv) = (tvmin); \
138 	if ((u_long)(tv) > (u_long)(tvmax)) \
139 		(tv) = (tvmax); \
140 } while(0)
141 
142 /*#define BBR_INVARIANT 1*/
143 
144 /*
145  * initial window
146  */
147 static uint32_t bbr_def_init_win = 10;
148 static int32_t bbr_persist_min = 250000;	/* 250ms */
149 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
150 static int32_t bbr_cwnd_may_shrink = 0;
151 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
152 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
153 static int32_t bbr_hardware_pacing_limit = 8000;
154 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
155 static int32_t bbr_no_retran = 0;
156 
157 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
158 static int32_t bbr_max_net_error_cnt = 10;
159 /* Should the following be dynamic too -- loss wise */
160 static int32_t bbr_rtt_gain_thresh = 0;
161 /* Measurement controls */
162 static int32_t bbr_use_google_algo = 1;
163 static int32_t bbr_ts_limiting = 1;
164 static int32_t bbr_ts_can_raise = 0;
165 static int32_t bbr_do_red = 600;
166 static int32_t bbr_red_scale = 20000;
167 static int32_t bbr_red_mul = 1;
168 static int32_t bbr_red_div = 2;
169 static int32_t bbr_red_growth_restrict = 1;
170 static int32_t  bbr_target_is_bbunit = 0;
171 static int32_t bbr_drop_limit = 0;
172 /*
173  * How much gain do we need to see to
174  * stay in startup?
175  */
176 static int32_t bbr_marks_rxt_sack_passed = 0;
177 static int32_t bbr_start_exit = 25;
178 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
179 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
180 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
181 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
182 					 * if we go back ever to where the pacer
183 					 * has priority over timers.
184 					 */
185 static int32_t bbr_policer_call_from_rack_to = 0;
186 static int32_t bbr_policer_detection_enabled = 1;
187 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
188 						 * measurements before we are
189 						 * "good" note that 2 == 1.
190 						 * This is because we use a >
191 						 * comparison. This means if
192 						 * min_measure was 0, it takes
193 						 * num-measures > min(0) and
194 						 * you get 1 measurement and
195 						 * you are good. Set to 1, you
196 						 * have to have two
197 						 * measurements (this is done
198 						 * to prevent it from being ok
199 						 * to have no measurements). */
200 static int32_t bbr_no_pacing_until = 4;
201 
202 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
203 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
204 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
205 
206 static int32_t bbr_target_cwnd_mult_limit = 8;
207 /*
208  * bbr_cwnd_min_val is the number of
209  * segments we hold to in the RTT probe
210  * state typically 4.
211  */
212 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
213 
214 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
215 
216 static int32_t bbr_gain_to_target = 1;
217 static int32_t bbr_gain_gets_extra_too = 1;
218 /*
219  * bbr_high_gain is the 2/ln(2) value we need
220  * to double the sending rate in startup. This
221  * is used for both cwnd and hptsi gain's.
222  */
223 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
224 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
225 static int32_t bbr_use_lower_gain_in_startup = 1;
226 
227 /* thresholds for reduction on drain in sub-states/drain */
228 static int32_t bbr_drain_rtt = BBR_SRTT;
229 static int32_t bbr_drain_floor = 88;
230 static int32_t google_allow_early_out = 1;
231 static int32_t google_consider_lost = 1;
232 static int32_t bbr_drain_drop_mul = 4;
233 static int32_t bbr_drain_drop_div = 5;
234 static int32_t bbr_rand_ot = 50;
235 static int32_t bbr_can_force_probertt = 0;
236 static int32_t bbr_can_adjust_probertt = 1;
237 static int32_t bbr_probertt_sets_rtt = 0;
238 static int32_t bbr_can_use_ts_for_rtt = 1;
239 static int32_t bbr_is_ratio = 0;
240 static int32_t bbr_sub_drain_app_limit = 1;
241 static int32_t bbr_prtt_slam_cwnd = 1;
242 static int32_t bbr_sub_drain_slam_cwnd = 1;
243 static int32_t bbr_slam_cwnd_in_main_drain = 1;
244 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
245 					 * hold */
246 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
247 /*
248  * bbr_drain_gain is the reverse of the high_gain
249  * designed to drain back out the standing queue
250  * that is formed in startup by causing a larger
251  * hptsi gain and thus drainging the packets
252  * in flight.
253  */
254 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
255 static int32_t bbr_rttprobe_gain = 192;
256 
257 /*
258  * The cwnd_gain is the default cwnd gain applied when
259  * calculating a target cwnd. Note that the cwnd is
260  * a secondary factor in the way BBR works (see the
261  * paper and think about it, it will take some time).
262  * Basically the hptsi_gain spreads the packets out
263  * so you never get more than BDP to the peer even
264  * if the cwnd is high. In our implemenation that
265  * means in non-recovery/retransmission scenarios
266  * cwnd will never be reached by the flight-size.
267  */
268 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
269 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
270 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
271 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
272 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
273 static int32_t bbr_ignore_data_after_close = 1;
274 static int16_t bbr_hptsi_gain[] = {
275 	(BBR_UNIT *5 / 4),
276 	(BBR_UNIT * 3 / 4),
277 	BBR_UNIT,
278 	BBR_UNIT,
279 	BBR_UNIT,
280 	BBR_UNIT,
281 	BBR_UNIT,
282 	BBR_UNIT
283 };
284 int32_t bbr_use_rack_resend_cheat = 1;
285 int32_t bbr_sends_full_iwnd = 1;
286 
287 #define BBR_HPTSI_GAIN_MAX 8
288 /*
289  * The BBR module incorporates a number of
290  * TCP ideas that have been put out into the IETF
291  * over the last few years:
292  * - Yuchung Cheng's RACK TCP (for which its named) that
293  *    will stop us using the number of dup acks and instead
294  *    use time as the gage of when we retransmit.
295  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
296  *    of Dukkipati et.al.
297  * - Van Jacobson's et.al BBR.
298  *
299  * RACK depends on SACK, so if an endpoint arrives that
300  * cannot do SACK the state machine below will shuttle the
301  * connection back to using the "default" TCP stack that is
302  * in FreeBSD.
303  *
304  * To implement BBR and RACK the original TCP stack was first decomposed
305  * into a functional state machine with individual states
306  * for each of the possible TCP connection states. The do_segment
307  * functions role in life is to mandate the connection supports SACK
308  * initially and then assure that the RACK state matches the conenction
309  * state before calling the states do_segment function. Data processing
310  * of inbound segments also now happens in the hpts_do_segment in general
311  * with only one exception. This is so we can keep the connection on
312  * a single CPU.
313  *
314  * Each state is simplified due to the fact that the original do_segment
315  * has been decomposed and we *know* what state we are in (no
316  * switches on the state) and all tests for SACK are gone. This
317  * greatly simplifies what each state does.
318  *
319  * TCP output is also over-written with a new version since it
320  * must maintain the new rack scoreboard and has had hptsi
321  * integrated as a requirment. Still todo is to eliminate the
322  * use of the callout_() system and use the hpts for all
323  * timers as well.
324  */
325 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
326 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
327 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
328 						 * free list */
329 static int32_t bbr_tlp_thresh = 1;
330 static int32_t bbr_reorder_thresh = 2;
331 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
332 						 * 60,000,000 - 60 seconds */
333 static int32_t bbr_pkt_delay = 1000;
334 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
335 static int32_t bbr_incr_timers = 1;
336 
337 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
338 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
339 static int32_t bbr_exit_startup_at_loss = 1;
340 
341 /*
342  * bbr_lt_bw_ratio is 1/8th
343  * bbr_lt_bw_diff is  < 4 Kbit/sec
344  */
345 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
346 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
347 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
348 						 * the lt_bw for */
349 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
350 						 * lt_bw */
351 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
352 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
353 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
354 
355 static int32_t bbr_verbose_logging = 0;
356 /*
357  * Currently regular tcp has a rto_min of 30ms
358  * the backoff goes 12 times so that ends up
359  * being a total of 122.850 seconds before a
360  * connection is killed.
361  */
362 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
363 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
364 
365 /****************************************************/
366 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
367 /****************************************************/
368 /* What amount is our formula using to get TSO size */
369 static int32_t bbr_hptsi_per_second = 1000;
370 
371 /*
372  * For hptsi under bbr_cross_over connections what is delay
373  * target 7ms (in usec) combined with a seg_max of 2
374  * gets us close to identical google behavior in
375  * TSO size selection (possibly more 1MSS sends).
376  */
377 static int32_t bbr_hptsi_segments_delay_tar = 7000;
378 
379 /* Does pacing delay include overhead's in its time calculations? */
380 static int32_t bbr_include_enet_oh = 0;
381 static int32_t bbr_include_ip_oh = 1;
382 static int32_t bbr_include_tcp_oh = 1;
383 static int32_t bbr_google_discount = 10;
384 
385 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
386 static int32_t bbr_state_is_pkt_epoch = 0;
387 static int32_t bbr_state_drain_2_tar = 1;
388 /* What is the max the 0 - bbr_cross_over MBPS TSO target
389  * can reach using our delay target. Note that this
390  * value becomes the floor for the cross over
391  * algorithm.
392  */
393 static int32_t bbr_hptsi_segments_max = 2;
394 static int32_t bbr_hptsi_segments_floor = 1;
395 static int32_t bbr_hptsi_utter_max = 0;
396 
397 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
398 static int32_t bbr_hptsi_bytes_min = 1460;
399 static int32_t bbr_all_get_min = 0;
400 
401 /* Cross over point from algo-a to algo-b */
402 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
403 
404 /* Do we deal with our restart state? */
405 static int32_t bbr_uses_idle_restart = 0;
406 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
407 
408 /* Do we allow hardware pacing? */
409 static int32_t bbr_allow_hdwr_pacing = 0;
410 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
411 static int32_t bbr_hdwr_pace_floor = 1;
412 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
413 
414 /****************************************************/
415 static int32_t bbr_resends_use_tso = 0;
416 static int32_t bbr_tlp_max_resend = 2;
417 static int32_t bbr_sack_block_limit = 128;
418 
419 #define  BBR_MAX_STAT 19
420 counter_u64_t bbr_state_time[BBR_MAX_STAT];
421 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
422 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
423 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
424 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
425 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
426 counter_u64_t bbr_flows_whdwr_pacing;
427 counter_u64_t bbr_flows_nohdwr_pacing;
428 
429 counter_u64_t bbr_nohdwr_pacing_enobuf;
430 counter_u64_t bbr_hdwr_pacing_enobuf;
431 
432 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
433 
434 /*
435  * Static defintions we need for forward declarations.
436  */
437 static uint32_t
438 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
439 		      uint32_t useconds_time, uint64_t bw);
440 static uint32_t
441 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
442 static void
443 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
444 static void
445 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
446 static void
447 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
448 		    int dolog);
449 static uint32_t
450 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
451 static void
452 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
453 		 int32_t pkt_epoch, uint32_t losses);
454 static uint32_t
455 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts,
456 		     struct bbr_sendmap *rsm);
457 static uint32_t
458 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
459 static uint32_t
460 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
461 		    struct bbr_sendmap *rsm, uint32_t srtt, uint32_t cts);
462 static void
463 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
464 		 int32_t line);
465 static void
466 bbr_set_state_target(struct tcp_bbr *bbr, int line);
467 static void
468 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
469 static void
470 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick,
471 		       int event, int line);
472 static void
473 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
474 static void
475 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
476 static void
477 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
478 		    uint32_t rtt, uint32_t line, uint8_t is_start,
479 		    uint16_t set);
480 static struct bbr_sendmap *
481 bbr_find_lowest_rsm(struct tcp_bbr *bbr);
482 static __inline uint32_t
483 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
484 static void
485 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot,
486 		 uint8_t which);
487 static void
488 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts,
489 		  uint32_t time_since_sent, uint32_t srtt,
490 		  uint32_t thresh, uint32_t to);
491 static void
492 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
493 static void
494 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
495 		    uint32_t del_by, uint32_t cts, uint32_t sloton,
496 		    uint32_t prev_delay);
497 static void
498 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
499 		  int32_t line);
500 static void
501 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr);
502 static void
503 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
504 static void
505 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
506 static void
507 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
508 static void
509 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
510 			  uint32_t cts, uint32_t usecs, uint64_t bw,
511 			  uint32_t override, int mod);
512 static int bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt);
513 
514 static inline uint8_t
515 bbr_state_val(struct tcp_bbr *bbr)
516 {
517 	return(bbr->rc_bbr_substate);
518 }
519 
520 static inline uint32_t
521 get_min_cwnd(struct tcp_bbr *bbr)
522 {
523 	int mss;
524 
525 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
526 		  bbr->r_ctl.rc_pace_max_segs);
527 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
528 		return (bbr_cwnd_min_val_hs * mss);
529 	else
530 		return (bbr_cwnd_min_val * mss);
531 }
532 
533 static uint32_t
534 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
535 {
536 	uint64_t srtt, var;
537 	uint64_t ret_val;
538 
539 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
540 	if (tp->t_srtt == 0) {
541 		srtt = (uint64_t)BBR_INITIAL_RTO;
542 		var = 0;
543 	} else {
544 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
545 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
546 	}
547 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
548 	    bbr_persist_min, bbr_persist_max);
549 	return ((uint32_t)ret_val);
550 }
551 
552 static uint32_t
553 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
554 {
555 	/*
556 	 * Start the FR timer, we do this based on getting the first one in
557 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
558 	 * events we need to stop the running timer (if its running) before
559 	 * starting the new one.
560 	 */
561 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
562 	int32_t idx;
563 	int32_t is_tlp_timer = 0;
564 	struct bbr_sendmap *rsm;
565 
566 	if (bbr->rc_all_timers_stopped) {
567 		/* All timers have been stopped none are to run */
568 		return (0);
569 	}
570 	if (bbr->rc_in_persist) {
571 		/* We can't start any timer in persists */
572 		return (bbr_get_persists_timer_val(tp, bbr));
573 	}
574 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
575 	if ((rsm == NULL) ||
576 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
577 	    (tp->t_state < TCPS_ESTABLISHED)) {
578 		/* Nothing on the send map */
579 activate_rxt:
580 		if (SEQ_LT(tp->snd_una, tp->snd_max) ||
581 		    sbavail(&tptosocket(tp)->so_snd)) {
582 			uint64_t tov;
583 
584 			time_since_sent = 0;
585 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
586 			if (rsm) {
587 				idx = rsm->r_rtr_cnt - 1;
588 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
589 					tstmp_touse = rsm->r_tim_lastsent[idx];
590 				else
591 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
592 				if (TSTMP_GT(tstmp_touse, cts))
593 				    time_since_sent = cts - tstmp_touse;
594 			}
595 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
596 			if (tp->t_srtt == 0)
597 				tov = BBR_INITIAL_RTO;
598 			else
599 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
600 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
601 			if (tp->t_rxtshift)
602 				tov *= tcp_backoff[tp->t_rxtshift];
603 			if (tov > time_since_sent)
604 				tov -= time_since_sent;
605 			else
606 				tov = bbr->r_ctl.rc_min_to;
607 			TCPT_RANGESET_NOSLOP(to, tov,
608 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
609 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
610 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
611 			return (to);
612 		}
613 		return (0);
614 	}
615 	if (rsm->r_flags & BBR_ACKED) {
616 		rsm = bbr_find_lowest_rsm(bbr);
617 		if (rsm == NULL) {
618 			/* No lowest? */
619 			goto activate_rxt;
620 		}
621 	}
622 	/* Convert from ms to usecs */
623 	if (rsm->r_flags & BBR_SACK_PASSED) {
624 		if ((tp->t_flags & TF_SENTFIN) &&
625 		    ((tp->snd_max - tp->snd_una) == 1) &&
626 		    (rsm->r_flags & BBR_HAS_FIN)) {
627 			/*
628 			 * We don't start a bbr rack timer if all we have is
629 			 * a FIN outstanding.
630 			 */
631 			goto activate_rxt;
632 		}
633 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
634 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
635 		idx = rsm->r_rtr_cnt - 1;
636 		exp = rsm->r_tim_lastsent[idx] + thresh;
637 		if (SEQ_GEQ(exp, cts)) {
638 			to = exp - cts;
639 			if (to < bbr->r_ctl.rc_min_to) {
640 				to = bbr->r_ctl.rc_min_to;
641 			}
642 		} else {
643 			to = bbr->r_ctl.rc_min_to;
644 		}
645 	} else {
646 		/* Ok we need to do a TLP not RACK */
647 		if (bbr->rc_tlp_in_progress != 0) {
648 			/*
649 			 * The previous send was a TLP.
650 			 */
651 			goto activate_rxt;
652 		}
653 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
654 		if (rsm == NULL) {
655 			/* We found no rsm to TLP with. */
656 			goto activate_rxt;
657 		}
658 		if (rsm->r_flags & BBR_HAS_FIN) {
659 			/* If its a FIN we don't do TLP */
660 			rsm = NULL;
661 			goto activate_rxt;
662 		}
663 		time_since_sent = 0;
664 		idx = rsm->r_rtr_cnt - 1;
665 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
666 			tstmp_touse = rsm->r_tim_lastsent[idx];
667 		else
668 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
669 		if (TSTMP_GT(tstmp_touse, cts))
670 		    time_since_sent = cts - tstmp_touse;
671 		is_tlp_timer = 1;
672 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
673 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
674 		if (thresh > time_since_sent)
675 			to = thresh - time_since_sent;
676 		else
677 			to = bbr->r_ctl.rc_min_to;
678 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
679 			/*
680 			 * If the TLP time works out to larger than the max
681 			 * RTO lets not do TLP.. just RTO.
682 			 */
683 			goto activate_rxt;
684 		}
685 		if ((bbr->rc_tlp_rtx_out == 1) &&
686 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
687 			/*
688 			 * Second retransmit of the same TLP
689 			 * lets not.
690 			 */
691 			bbr->rc_tlp_rtx_out = 0;
692 			goto activate_rxt;
693 		}
694 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
695 			/*
696 			 * The tail is no longer the last one I did a probe
697 			 * on
698 			 */
699 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
700 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
701 		}
702 	}
703 	if (is_tlp_timer == 0) {
704 		BBR_STAT_INC(bbr_to_arm_rack);
705 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
706 	} else {
707 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
708 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
709 			/*
710 			 * We have exceeded how many times we can retran the
711 			 * current TLP timer, switch to the RTO timer.
712 			 */
713 			goto activate_rxt;
714 		} else {
715 			BBR_STAT_INC(bbr_to_arm_tlp);
716 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
717 		}
718 	}
719 	return (to);
720 }
721 
722 static inline int32_t
723 bbr_minseg(struct tcp_bbr *bbr)
724 {
725 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
726 }
727 
728 static void
729 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
730 {
731 	struct inpcb *inp = tptoinpcb(tp);
732 	struct hpts_diag diag;
733 	uint32_t delayed_ack = 0;
734 	uint32_t left = 0;
735 	uint32_t hpts_timeout;
736 	uint8_t stopped;
737 	int32_t delay_calc = 0;
738 	uint32_t prev_delay = 0;
739 
740 	if (tcp_in_hpts(tp)) {
741 		/* A previous call is already set up */
742 		return;
743 	}
744 	if ((tp->t_state == TCPS_CLOSED) ||
745 	    (tp->t_state == TCPS_LISTEN)) {
746 		return;
747 	}
748 	stopped = bbr->rc_tmr_stopped;
749 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
750 		left = bbr->r_ctl.rc_timer_exp - cts;
751 	}
752 	bbr->r_ctl.rc_hpts_flags = 0;
753 	bbr->r_ctl.rc_timer_exp = 0;
754 	prev_delay = bbr->r_ctl.rc_last_delay_val;
755 	if (bbr->r_ctl.rc_last_delay_val &&
756 	    (slot == 0)) {
757 		/*
758 		 * If a previous pacer delay was in place we
759 		 * are not coming from the output side (where
760 		 * we calculate a delay, more likely a timer).
761 		 */
762 		slot = bbr->r_ctl.rc_last_delay_val;
763 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
764 			/* Compensate for time passed  */
765 			delay_calc = cts - bbr->rc_pacer_started;
766 			if (delay_calc <= slot)
767 				slot -= delay_calc;
768 		}
769 	}
770 	/* Do we have early to make up for by pushing out the pacing time? */
771 	if (bbr->r_agg_early_set) {
772 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
773 		slot += bbr->r_ctl.rc_agg_early;
774 		bbr->r_ctl.rc_agg_early = 0;
775 		bbr->r_agg_early_set = 0;
776 	}
777 	/* Are we running a total debt that needs to be compensated for? */
778 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
779 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
780 			/* We nuke the delay */
781 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
782 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
783 		} else {
784 			/* We nuke some of the delay, put in a minimal 100usecs  */
785 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
786 			bbr->r_ctl.rc_last_delay_val = slot = 100;
787 		}
788 	}
789 	bbr->r_ctl.rc_last_delay_val = slot;
790 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
791 	if (tp->t_flags & TF_DELACK) {
792 		if (bbr->rc_in_persist == 0) {
793 			delayed_ack = bbr_delack_time;
794 		} else {
795 			/*
796 			 * We are in persists and have
797 			 * gotten a new data element.
798 			 */
799 			if (hpts_timeout > bbr_delack_time) {
800 				/*
801 				 * Lets make the persists timer (which acks)
802 				 * be the smaller of hpts_timeout and bbr_delack_time.
803 				 */
804 				hpts_timeout = bbr_delack_time;
805 			}
806 		}
807 	}
808 	if (delayed_ack &&
809 	    ((hpts_timeout == 0) ||
810 	     (delayed_ack < hpts_timeout))) {
811 		/* We need a Delayed ack timer */
812 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
813 		hpts_timeout = delayed_ack;
814 	}
815 	if (slot) {
816 		/* Mark that we have a pacing timer up */
817 		BBR_STAT_INC(bbr_paced_segments);
818 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
819 	}
820 	/*
821 	 * If no timers are going to run and we will fall off thfe hptsi
822 	 * wheel, we resort to a keep-alive timer if its configured.
823 	 */
824 	if ((hpts_timeout == 0) &&
825 	    (slot == 0)) {
826 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
827 		    (tp->t_state <= TCPS_CLOSING)) {
828 			/*
829 			 * Ok we have no timer (persists, rack, tlp, rxt  or
830 			 * del-ack), we don't have segments being paced. So
831 			 * all that is left is the keepalive timer.
832 			 */
833 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
834 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
835 			} else {
836 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
837 			}
838 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
839 		}
840 	}
841 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
842 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
843 		/*
844 		 * RACK, TLP, persists and RXT timers all are restartable
845 		 * based on actions input .. i.e we received a packet (ack
846 		 * or sack) and that changes things (rw, or snd_una etc).
847 		 * Thus we can restart them with a new value. For
848 		 * keep-alive, delayed_ack we keep track of what was left
849 		 * and restart the timer with a smaller value.
850 		 */
851 		if (left < hpts_timeout)
852 			hpts_timeout = left;
853 	}
854 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
855 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
856 		/*
857 		 * If configured to do so, and the timer is either
858 		 * the TLP or RXT timer, we need to increase the timeout
859 		 * by the pacing time. Consider the bottleneck at my
860 		 * machine as an example, we are sending something
861 		 * to start a TLP on. The last packet won't be emitted
862 		 * fully until the pacing time (the bottleneck will hold
863 		 * the data in place). Once the packet is emitted that
864 		 * is when we want to start waiting for the TLP. This
865 		 * is most evident with hardware pacing (where the nic
866 		 * is holding the packet(s) before emitting). But it
867 		 * can also show up in the network so we do it for all
868 		 * cases. Technically we would take off one packet from
869 		 * this extra delay but this is easier and being more
870 		 * conservative is probably better.
871 		 */
872 		hpts_timeout += slot;
873 	}
874 	if (hpts_timeout) {
875 		/*
876 		 * Hack alert for now we can't time-out over 2147 seconds (a
877 		 * bit more than 35min)
878 		 */
879 		if (hpts_timeout > 0x7ffffffe)
880 			hpts_timeout = 0x7ffffffe;
881 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
882 	} else
883 		bbr->r_ctl.rc_timer_exp = 0;
884 	if ((slot) &&
885 	    (bbr->rc_use_google ||
886 	     bbr->output_error_seen ||
887 	     (slot <= hpts_timeout))  ) {
888 		/*
889 		 * Tell LRO that it can queue packets while
890 		 * we pace.
891 		 */
892 		bbr->rc_tp->t_flags2 |= TF2_MBUF_QUEUE_READY;
893 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
894 		    (bbr->rc_cwnd_limited == 0)) {
895 			/*
896 			 * If we are not cwnd limited and we
897 			 * are running a rack timer we put on
898 			 * the do not disturbe even for sack.
899 			 */
900 			tp->t_flags2 |= TF2_DONT_SACK_QUEUE;
901 		} else
902 			tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
903 		bbr->rc_pacer_started = cts;
904 
905 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(slot),
906 					   __LINE__, &diag);
907 		bbr->rc_timer_first = 0;
908 		bbr->bbr_timer_src = frm;
909 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
910 		bbr_log_hpts_diag(bbr, cts, &diag);
911 	} else if (hpts_timeout) {
912 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(hpts_timeout),
913 					   __LINE__, &diag);
914 		/*
915 		 * We add the flag here as well if the slot is set,
916 		 * since hpts will call in to clear the queue first before
917 		 * calling the output routine (which does our timers).
918 		 * We don't want to set the flag if its just a timer
919 		 * else the arrival of data might (that causes us
920 		 * to send more) might get delayed. Imagine being
921 		 * on a keep-alive timer and a request comes in for
922 		 * more data.
923 		 */
924 		if (slot)
925 			bbr->rc_pacer_started = cts;
926 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
927 		    (bbr->rc_cwnd_limited == 0)) {
928 			/*
929 			 * For a rack timer, don't wake us even
930 			 * if a sack arrives as long as we are
931 			 * not cwnd limited.
932 			 */
933 			tp->t_flags2 |= (TF2_MBUF_QUEUE_READY |
934 			    TF2_DONT_SACK_QUEUE);
935 		} else {
936 			/* All other timers wake us up */
937 			tp->t_flags2 &= ~(TF2_MBUF_QUEUE_READY |
938 			    TF2_DONT_SACK_QUEUE);
939 		}
940 		bbr->bbr_timer_src = frm;
941 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
942 		bbr_log_hpts_diag(bbr, cts, &diag);
943 		bbr->rc_timer_first = 1;
944 	}
945 	bbr->rc_tmr_stopped = 0;
946 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
947 }
948 
949 static void
950 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
951 {
952 	/*
953 	 * We received an ack, and then did not call send or were bounced
954 	 * out due to the hpts was running. Now a timer is up as well, is it
955 	 * the right timer?
956 	 */
957 	struct inpcb *inp;
958 	struct bbr_sendmap *rsm;
959 	uint32_t hpts_timeout;
960 	int tmr_up;
961 
962 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
963 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
964 		return;
965 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
966 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
967 	    (tmr_up == PACE_TMR_RXT)) {
968 		/* Should be an RXT */
969 		return;
970 	}
971 	inp = bbr->rc_inp;
972 	if (rsm == NULL) {
973 		/* Nothing outstanding? */
974 		if (tp->t_flags & TF_DELACK) {
975 			if (tmr_up == PACE_TMR_DELACK)
976 				/*
977 				 * We are supposed to have delayed ack up
978 				 * and we do
979 				 */
980 				return;
981 		} else if (sbavail(&inp->inp_socket->so_snd) &&
982 		    (tmr_up == PACE_TMR_RXT)) {
983 			/*
984 			 * if we hit enobufs then we would expect the
985 			 * possibility of nothing outstanding and the RXT up
986 			 * (and the hptsi timer).
987 			 */
988 			return;
989 		} else if (((V_tcp_always_keepalive ||
990 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
991 			    (tp->t_state <= TCPS_CLOSING)) &&
992 			    (tmr_up == PACE_TMR_KEEP) &&
993 		    (tp->snd_max == tp->snd_una)) {
994 			/* We should have keep alive up and we do */
995 			return;
996 		}
997 	}
998 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
999 		if ((tp->t_flags & TF_SENTFIN) &&
1000 		    ((tp->snd_max - tp->snd_una) == 1) &&
1001 		    (rsm->r_flags & BBR_HAS_FIN)) {
1002 			/* needs to be a RXT */
1003 			if (tmr_up == PACE_TMR_RXT)
1004 				return;
1005 			else
1006 				goto wrong_timer;
1007 		} else if (tmr_up == PACE_TMR_RACK)
1008 			return;
1009 		else
1010 			goto wrong_timer;
1011 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1012 		/* Rack timer has priority if we have data out */
1013 		return;
1014 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1015 		    ((tmr_up == PACE_TMR_TLP) ||
1016 	    (tmr_up == PACE_TMR_RXT))) {
1017 		/*
1018 		 * Either a TLP or RXT is fine if no sack-passed is in place
1019 		 * and data is outstanding.
1020 		 */
1021 		return;
1022 	} else if (tmr_up == PACE_TMR_DELACK) {
1023 		/*
1024 		 * If the delayed ack was going to go off before the
1025 		 * rtx/tlp/rack timer were going to expire, then that would
1026 		 * be the timer in control. Note we don't check the time
1027 		 * here trusting the code is correct.
1028 		 */
1029 		return;
1030 	}
1031 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1032 	    ((tmr_up == PACE_TMR_RXT) ||
1033 	     (tmr_up == PACE_TMR_TLP) ||
1034 	     (tmr_up == PACE_TMR_RACK))) {
1035 		/*
1036 		 * We have outstanding data and
1037 		 * we *do* have a RACK, TLP or RXT
1038 		 * timer running. We won't restart
1039 		 * anything here since thats probably ok we
1040 		 * will get called with some timer here shortly.
1041 		 */
1042 		return;
1043 	}
1044 	/*
1045 	 * Ok the timer originally started is not what we want now. We will
1046 	 * force the hpts to be stopped if any, and restart with the slot
1047 	 * set to what was in the saved slot.
1048 	 */
1049 wrong_timer:
1050 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1051 		if (tcp_in_hpts(tp))
1052 			tcp_hpts_remove(tp);
1053 		bbr_timer_cancel(bbr, __LINE__, cts);
1054 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1055 		    0);
1056 	} else {
1057 		/*
1058 		 * Output is hptsi so we just need to switch the type of
1059 		 * timer. We don't bother with keep-alive, since when we
1060 		 * jump through the output, it will start the keep-alive if
1061 		 * nothing is sent.
1062 		 *
1063 		 * We only need a delayed-ack added and or the hpts_timeout.
1064 		 */
1065 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1066 		if (tp->t_flags & TF_DELACK) {
1067 			if (hpts_timeout == 0) {
1068 				hpts_timeout = bbr_delack_time;
1069 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1070 			}
1071 			else if (hpts_timeout > bbr_delack_time) {
1072 				hpts_timeout = bbr_delack_time;
1073 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1074 			}
1075 		}
1076 		if (hpts_timeout) {
1077 			if (hpts_timeout > 0x7ffffffe)
1078 				hpts_timeout = 0x7ffffffe;
1079 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1080 		}
1081 	}
1082 }
1083 
1084 int32_t bbr_clear_lost = 0;
1085 
1086 /*
1087  * Considers the two time values now (cts) and earlier.
1088  * If cts is smaller than earlier, we could have
1089  * had a sequence wrap (our counter wraps every
1090  * 70 min or so) or it could be just clock skew
1091  * getting us two different time values. Clock skew
1092  * will show up within 10ms or so. So in such
1093  * a case (where cts is behind earlier time by
1094  * less than 10ms) we return 0. Otherwise we
1095  * return the true difference between them.
1096  */
1097 static inline uint32_t
1098 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1099 	/*
1100 	 * Given two timestamps, the current time stamp cts, and some other
1101 	 * time-stamp taken in theory earlier return the difference. The
1102 	 * trick is here sometimes locking will get the other timestamp
1103 	 * after the cts. If this occurs we need to return 0.
1104 	 */
1105 	if (TSTMP_GEQ(cts, earlier_time))
1106 		return (cts - earlier_time);
1107 	/*
1108 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1109 	 * If its more than 10ms difference then we had a time wrap. Else
1110 	 * its just the normal locking foo. I wonder if we should not go to
1111 	 * 64bit TS and get rid of this issue.
1112 	 */
1113 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1114 		return (0);
1115 	/*
1116 	 * Ok the time must have wrapped. So we need to answer a large
1117 	 * amount of time, which the normal subtraction should do.
1118 	 */
1119 	return (cts - earlier_time);
1120 }
1121 
1122 static int
1123 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1124 {
1125 	uint32_t stat;
1126 	int32_t error;
1127 
1128 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1129 	if (error || req->newptr == NULL)
1130 		return error;
1131 
1132 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1133 	if (error)
1134 		return (error);
1135 	if (stat == 1) {
1136 #ifdef BBR_INVARIANTS
1137 		printf("Clearing BBR lost counters\n");
1138 #endif
1139 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1140 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1141 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1142 	} else if (stat == 2) {
1143 #ifdef BBR_INVARIANTS
1144 		printf("Clearing BBR option counters\n");
1145 #endif
1146 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1147 	} else if (stat == 3) {
1148 #ifdef BBR_INVARIANTS
1149 		printf("Clearing BBR stats counters\n");
1150 #endif
1151 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1152 	} else if (stat == 4) {
1153 #ifdef BBR_INVARIANTS
1154 		printf("Clearing BBR out-size counters\n");
1155 #endif
1156 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1157 	}
1158 	bbr_clear_lost = 0;
1159 	return (0);
1160 }
1161 
1162 static void
1163 bbr_init_sysctls(void)
1164 {
1165 	struct sysctl_oid *bbr_probertt;
1166 	struct sysctl_oid *bbr_hptsi;
1167 	struct sysctl_oid *bbr_measure;
1168 	struct sysctl_oid *bbr_cwnd;
1169 	struct sysctl_oid *bbr_timeout;
1170 	struct sysctl_oid *bbr_states;
1171 	struct sysctl_oid *bbr_startup;
1172 	struct sysctl_oid *bbr_policer;
1173 
1174 	/* Probe rtt controls */
1175 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1176 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1177 	    OID_AUTO,
1178 	    "probertt",
1179 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1180 	    "");
1181 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1182 	    SYSCTL_CHILDREN(bbr_probertt),
1183 	    OID_AUTO, "gain", CTLFLAG_RW,
1184 	    &bbr_rttprobe_gain, 192,
1185 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1186 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1187 	    SYSCTL_CHILDREN(bbr_probertt),
1188 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1189 	    &bbr_rtt_probe_cwndtarg, 4,
1190 	    "How many mss's are outstanding during probe-rtt");
1191 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1192 	    SYSCTL_CHILDREN(bbr_probertt),
1193 	    OID_AUTO, "int", CTLFLAG_RW,
1194 	    &bbr_rtt_probe_limit, 4000000,
1195 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1196 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1197 	    SYSCTL_CHILDREN(bbr_probertt),
1198 	    OID_AUTO, "mintime", CTLFLAG_RW,
1199 	    &bbr_rtt_probe_time, 200000,
1200 	    "How many microseconds in probe-rtt");
1201 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1202 	    SYSCTL_CHILDREN(bbr_probertt),
1203 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1204 	    &bbr_filter_len_sec, 6,
1205 	    "How long in seconds does the rttProp filter run?");
1206 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1207 	    SYSCTL_CHILDREN(bbr_probertt),
1208 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1209 	    &bbr_drain_rtt, BBR_SRTT,
1210 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1211 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1212 	    SYSCTL_CHILDREN(bbr_probertt),
1213 	    OID_AUTO, "can_force", CTLFLAG_RW,
1214 	    &bbr_can_force_probertt, 0,
1215 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1216 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1217 	    SYSCTL_CHILDREN(bbr_probertt),
1218 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1219 	    &bbr_probertt_sets_rtt, 0,
1220 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1221 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1222 	    SYSCTL_CHILDREN(bbr_probertt),
1223 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1224 	    &bbr_can_adjust_probertt, 1,
1225 	    "Can we dynamically adjust the probe-rtt limits and times?");
1226 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1227 	    SYSCTL_CHILDREN(bbr_probertt),
1228 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1229 	    &bbr_is_ratio, 0,
1230 	    "is the limit to filter a ratio?");
1231 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1232 	    SYSCTL_CHILDREN(bbr_probertt),
1233 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1234 	    &bbr_prtt_slam_cwnd, 0,
1235 	    "Should we set/recover cwnd?");
1236 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1237 	    SYSCTL_CHILDREN(bbr_probertt),
1238 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1239 	    &bbr_can_use_ts_for_rtt, 1,
1240 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1241 
1242 	/* Pacing controls */
1243 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1244 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1245 	    OID_AUTO,
1246 	    "pacing",
1247 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1248 	    "");
1249 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1250 	    SYSCTL_CHILDREN(bbr_hptsi),
1251 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1252 	    &bbr_allow_hdwr_pacing, 1,
1253 	    "Do we allow hardware pacing?");
1254 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1255 	    SYSCTL_CHILDREN(bbr_hptsi),
1256 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1257 	    &bbr_hardware_pacing_limit, 4000,
1258 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1259 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1260 	    SYSCTL_CHILDREN(bbr_hptsi),
1261 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1262 	    &bbr_hdwr_pace_adjust, 2,
1263 	    "Multiplier to calculated tso size?");
1264 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1265 	    SYSCTL_CHILDREN(bbr_hptsi),
1266 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1267 	    &bbr_hdwr_pace_floor, 1,
1268 	    "Do we invoke the hardware pacing floor?");
1269 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1270 	    SYSCTL_CHILDREN(bbr_hptsi),
1271 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1272 	    &bbr_hdwr_pacing_delay_cnt, 10,
1273 	    "How many packets must be sent after hdwr pacing is enabled");
1274 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1275 	    SYSCTL_CHILDREN(bbr_hptsi),
1276 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1277 	    &bbr_cross_over, 3000000,
1278 	    "What is the point where we cross over to linux like TSO size set");
1279 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1280 	    SYSCTL_CHILDREN(bbr_hptsi),
1281 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1282 	    &bbr_hptsi_segments_delay_tar, 7000,
1283 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1284 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1285 	    SYSCTL_CHILDREN(bbr_hptsi),
1286 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1287 	    &bbr_include_enet_oh, 0,
1288 	    "Do we include the ethernet overhead in calculating pacing delay?");
1289 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1290 	    SYSCTL_CHILDREN(bbr_hptsi),
1291 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1292 	    &bbr_include_ip_oh, 1,
1293 	    "Do we include the IP overhead in calculating pacing delay?");
1294 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1295 	    SYSCTL_CHILDREN(bbr_hptsi),
1296 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1297 	    &bbr_include_tcp_oh, 0,
1298 	    "Do we include the TCP overhead in calculating pacing delay?");
1299 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1300 	    SYSCTL_CHILDREN(bbr_hptsi),
1301 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1302 	    &bbr_google_discount, 10,
1303 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1304 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1305 	    SYSCTL_CHILDREN(bbr_hptsi),
1306 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1307 	    &bbr_all_get_min, 0,
1308 	    "If you are less than a MSS do you just get the min?");
1309 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1310 	    SYSCTL_CHILDREN(bbr_hptsi),
1311 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1312 	    &bbr_hptsi_bytes_min, 1460,
1313 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1314 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1315 	    SYSCTL_CHILDREN(bbr_hptsi),
1316 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1317 	    &bbr_hptsi_segments_max, 6,
1318 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1319 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1320 	    SYSCTL_CHILDREN(bbr_hptsi),
1321 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1322 	    &bbr_hptsi_segments_floor, 1,
1323 	    "Minimum TSO size we will fall too in segments");
1324 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1325 	    SYSCTL_CHILDREN(bbr_hptsi),
1326 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1327 	    &bbr_hptsi_utter_max, 0,
1328 	    "The absolute maximum that any pacing (outside of hardware) can be");
1329 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1330 	    SYSCTL_CHILDREN(bbr_hptsi),
1331 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1332 	    &bbr_hptsi_per_second, 100,
1333 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1334 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1335 	    SYSCTL_CHILDREN(bbr_hptsi),
1336 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1337 	    &bbr_hptsi_max_mul, 1,
1338 	    "The multiplier for pace len max");
1339 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1340 	    SYSCTL_CHILDREN(bbr_hptsi),
1341 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1342 	    &bbr_hptsi_max_div, 2,
1343 	    "The divisor for pace len max");
1344 	/* Measurement controls */
1345 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1346 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1347 	    OID_AUTO,
1348 	    "measure",
1349 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1350 	    "Measurement controls");
1351 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1352 	    SYSCTL_CHILDREN(bbr_measure),
1353 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1354 	    &bbr_initial_bw_bps, 62500,
1355 	    "Minimum initial b/w in bytes per second");
1356 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1357 	    SYSCTL_CHILDREN(bbr_measure),
1358 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1359 	    &bbr_sack_not_required, 0,
1360 	    "Do we allow bbr to run on connections not supporting SACK?");
1361 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1362 	    SYSCTL_CHILDREN(bbr_measure),
1363 	    OID_AUTO, "use_google", CTLFLAG_RW,
1364 	    &bbr_use_google_algo, 0,
1365 	    "Use has close to google V1.0 has possible?");
1366 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1367 	    SYSCTL_CHILDREN(bbr_measure),
1368 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1369 	    &bbr_ts_limiting, 1,
1370 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1371 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1372 	    SYSCTL_CHILDREN(bbr_measure),
1373 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1374 	    &bbr_ts_can_raise, 0,
1375 	    "Can we raise the b/w via timestamp b/w calculation?");
1376 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1377 	    SYSCTL_CHILDREN(bbr_measure),
1378 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1379 	    &bbr_min_usec_delta, 20000,
1380 	    "How long in usec between ts of our sends in ts validation code?");
1381 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1382 	    SYSCTL_CHILDREN(bbr_measure),
1383 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1384 	    &bbr_min_peer_delta, 20,
1385 	    "What min numerical value should be between the peer deltas?");
1386 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1387 	    SYSCTL_CHILDREN(bbr_measure),
1388 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1389 	    &bbr_delta_percent, 150,
1390 	    "What percentage (150 = 15.0) do we allow variance for?");
1391 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1392 	    SYSCTL_CHILDREN(bbr_measure),
1393 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1394 	    &bbr_min_measurements_req, 1,
1395 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1396 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1397 	    SYSCTL_CHILDREN(bbr_measure),
1398 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1399 	    &bbr_no_pacing_until, 4,
1400 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1401 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1402 	    SYSCTL_CHILDREN(bbr_measure),
1403 	    OID_AUTO, "quanta", CTLFLAG_RW,
1404 	    &bbr_quanta, 2,
1405 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1406 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1407 	    SYSCTL_CHILDREN(bbr_measure),
1408 	    OID_AUTO, "noretran", CTLFLAG_RW,
1409 	    &bbr_no_retran, 0,
1410 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1411 	/* State controls */
1412 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1413 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1414 	    OID_AUTO,
1415 	    "states",
1416 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1417 	    "State controls");
1418 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1419 	    SYSCTL_CHILDREN(bbr_states),
1420 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1421 	    &bbr_uses_idle_restart, 0,
1422 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1423 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1424 	    SYSCTL_CHILDREN(bbr_states),
1425 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1426 	    &bbr_idle_restart_threshold, 100000,
1427 	    "How long must we be idle before we restart??");
1428 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1429 	    SYSCTL_CHILDREN(bbr_states),
1430 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1431 	    &bbr_state_is_pkt_epoch, 0,
1432 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1433 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1434 	    SYSCTL_CHILDREN(bbr_states),
1435 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1436 	    &bbr_rtt_gain_thresh, 0,
1437 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1438 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1439 	    SYSCTL_CHILDREN(bbr_states),
1440 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1441 	    &bbr_drain_floor, 88,
1442 	    "What is the lowest we can drain (pg) too?");
1443 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1444 	    SYSCTL_CHILDREN(bbr_states),
1445 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1446 	    &bbr_state_drain_2_tar, 1,
1447 	    "Do we drain to target in drain substate?");
1448 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1449 	    SYSCTL_CHILDREN(bbr_states),
1450 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1451 	    &bbr_gain_to_target, 1,
1452 	    "Does probe bw gain to target??");
1453 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1454 	    SYSCTL_CHILDREN(bbr_states),
1455 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1456 	    &bbr_gain_gets_extra_too, 1,
1457 	    "Does probe bw gain get the extra time too?");
1458 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1459 	    SYSCTL_CHILDREN(bbr_states),
1460 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1461 	    &bbr_drain_drop_div, 5,
1462 	    "Long drain drop divider?");
1463 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1464 	    SYSCTL_CHILDREN(bbr_states),
1465 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1466 	    &bbr_drain_drop_mul, 4,
1467 	    "Long drain drop multiplier?");
1468 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1469 	    SYSCTL_CHILDREN(bbr_states),
1470 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1471 	    &bbr_rand_ot, 50,
1472 	    "Random discount of the ot?");
1473 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1474 	    SYSCTL_CHILDREN(bbr_states),
1475 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1476 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1477 	    "How many packet-epochs does the b/w delivery rate last?");
1478 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1479 	    SYSCTL_CHILDREN(bbr_states),
1480 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1481 	    &bbr_sub_drain_app_limit, 0,
1482 	    "Does our sub-state drain invoke app limited if its long?");
1483 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1484 	    SYSCTL_CHILDREN(bbr_states),
1485 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1486 	    &bbr_sub_drain_slam_cwnd, 0,
1487 	    "Should we set/recover cwnd for sub-state drain?");
1488 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1489 	    SYSCTL_CHILDREN(bbr_states),
1490 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1491 	    &bbr_slam_cwnd_in_main_drain, 0,
1492 	    "Should we set/recover cwnd for main-state drain?");
1493 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1494 	    SYSCTL_CHILDREN(bbr_states),
1495 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1496 	    &google_allow_early_out, 1,
1497 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1498 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1499 	    SYSCTL_CHILDREN(bbr_states),
1500 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1501 	    &google_consider_lost, 1,
1502 	    "Should we have losses exit gain of probebw in google mode??");
1503 	/* Startup controls */
1504 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1505 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1506 	    OID_AUTO,
1507 	    "startup",
1508 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1509 	    "Startup controls");
1510 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1511 	    SYSCTL_CHILDREN(bbr_startup),
1512 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1513 	    &bbr_sends_full_iwnd, 1,
1514 	    "Do we not pace but burst out initial windows has our TSO size?");
1515 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1516 	    SYSCTL_CHILDREN(bbr_startup),
1517 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1518 	    &bbr_startup_loss_thresh, 2000,
1519 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1520 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1521 	    SYSCTL_CHILDREN(bbr_startup),
1522 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1523 	    &bbr_use_lower_gain_in_startup, 1,
1524 	    "Should we use a lower hptsi gain if we see loss in startup?");
1525 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1526 	    SYSCTL_CHILDREN(bbr_startup),
1527 	    OID_AUTO, "gain", CTLFLAG_RW,
1528 	    &bbr_start_exit, 25,
1529 	    "What gain percent do we need to see to stay in startup??");
1530 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1531 	    SYSCTL_CHILDREN(bbr_startup),
1532 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1533 	    &bbr_low_start_exit, 15,
1534 	    "What gain percent do we need to see to stay in the lower gain startup??");
1535 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1536 	    SYSCTL_CHILDREN(bbr_startup),
1537 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1538 	    &bbr_exit_startup_at_loss, 1,
1539 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1540 	/* CWND controls */
1541 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1542 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1543 	    OID_AUTO,
1544 	    "cwnd",
1545 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1546 	    "Cwnd controls");
1547 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1548 	    SYSCTL_CHILDREN(bbr_cwnd),
1549 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1550 	    &bbr_cwndtarget_rtt_touse, 0,
1551 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1552 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1553 	    SYSCTL_CHILDREN(bbr_cwnd),
1554 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1555 	    &bbr_cwnd_may_shrink, 0,
1556 	    "Can the cwnd shrink if it would grow to more than the target?");
1557 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1558 	    SYSCTL_CHILDREN(bbr_cwnd),
1559 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1560 	    &bbr_target_cwnd_mult_limit, 8,
1561 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1562 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1563 	    SYSCTL_CHILDREN(bbr_cwnd),
1564 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1565 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1566 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1567 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1568 	    SYSCTL_CHILDREN(bbr_cwnd),
1569 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1570 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1571 	    "What is the min cwnd (rttProp > 1ms)");
1572 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1573 	    SYSCTL_CHILDREN(bbr_cwnd),
1574 	    OID_AUTO, "initwin", CTLFLAG_RW,
1575 	    &bbr_def_init_win, 10,
1576 	    "What is the BBR initial window, if 0 use tcp version");
1577 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1578 	    SYSCTL_CHILDREN(bbr_cwnd),
1579 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1580 	    &bbr_do_red, 600,
1581 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1582 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1583 	    SYSCTL_CHILDREN(bbr_cwnd),
1584 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1585 	    &bbr_red_scale, 20000,
1586 	    "What RTT do we scale with?");
1587 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1588 	    SYSCTL_CHILDREN(bbr_cwnd),
1589 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1590 	    &bbr_red_growth_restrict, 1,
1591 	    "Do we restrict cwnd growth for whats in flight?");
1592 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1593 	    SYSCTL_CHILDREN(bbr_cwnd),
1594 	    OID_AUTO, "red_div", CTLFLAG_RW,
1595 	    &bbr_red_div, 2,
1596 	    "If we reduce whats the divisor?");
1597 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1598 	    SYSCTL_CHILDREN(bbr_cwnd),
1599 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1600 	    &bbr_red_mul, 1,
1601 	    "If we reduce whats the mulitiplier?");
1602 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1603 	    SYSCTL_CHILDREN(bbr_cwnd),
1604 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1605 	    &bbr_target_is_bbunit, 0,
1606 	    "Is the state target the pacing_gain or BBR_UNIT?");
1607 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1608 	    SYSCTL_CHILDREN(bbr_cwnd),
1609 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1610 	    &bbr_drop_limit, 0,
1611 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1612 
1613 	/* Timeout controls */
1614 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1615 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1616 	    OID_AUTO,
1617 	    "timeout",
1618 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1619 	    "Time out controls");
1620 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1621 	    SYSCTL_CHILDREN(bbr_timeout),
1622 	    OID_AUTO, "delack", CTLFLAG_RW,
1623 	    &bbr_delack_time, 100000,
1624 	    "BBR's delayed ack time");
1625 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1626 	    SYSCTL_CHILDREN(bbr_timeout),
1627 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1628 	    &bbr_tlp_type_to_use, 3,
1629 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1630 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1631 	    SYSCTL_CHILDREN(bbr_timeout),
1632 	    OID_AUTO, "persmin", CTLFLAG_RW,
1633 	    &bbr_persist_min, 250000,
1634 	    "What is the minimum time in microseconds between persists");
1635 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1636 	    SYSCTL_CHILDREN(bbr_timeout),
1637 	    OID_AUTO, "persmax", CTLFLAG_RW,
1638 	    &bbr_persist_max, 1000000,
1639 	    "What is the largest delay in microseconds between persists");
1640 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1641 	    SYSCTL_CHILDREN(bbr_timeout),
1642 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1643 	    &bbr_tlp_min, 10000,
1644 	    "TLP Min timeout in usecs");
1645 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1646 	    SYSCTL_CHILDREN(bbr_timeout),
1647 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1648 	    &bbr_delayed_ack_time, 200000,
1649 	    "TLP delayed ack compensation value");
1650 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1651 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1652 	    OID_AUTO, "minrto", CTLFLAG_RW,
1653 	    &bbr_rto_min_ms, 30,
1654 	    "Minimum RTO in ms");
1655 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1656 	    SYSCTL_CHILDREN(bbr_timeout),
1657 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1658 	    &bbr_rto_max_sec, 4,
1659 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1660 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1661 	    SYSCTL_CHILDREN(bbr_timeout),
1662 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1663 	    &bbr_tlp_max_resend, 2,
1664 	    "How many times does TLP retry a single segment or multiple with no ACK");
1665 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1666 	    SYSCTL_CHILDREN(bbr_timeout),
1667 	    OID_AUTO, "minto", CTLFLAG_RW,
1668 	    &bbr_min_to, 1000,
1669 	    "Minimum rack timeout in useconds");
1670 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1671 	    SYSCTL_CHILDREN(bbr_timeout),
1672 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1673 	    &bbr_pkt_delay, 1000,
1674 	    "Extra RACK time (in useconds) besides reordering thresh");
1675 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1676 	    SYSCTL_CHILDREN(bbr_timeout),
1677 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1678 	    &bbr_incr_timers, 1,
1679 	    "Increase the RXT/TLP timer by the pacing time used?");
1680 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1681 	    SYSCTL_CHILDREN(bbr_timeout),
1682 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1683 	    &bbr_marks_rxt_sack_passed, 0,
1684 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1685 	/* Policer controls */
1686 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1687 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1688 	    OID_AUTO,
1689 	    "policer",
1690 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1691 	    "Policer controls");
1692 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1693 	    SYSCTL_CHILDREN(bbr_policer),
1694 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1695 	    &bbr_policer_detection_enabled, 1,
1696 	    "Is policer detection enabled??");
1697 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1698 	    SYSCTL_CHILDREN(bbr_policer),
1699 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1700 	    &bbr_lt_intvl_min_rtts, 4,
1701 	    "Minimum number of PE's?");
1702 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1703 	    SYSCTL_CHILDREN(bbr_policer),
1704 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1705 	    &bbr_lt_bw_diff, (4000/8),
1706 	    "Minimal bw diff?");
1707 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1708 	    SYSCTL_CHILDREN(bbr_policer),
1709 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1710 	    &bbr_lt_bw_ratio, 8,
1711 	    "Minimal bw diff?");
1712 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1713 	    SYSCTL_CHILDREN(bbr_policer),
1714 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1715 	    &bbr_policer_call_from_rack_to, 0,
1716 	    "Do we call the policer detection code from a rack-timeout?");
1717 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1718 	    SYSCTL_CHILDREN(bbr_policer),
1719 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1720 	    &bbr_lt_intvl_fp, 0,
1721 	    "What packet epoch do we do false-positive detection at (0=no)?");
1722 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1723 	    SYSCTL_CHILDREN(bbr_policer),
1724 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1725 	    &bbr_lt_loss_thresh, 196,
1726 	    "Loss threshold 196 = 19.6%?");
1727 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1728 	    SYSCTL_CHILDREN(bbr_policer),
1729 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1730 	    &bbr_lt_fd_thresh, 100,
1731 	    "What percentage is the false detection threshold (150=15.0)?");
1732 	/* All the rest */
1733 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1734 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1735 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1736 	    &bbr_use_rack_resend_cheat, 0,
1737 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1738 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1739 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1740 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1741 	    &bbr_error_base_paceout, 10000,
1742 	    "When we hit an error what is the min to pace out in usec's?");
1743 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1744 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1745 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1746 	    &bbr_max_net_error_cnt, 10,
1747 	    "When we hit this many errors in a row, kill the session?");
1748 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1749 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1750 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1751 	    &bbr_ignore_data_after_close, 1,
1752 	    "Do we hold off sending a RST until all pending data is ack'd");
1753 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1754 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1755 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1756 	    &bbr_resends_use_tso, 0,
1757 	    "Can resends use TSO?");
1758 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1759 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1760 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1761 	    &bbr_sack_block_limit, 128,
1762 	    "When do we start ignoring small sack blocks");
1763 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1764 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1765 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1766 	    &bbr_verbose_logging, 0,
1767 	    "Should BBR black box logging be verbose");
1768 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1769 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1770 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1771 	    &bbr_reorder_thresh, 2,
1772 	    "What factor for rack will be added when seeing reordering (shift right)");
1773 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1774 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1775 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1776 	    &bbr_reorder_fade, 0,
1777 	    "Does reorder detection fade, if so how many ms (0 means never)");
1778 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1779 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1780 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1781 	    &bbr_tlp_thresh, 1,
1782 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1783 	/* Stats and counters */
1784 	/* The pacing counters for hdwr/software can't be in the array */
1785 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1786 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1787 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1788 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1789 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1790 	    &bbr_hdwr_pacing_enobuf,
1791 	    "Total number of enobufs for hardware paced flows");
1792 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1793 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1794 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1795 	    &bbr_nohdwr_pacing_enobuf,
1796 	    "Total number of enobufs for non-hardware paced flows");
1797 
1798 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1799 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1800 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1801 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1802 	    &bbr_flows_whdwr_pacing,
1803 	    "Total number of hardware paced flows");
1804 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1805 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1806 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1807 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1808 	    &bbr_flows_nohdwr_pacing,
1809 	    "Total number of software paced flows");
1810 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1811 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1812 	    OID_AUTO, "stats", CTLFLAG_RD,
1813 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1814 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1815 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1816 	    OID_AUTO, "opts", CTLFLAG_RD,
1817 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1818 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1819 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1820 	    OID_AUTO, "lost", CTLFLAG_RD,
1821 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1822 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1823 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1824 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1825 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1826 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1827 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1828 	    OID_AUTO, "statetime", CTLFLAG_RD,
1829 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1830 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1831 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1832 	    OID_AUTO, "outsize", CTLFLAG_RD,
1833 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1834 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1835 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1836 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1837 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1838 }
1839 
1840 static void
1841 bbr_counter_destroy(void)
1842 {
1843 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1844 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1845 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1846 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1847 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1848 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1849 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1850 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1851 	counter_u64_free(bbr_flows_whdwr_pacing);
1852 	counter_u64_free(bbr_flows_nohdwr_pacing);
1853 
1854 }
1855 
1856 static __inline void
1857 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1858 {
1859 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1860 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1861 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1862 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1863 	l->bw_inuse = bbr_get_bw(bbr);
1864 	l->inflight = ctf_flight_size(bbr->rc_tp,
1865 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1866 	l->applimited = bbr->r_ctl.r_app_limited_until;
1867 	l->delivered = bbr->r_ctl.rc_delivered;
1868 	l->timeStamp = cts;
1869 	l->lost = bbr->r_ctl.rc_lost;
1870 	l->bbr_state = bbr->rc_bbr_state;
1871 	l->bbr_substate = bbr_state_val(bbr);
1872 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1873 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1874 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1875 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1876 	l->inhpts = tcp_in_hpts(bbr->rc_tp);
1877 	l->use_lt_bw = bbr->rc_lt_use_bw;
1878 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1879 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1880 }
1881 
1882 static void
1883 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1884 {
1885 	if (tcp_bblogging_on(bbr->rc_tp)) {
1886 		union tcp_log_stackspecific log;
1887 
1888 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1889 		log.u_bbr.flex1 = 0;
1890 		log.u_bbr.flex2 = 0;
1891 		log.u_bbr.flex5 = 0;
1892 		log.u_bbr.flex3 = 0;
1893 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1894 		log.u_bbr.flex7 = reason;
1895 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1896 		log.u_bbr.flex8 = 0;
1897 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1898 		    &bbr->rc_inp->inp_socket->so_rcv,
1899 		    &bbr->rc_inp->inp_socket->so_snd,
1900 		    BBR_LOG_BW_RED_EV, 0,
1901 		    0, &log, false, &bbr->rc_tv);
1902 	}
1903 }
1904 
1905 static void
1906 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1907 {
1908 	if (tcp_bblogging_on(bbr->rc_tp)) {
1909 		union tcp_log_stackspecific log;
1910 
1911 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1912 		log.u_bbr.flex1 = seq;
1913 		log.u_bbr.flex2 = count;
1914 		log.u_bbr.flex8 = mode;
1915 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1916 		    &bbr->rc_inp->inp_socket->so_rcv,
1917 		    &bbr->rc_inp->inp_socket->so_snd,
1918 		    BBR_LOG_LOWGAIN, 0,
1919 		    0, &log, false, &bbr->rc_tv);
1920 	}
1921 }
1922 
1923 static void
1924 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1925     uint8_t reason, uint32_t p_maxseg, int len)
1926 {
1927 	if (tcp_bblogging_on(bbr->rc_tp)) {
1928 		union tcp_log_stackspecific log;
1929 
1930 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1931 		log.u_bbr.flex1 = p_maxseg;
1932 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1933 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1934 		log.u_bbr.flex4 = reason;
1935 		log.u_bbr.flex5 = bbr->rc_in_persist;
1936 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1937 		log.u_bbr.flex7 = p_maxseg;
1938 		log.u_bbr.flex8 = bbr->rc_in_persist;
1939 		log.u_bbr.pkts_out = 0;
1940 		log.u_bbr.applimited = len;
1941 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1942 		    &bbr->rc_inp->inp_socket->so_rcv,
1943 		    &bbr->rc_inp->inp_socket->so_snd,
1944 		    BBR_LOG_JUSTRET, 0,
1945 		    tlen, &log, false, &bbr->rc_tv);
1946 	}
1947 }
1948 
1949 static void
1950 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1951 {
1952 	if (tcp_bblogging_on(bbr->rc_tp)) {
1953 		union tcp_log_stackspecific log;
1954 
1955 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1956 		log.u_bbr.flex1 = seq;
1957 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1958 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1959 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1960 		    &bbr->rc_inp->inp_socket->so_rcv,
1961 		    &bbr->rc_inp->inp_socket->so_snd,
1962 		    BBR_LOG_ENTREC, 0,
1963 		    0, &log, false, &bbr->rc_tv);
1964 	}
1965 }
1966 
1967 static void
1968 bbr_log_msgsize_fail(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t len, uint32_t maxseg, uint32_t mtu, int32_t csum_flags, int32_t tso, uint32_t cts)
1969 {
1970 	if (tcp_bblogging_on(tp)) {
1971 		union tcp_log_stackspecific log;
1972 
1973 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1974 		log.u_bbr.flex1 = tso;
1975 		log.u_bbr.flex2 = maxseg;
1976 		log.u_bbr.flex3 = mtu;
1977 		log.u_bbr.flex4 = csum_flags;
1978 		TCP_LOG_EVENTP(tp, NULL,
1979 		    &bbr->rc_inp->inp_socket->so_rcv,
1980 		    &bbr->rc_inp->inp_socket->so_snd,
1981 		    BBR_LOG_MSGSIZE, 0,
1982 		    0, &log, false, &bbr->rc_tv);
1983 	}
1984 }
1985 
1986 static void
1987 bbr_log_flowend(struct tcp_bbr *bbr)
1988 {
1989 	if (tcp_bblogging_on(bbr->rc_tp)) {
1990 		union tcp_log_stackspecific log;
1991 		struct sockbuf *r, *s;
1992 		struct timeval tv;
1993 
1994 		if (bbr->rc_inp->inp_socket) {
1995 			r = &bbr->rc_inp->inp_socket->so_rcv;
1996 			s = &bbr->rc_inp->inp_socket->so_snd;
1997 		} else {
1998 			r = s = NULL;
1999 		}
2000 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2001 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2002 		    r, s,
2003 		    TCP_LOG_FLOWEND, 0,
2004 		    0, &log, false, &tv);
2005 	}
2006 }
2007 
2008 static void
2009 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2010     uint32_t lost, uint32_t del)
2011 {
2012 	if (tcp_bblogging_on(bbr->rc_tp)) {
2013 		union tcp_log_stackspecific log;
2014 
2015 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2016 		log.u_bbr.flex1 = lost;
2017 		log.u_bbr.flex2 = del;
2018 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2019 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2020 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2021 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2022 		log.u_bbr.flex7 = line;
2023 		log.u_bbr.flex8 = 0;
2024 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2025 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2026 		    &bbr->rc_inp->inp_socket->so_rcv,
2027 		    &bbr->rc_inp->inp_socket->so_snd,
2028 		    BBR_LOG_PKT_EPOCH, 0,
2029 		    0, &log, false, &bbr->rc_tv);
2030 	}
2031 }
2032 
2033 static void
2034 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2035 {
2036 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2037 		union tcp_log_stackspecific log;
2038 
2039 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2040 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2041 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2042 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2043 		log.u_bbr.flex7 = line;
2044 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2045 		    &bbr->rc_inp->inp_socket->so_rcv,
2046 		    &bbr->rc_inp->inp_socket->so_snd,
2047 		    BBR_LOG_TIME_EPOCH, 0,
2048 		    0, &log, false, &bbr->rc_tv);
2049 	}
2050 }
2051 
2052 static void
2053 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2054 {
2055 	if (tcp_bblogging_on(bbr->rc_tp)) {
2056 		union tcp_log_stackspecific log;
2057 
2058 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2059 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2060 		log.u_bbr.flex2 = new_tar;
2061 		log.u_bbr.flex3 = line;
2062 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2063 		log.u_bbr.flex5 = bbr_quanta;
2064 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2065 		log.u_bbr.flex7 = bbr->rc_last_options;
2066 		log.u_bbr.flex8 = meth;
2067 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2068 		    &bbr->rc_inp->inp_socket->so_rcv,
2069 		    &bbr->rc_inp->inp_socket->so_snd,
2070 		    BBR_LOG_STATE_TARGET, 0,
2071 		    0, &log, false, &bbr->rc_tv);
2072 	}
2073 
2074 }
2075 
2076 static void
2077 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2078 {
2079 	if (tcp_bblogging_on(bbr->rc_tp)) {
2080 		union tcp_log_stackspecific log;
2081 
2082 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2083 		log.u_bbr.flex1 = line;
2084 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2085 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2086 		if (bbr_state_is_pkt_epoch)
2087 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2088 		else
2089 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2090 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2091 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2092 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2093 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2094 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2095 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2096 		    &bbr->rc_inp->inp_socket->so_rcv,
2097 		    &bbr->rc_inp->inp_socket->so_snd,
2098 		    BBR_LOG_STATE, 0,
2099 		    0, &log, false, &bbr->rc_tv);
2100 	}
2101 }
2102 
2103 static void
2104 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2105 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2106 {
2107 	if (tcp_bblogging_on(bbr->rc_tp)) {
2108 		union tcp_log_stackspecific log;
2109 
2110 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2111 		log.u_bbr.flex1 = line;
2112 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2113 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2114 		log.u_bbr.flex4 = applied;
2115 		log.u_bbr.flex5 = rtt;
2116 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2117 		log.u_bbr.flex7 = cond;
2118 		log.u_bbr.flex8 = reas;
2119 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2120 		    &bbr->rc_inp->inp_socket->so_rcv,
2121 		    &bbr->rc_inp->inp_socket->so_snd,
2122 		    BBR_LOG_RTT_SHRINKS, 0,
2123 		    0, &log, false, &bbr->rc_tv);
2124 	}
2125 }
2126 
2127 static void
2128 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2129 {
2130 	if (tcp_bblogging_on(bbr->rc_tp)) {
2131 		union tcp_log_stackspecific log;
2132 
2133 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2134 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2135 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2136 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2137 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2138 		    &bbr->rc_inp->inp_socket->so_rcv,
2139 		    &bbr->rc_inp->inp_socket->so_snd,
2140 		    BBR_LOG_EXITREC, 0,
2141 		    0, &log, false, &bbr->rc_tv);
2142 	}
2143 }
2144 
2145 static void
2146 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2147     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2148 {
2149 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2150 		union tcp_log_stackspecific log;
2151 
2152 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2153 		log.u_bbr.flex1 = line;
2154 		log.u_bbr.flex2 = prev_acked;
2155 		log.u_bbr.flex3 = bytes_this_ack;
2156 		log.u_bbr.flex4 = chg;
2157 		log.u_bbr.flex5 = th_ack;
2158 		log.u_bbr.flex6 = target;
2159 		log.u_bbr.flex8 = meth;
2160 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2161 		    &bbr->rc_inp->inp_socket->so_rcv,
2162 		    &bbr->rc_inp->inp_socket->so_snd,
2163 		    BBR_LOG_CWND, 0,
2164 		    0, &log, false, &bbr->rc_tv);
2165 	}
2166 }
2167 
2168 static void
2169 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2170 {
2171 	/*
2172 	 * Log the rtt sample we are applying to the srtt algorithm in
2173 	 * useconds.
2174 	 */
2175 	if (tcp_bblogging_on(bbr->rc_tp)) {
2176 		union tcp_log_stackspecific log;
2177 
2178 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2179 		log.u_bbr.flex1 = rtt;
2180 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2181 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2182 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2183 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2184 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2185 		log.u_bbr.flex6 = tsin;
2186 		log.u_bbr.flex7 = 0;
2187 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2188 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2189 		    &bbr->rc_inp->inp_socket->so_rcv,
2190 		    &bbr->rc_inp->inp_socket->so_snd,
2191 		    TCP_LOG_RTT, 0,
2192 		    0, &log, false, &bbr->rc_tv);
2193 	}
2194 }
2195 
2196 static void
2197 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2198 {
2199 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2200 		union tcp_log_stackspecific log;
2201 
2202 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2203 		log.u_bbr.flex1 = time_in;
2204 		log.u_bbr.flex2 = line;
2205 		log.u_bbr.flex8 = enter_exit;
2206 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2207 		    &bbr->rc_inp->inp_socket->so_rcv,
2208 		    &bbr->rc_inp->inp_socket->so_snd,
2209 		    BBR_LOG_PERSIST, 0,
2210 		    0, &log, false, &bbr->rc_tv);
2211 	}
2212 }
2213 static void
2214 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2215 {
2216 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2217 		union tcp_log_stackspecific log;
2218 
2219 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2220 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2221 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2222 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2223 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2224 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2225 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2226 		    &bbr->rc_inp->inp_socket->so_rcv,
2227 		    &bbr->rc_inp->inp_socket->so_snd,
2228 		    BBR_LOG_ACKCLEAR, 0,
2229 		    0, &log, false, &bbr->rc_tv);
2230 	}
2231 }
2232 
2233 static void
2234 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2235 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2236 {
2237 	if (tcp_bblogging_on(bbr->rc_tp)) {
2238 		union tcp_log_stackspecific log;
2239 		struct timeval tv;
2240 
2241 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2242 		log.u_bbr.flex1 = nsegs;
2243 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2244 		if (m) {
2245 			struct timespec ts;
2246 
2247 			log.u_bbr.flex3 = m->m_flags;
2248 			if (m->m_flags & M_TSTMP) {
2249 				mbuf_tstmp2timespec(m, &ts);
2250 				tv.tv_sec = ts.tv_sec;
2251 				tv.tv_usec = ts.tv_nsec / 1000;
2252 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2253 			} else {
2254 				log.u_bbr.lt_epoch = 0;
2255 			}
2256 			if (m->m_flags & M_TSTMP_LRO) {
2257 				mbuf_tstmp2timeval(m, &tv);
2258 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2259 			} else {
2260 				/* No arrival timestamp */
2261 				log.u_bbr.flex5 = 0;
2262 			}
2263 
2264 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2265 		} else {
2266 			log.u_bbr.flex3 = 0;
2267 			log.u_bbr.flex5 = 0;
2268 			log.u_bbr.flex6 = 0;
2269 			log.u_bbr.pkts_out = 0;
2270 		}
2271 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2272 		log.u_bbr.flex7 = bbr->r_wanted_output;
2273 		log.u_bbr.flex8 = bbr->rc_in_persist;
2274 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2275 		    &bbr->rc_inp->inp_socket->so_rcv,
2276 		    &bbr->rc_inp->inp_socket->so_snd,
2277 		    TCP_LOG_IN, 0,
2278 		    tlen, &log, true, &bbr->rc_tv);
2279 	}
2280 }
2281 
2282 static void
2283 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2284 {
2285 	if (tcp_bblogging_on(bbr->rc_tp)) {
2286 		union tcp_log_stackspecific log;
2287 
2288 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2289 		log.u_bbr.flex1 = did_out;
2290 		log.u_bbr.flex2 = nxt_pkt;
2291 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2292 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2293 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2294 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2295 		log.u_bbr.flex7 = bbr->r_wanted_output;
2296 		log.u_bbr.flex8 = bbr->rc_in_persist;
2297 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2298 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2299 		    &bbr->rc_inp->inp_socket->so_rcv,
2300 		    &bbr->rc_inp->inp_socket->so_snd,
2301 		    BBR_LOG_DOSEG_DONE, 0,
2302 		    0, &log, true, &bbr->rc_tv);
2303 	}
2304 }
2305 
2306 static void
2307 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2308     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2309 {
2310 	if (tcp_bblogging_on(bbr->rc_tp)) {
2311 		union tcp_log_stackspecific log;
2312 
2313 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2314 		log.u_bbr.flex1 = line;
2315 		log.u_bbr.flex2 = o_len;
2316 		log.u_bbr.flex3 = segcnt;
2317 		log.u_bbr.flex4 = segsiz;
2318 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2319 		    &bbr->rc_inp->inp_socket->so_rcv,
2320 		    &bbr->rc_inp->inp_socket->so_snd,
2321 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2322 		    len, &log, true, &bbr->rc_tv);
2323 	}
2324 }
2325 
2326 static void
2327 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2328 {
2329 	if (tcp_bblogging_on(bbr->rc_tp)) {
2330 		union tcp_log_stackspecific log;
2331 
2332 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2333 		log.u_bbr.flex1 = timers;
2334 		log.u_bbr.flex2 = ret;
2335 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2336 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2337 		log.u_bbr.flex5 = cts;
2338 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2339 		log.u_bbr.flex8 = hpts_calling;
2340 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2341 		    &bbr->rc_inp->inp_socket->so_rcv,
2342 		    &bbr->rc_inp->inp_socket->so_snd,
2343 		    BBR_LOG_TO_PROCESS, 0,
2344 		    0, &log, false, &bbr->rc_tv);
2345 	}
2346 }
2347 
2348 static void
2349 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2350 {
2351 	if (tcp_bblogging_on(bbr->rc_tp)) {
2352 		union tcp_log_stackspecific log;
2353 		uint64_t ar;
2354 
2355 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2356 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2357 		log.u_bbr.flex2 = 0;
2358 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2359 		ar = (uint64_t)(bbr->r_ctl.rc_resend);
2360 		ar >>= 32;
2361 		ar &= 0x00000000ffffffff;
2362 		log.u_bbr.flex4 = (uint32_t)ar;
2363 		ar = (uint64_t)bbr->r_ctl.rc_resend;
2364 		ar &= 0x00000000ffffffff;
2365 		log.u_bbr.flex5 = (uint32_t)ar;
2366 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2367 		log.u_bbr.flex8 = to_num;
2368 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2369 		    &bbr->rc_inp->inp_socket->so_rcv,
2370 		    &bbr->rc_inp->inp_socket->so_snd,
2371 		    BBR_LOG_RTO, 0,
2372 		    0, &log, false, &bbr->rc_tv);
2373 	}
2374 }
2375 
2376 static void
2377 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2378 {
2379 	if (tcp_bblogging_on(bbr->rc_tp)) {
2380 		union tcp_log_stackspecific log;
2381 
2382 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2383 		log.u_bbr.flex1 = flex1;
2384 		log.u_bbr.flex2 = flex2;
2385 		log.u_bbr.flex3 = flex3;
2386 		log.u_bbr.flex4 = 0;
2387 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2388 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2389 		log.u_bbr.flex8 = reason;
2390 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2391 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2392 		    &bbr->rc_inp->inp_socket->so_rcv,
2393 		    &bbr->rc_inp->inp_socket->so_snd,
2394 		    BBR_LOG_REDUCE, 0,
2395 		    0, &log, false, &bbr->rc_tv);
2396 	}
2397 }
2398 
2399 static void
2400 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2401 {
2402 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2403 		union tcp_log_stackspecific log;
2404 
2405 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2406 		log.u_bbr.flex1 = diag->p_nxt_slot;
2407 		log.u_bbr.flex2 = diag->p_cur_slot;
2408 		log.u_bbr.flex3 = diag->slot_req;
2409 		log.u_bbr.flex4 = diag->inp_hptsslot;
2410 		log.u_bbr.flex5 = diag->slot_remaining;
2411 		log.u_bbr.flex6 = diag->need_new_to;
2412 		log.u_bbr.flex7 = diag->p_hpts_active;
2413 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2414 		/* Hijack other fields as needed  */
2415 		log.u_bbr.epoch = diag->have_slept;
2416 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2417 		log.u_bbr.pkts_out = diag->co_ret;
2418 		log.u_bbr.applimited = diag->hpts_sleep_time;
2419 		log.u_bbr.delivered = diag->p_prev_slot;
2420 		log.u_bbr.inflight = diag->p_runningslot;
2421 		log.u_bbr.bw_inuse = diag->wheel_slot;
2422 		log.u_bbr.rttProp = diag->wheel_cts;
2423 		log.u_bbr.delRate = diag->maxslots;
2424 		log.u_bbr.cur_del_rate = diag->p_curtick;
2425 		log.u_bbr.cur_del_rate <<= 32;
2426 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2427 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2428 		    &bbr->rc_inp->inp_socket->so_rcv,
2429 		    &bbr->rc_inp->inp_socket->so_snd,
2430 		    BBR_LOG_HPTSDIAG, 0,
2431 		    0, &log, false, &bbr->rc_tv);
2432 	}
2433 }
2434 
2435 static void
2436 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2437     uint32_t thresh, uint32_t to)
2438 {
2439 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2440 		union tcp_log_stackspecific log;
2441 
2442 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2443 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2444 		log.u_bbr.flex2 = time_since_sent;
2445 		log.u_bbr.flex3 = srtt;
2446 		log.u_bbr.flex4 = thresh;
2447 		log.u_bbr.flex5 = to;
2448 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2449 		log.u_bbr.flex8 = mode;
2450 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2451 		    &bbr->rc_inp->inp_socket->so_rcv,
2452 		    &bbr->rc_inp->inp_socket->so_snd,
2453 		    BBR_LOG_TIMERPREP, 0,
2454 		    0, &log, false, &bbr->rc_tv);
2455 	}
2456 }
2457 
2458 static void
2459 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2460     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2461 {
2462 	if (tcp_bblogging_on(bbr->rc_tp)) {
2463 		union tcp_log_stackspecific log;
2464 
2465 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2466 		log.u_bbr.flex1 = usecs;
2467 		log.u_bbr.flex2 = len;
2468 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2469 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2470 		if (override)
2471 			log.u_bbr.flex5 = (1 << 2);
2472 		else
2473 			log.u_bbr.flex5 = 0;
2474 		log.u_bbr.flex6 = override;
2475 		log.u_bbr.flex7 = gain;
2476 		log.u_bbr.flex8 = mod;
2477 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2478 		    &bbr->rc_inp->inp_socket->so_rcv,
2479 		    &bbr->rc_inp->inp_socket->so_snd,
2480 		    BBR_LOG_HPTSI_CALC, 0,
2481 		    len, &log, false, &bbr->rc_tv);
2482 	}
2483 }
2484 
2485 static void
2486 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2487 {
2488 	if (tcp_bblogging_on(bbr->rc_tp)) {
2489 		union tcp_log_stackspecific log;
2490 
2491 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2492 
2493 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2494 		log.u_bbr.flex2 = to;
2495 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2496 		log.u_bbr.flex4 = slot;
2497 		log.u_bbr.flex5 = bbr->rc_tp->t_hpts_slot;
2498 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2499 		log.u_bbr.pkts_out = bbr->rc_tp->t_flags2;
2500 		log.u_bbr.flex8 = which;
2501 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2502 		    &bbr->rc_inp->inp_socket->so_rcv,
2503 		    &bbr->rc_inp->inp_socket->so_snd,
2504 		    BBR_LOG_TIMERSTAR, 0,
2505 		    0, &log, false, &bbr->rc_tv);
2506 	}
2507 }
2508 
2509 static void
2510 bbr_log_thresh_choice(struct tcp_bbr *bbr, uint32_t cts, uint32_t thresh, uint32_t lro, uint32_t srtt, struct bbr_sendmap *rsm, uint8_t frm)
2511 {
2512 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2513 		union tcp_log_stackspecific log;
2514 
2515 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2516 		log.u_bbr.flex1 = thresh;
2517 		log.u_bbr.flex2 = lro;
2518 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2519 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2520 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2521 		log.u_bbr.flex6 = srtt;
2522 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2523 		log.u_bbr.flex8 = frm;
2524 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2525 		    &bbr->rc_inp->inp_socket->so_rcv,
2526 		    &bbr->rc_inp->inp_socket->so_snd,
2527 		    BBR_LOG_THRESH_CALC, 0,
2528 		    0, &log, false, &bbr->rc_tv);
2529 	}
2530 }
2531 
2532 static void
2533 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2534 {
2535 	if (tcp_bblogging_on(bbr->rc_tp)) {
2536 		union tcp_log_stackspecific log;
2537 
2538 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2539 		log.u_bbr.flex1 = line;
2540 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2541 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2542 		log.u_bbr.flex4 = bbr->rc_in_persist;
2543 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2544 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2545 		log.u_bbr.flex8 = hpts_removed;
2546 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2547 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2548 		    &bbr->rc_inp->inp_socket->so_rcv,
2549 		    &bbr->rc_inp->inp_socket->so_snd,
2550 		    BBR_LOG_TIMERCANC, 0,
2551 		    0, &log, false, &bbr->rc_tv);
2552 	}
2553 }
2554 
2555 static void
2556 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2557 {
2558 	if (tcp_bblogging_on(bbr->rc_tp)) {
2559 		union tcp_log_stackspecific log;
2560 
2561 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2562 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2563 		log.u_bbr.flex2 = (peer_delta >> 32);
2564 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2565 		log.u_bbr.flex4 = (delta >> 32);
2566 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2567 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2568 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2569 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2570 		    &bbr->rc_inp->inp_socket->so_rcv,
2571 		    &bbr->rc_inp->inp_socket->so_snd,
2572 		    BBR_LOG_TSTMP_VAL, 0,
2573 		    0, &log, false, &bbr->rc_tv);
2574 	}
2575 }
2576 
2577 static void
2578 bbr_log_type_tsosize(struct tcp_bbr *bbr, uint32_t cts, uint32_t tsosz, uint32_t tls, uint32_t old_val, uint32_t maxseg, int hdwr)
2579 {
2580 	if (tcp_bblogging_on(bbr->rc_tp)) {
2581 		union tcp_log_stackspecific log;
2582 
2583 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2584 		log.u_bbr.flex1 = tsosz;
2585 		log.u_bbr.flex2 = tls;
2586 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2587 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2588 		log.u_bbr.flex5 = old_val;
2589 		log.u_bbr.flex6 = maxseg;
2590 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2591 		log.u_bbr.flex7 <<= 1;
2592 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2593 		if (hdwr)
2594 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2595 		else
2596 			log.u_bbr.flex8 = bbr->rc_use_google;
2597 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2598 		    &bbr->rc_inp->inp_socket->so_rcv,
2599 		    &bbr->rc_inp->inp_socket->so_snd,
2600 		    BBR_LOG_BBRTSO, 0,
2601 		    0, &log, false, &bbr->rc_tv);
2602 	}
2603 }
2604 
2605 static void
2606 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2607 		      uint32_t flags, uint32_t line)
2608 {
2609 	if (tcp_bblogging_on(bbr->rc_tp)) {
2610 		union tcp_log_stackspecific log;
2611 
2612 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2613 		log.u_bbr.flex1 = line;
2614 		log.u_bbr.flex2 = rsm->r_start;
2615 		log.u_bbr.flex3 = rsm->r_end;
2616 		log.u_bbr.flex4 = rsm->r_delivered;
2617 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2618 		log.u_bbr.flex6 = rsm->r_dupack;
2619 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2620 		log.u_bbr.flex8 = rsm->r_flags;
2621 		/* Hijack the pkts_out fids */
2622 		log.u_bbr.applimited = flags;
2623 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2624 		    &bbr->rc_inp->inp_socket->so_rcv,
2625 		    &bbr->rc_inp->inp_socket->so_snd,
2626 		    BBR_RSM_CLEARED, 0,
2627 		    0, &log, false, &bbr->rc_tv);
2628 	}
2629 }
2630 
2631 static void
2632 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2633     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2634     uint32_t flex6, uint32_t pkts_out, int flex7,
2635     uint32_t flex4, uint32_t flex1)
2636 {
2637 
2638 	if (tcp_bblogging_on(bbr->rc_tp)) {
2639 		union tcp_log_stackspecific log;
2640 
2641 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2642 		log.u_bbr.flex1 = flex1;
2643 		log.u_bbr.flex2 = flex2;
2644 		log.u_bbr.flex3 = flex3;
2645 		log.u_bbr.flex4 = flex4;
2646 		log.u_bbr.flex5 = flex5;
2647 		log.u_bbr.flex6 = flex6;
2648 		log.u_bbr.flex7 = flex7;
2649 		/* Hijack the pkts_out fids */
2650 		log.u_bbr.pkts_out = pkts_out;
2651 		log.u_bbr.flex8 = flex8;
2652 		if (bbr->rc_ack_was_delayed)
2653 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2654 		else
2655 			log.u_bbr.epoch = 0;
2656 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2657 		    &bbr->rc_inp->inp_socket->so_rcv,
2658 		    &bbr->rc_inp->inp_socket->so_snd,
2659 		    BBR_LOG_BBRUPD, 0,
2660 		    flex2, &log, false, &bbr->rc_tv);
2661 	}
2662 }
2663 
2664 static void
2665 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2666 	uint32_t newbw, uint32_t obw, uint32_t diff,
2667 	uint32_t tim)
2668 {
2669 	if (/*bbr_verbose_logging && */tcp_bblogging_on(bbr->rc_tp)) {
2670 		union tcp_log_stackspecific log;
2671 
2672 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2673 		log.u_bbr.flex1 = reason;
2674 		log.u_bbr.flex2 = newbw;
2675 		log.u_bbr.flex3 = obw;
2676 		log.u_bbr.flex4 = diff;
2677 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2678 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2679 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2680 		log.u_bbr.pkts_out = tim;
2681 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2682 		if (bbr->rc_lt_use_bw == 0)
2683 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2684 		else
2685 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2686 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2687 		    &bbr->rc_inp->inp_socket->so_rcv,
2688 		    &bbr->rc_inp->inp_socket->so_snd,
2689 		    BBR_LOG_BWSAMP, 0,
2690 		    0, &log, false, &bbr->rc_tv);
2691 	}
2692 }
2693 
2694 static inline void
2695 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2696 {
2697 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2698 		union tcp_log_stackspecific log;
2699 
2700 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2701 		log.u_bbr.flex1 = line;
2702 		log.u_bbr.flex2 = tick;
2703 		log.u_bbr.flex3 = tp->t_maxunacktime;
2704 		log.u_bbr.flex4 = tp->t_acktime;
2705 		log.u_bbr.flex8 = event;
2706 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2707 		    &bbr->rc_inp->inp_socket->so_rcv,
2708 		    &bbr->rc_inp->inp_socket->so_snd,
2709 		    BBR_LOG_PROGRESS, 0,
2710 		    0, &log, false, &bbr->rc_tv);
2711 	}
2712 }
2713 
2714 static void
2715 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2716 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2717 			 int error)
2718 {
2719 	if (tcp_bblogging_on(bbr->rc_tp)) {
2720 		union tcp_log_stackspecific log;
2721 
2722 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2723 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2724 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2725 		log.u_bbr.flex3 = (((uint64_t)ifp  >> 32) & 0x00000000ffffffff);
2726 		log.u_bbr.flex4 = ((uint64_t)ifp & 0x00000000ffffffff);
2727 		log.u_bbr.bw_inuse = rate;
2728 		log.u_bbr.flex5 = line;
2729 		log.u_bbr.flex6 = error;
2730 		log.u_bbr.flex8 = bbr->skip_gain;
2731 		log.u_bbr.flex8 <<= 1;
2732 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2733 		log.u_bbr.flex8 <<= 1;
2734 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2735 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2736 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2737 		    &bbr->rc_inp->inp_socket->so_rcv,
2738 		    &bbr->rc_inp->inp_socket->so_snd,
2739 		    BBR_LOG_HDWR_PACE, 0,
2740 		    0, &log, false, &bbr->rc_tv);
2741 	}
2742 }
2743 
2744 static void
2745 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)
2746 {
2747 	if (tcp_bblogging_on(bbr->rc_tp)) {
2748 		union tcp_log_stackspecific log;
2749 
2750 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2751 		log.u_bbr.flex1 = slot;
2752 		log.u_bbr.flex2 = del_by;
2753 		log.u_bbr.flex3 = prev_delay;
2754 		log.u_bbr.flex4 = line;
2755 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2756 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2757 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2758 		log.u_bbr.flex8 = bbr->rc_in_persist;
2759 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2760 		    &bbr->rc_inp->inp_socket->so_rcv,
2761 		    &bbr->rc_inp->inp_socket->so_snd,
2762 		    BBR_LOG_BBRSND, 0,
2763 		    len, &log, false, &bbr->rc_tv);
2764 	}
2765 }
2766 
2767 static void
2768 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)
2769 {
2770 	if (tcp_bblogging_on(bbr->rc_tp)) {
2771 		union tcp_log_stackspecific log;
2772 
2773 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2774 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2775 		log.u_bbr.flex2 = 0;
2776 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2777 		log.u_bbr.flex4 = end;
2778 		log.u_bbr.flex5 = seq;
2779 		log.u_bbr.flex6 = t;
2780 		log.u_bbr.flex7 = match;
2781 		log.u_bbr.flex8 = flags;
2782 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2783 		    &bbr->rc_inp->inp_socket->so_rcv,
2784 		    &bbr->rc_inp->inp_socket->so_snd,
2785 		    BBR_LOG_BBRRTT, 0,
2786 		    0, &log, false, &bbr->rc_tv);
2787 	}
2788 }
2789 
2790 static void
2791 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2792 {
2793 	if (tcp_bblogging_on(bbr->rc_tp)) {
2794 		union tcp_log_stackspecific log;
2795 
2796 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2797 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2798 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2799 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2800 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2801 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2802 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2803 		log.u_bbr.flex7 = 0;
2804 		log.u_bbr.flex8 = entry_method;
2805 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2806 		    &bbr->rc_inp->inp_socket->so_rcv,
2807 		    &bbr->rc_inp->inp_socket->so_snd,
2808 		    BBR_LOG_EXIT_GAIN, 0,
2809 		    0, &log, false, &bbr->rc_tv);
2810 	}
2811 }
2812 
2813 static void
2814 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2815 {
2816 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2817 		union tcp_log_stackspecific log;
2818 
2819 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2820 		/* R-HU */
2821 		log.u_bbr.flex1 = 0;
2822 		log.u_bbr.flex2 = 0;
2823 		log.u_bbr.flex3 = 0;
2824 		log.u_bbr.flex4 = 0;
2825 		log.u_bbr.flex7 = 0;
2826 		log.u_bbr.flex8 = settings_desired;
2827 
2828 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2829 		    &bbr->rc_inp->inp_socket->so_rcv,
2830 		    &bbr->rc_inp->inp_socket->so_snd,
2831 		    BBR_LOG_SETTINGS_CHG, 0,
2832 		    0, &log, false, &bbr->rc_tv);
2833 	}
2834 }
2835 
2836 /*
2837  * Returns the bw from the our filter.
2838  */
2839 static inline uint64_t
2840 bbr_get_full_bw(struct tcp_bbr *bbr)
2841 {
2842 	uint64_t bw;
2843 
2844 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2845 
2846 	return (bw);
2847 }
2848 
2849 static inline void
2850 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2851 {
2852 	uint64_t calclr;
2853 	uint32_t lost, del;
2854 
2855 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2856 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2857 	else
2858 		lost = 0;
2859 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2860 	if (lost == 0)  {
2861 		calclr = 0;
2862 	} else if (del) {
2863 		calclr = lost;
2864 		calclr *= (uint64_t)1000;
2865 		calclr /= (uint64_t)del;
2866 	} else {
2867 		/* Nothing delivered? 100.0% loss */
2868 		calclr = 1000;
2869 	}
2870 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2871 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2872 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2873 	bbr->r_ctl.rc_pkt_epoch++;
2874 	if (bbr->rc_no_pacing &&
2875 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2876 		bbr->rc_no_pacing = 0;
2877 		tcp_bbr_tso_size_check(bbr, cts);
2878 	}
2879 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2880 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2881 	/* What was our loss rate */
2882 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2883 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2884 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2885 }
2886 
2887 static inline void
2888 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2889 {
2890 	uint32_t epoch_time;
2891 
2892 	/* Tick the RTT clock */
2893 	bbr->r_ctl.rc_rtt_epoch++;
2894 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2895 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2896 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2897 }
2898 
2899 static inline void
2900 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2901 {
2902 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2903 		bbr->rc_is_pkt_epoch_now = 1;
2904 	}
2905 }
2906 
2907 /*
2908  * Returns the bw from either the b/w filter
2909  * or from the lt_bw (if the connection is being
2910  * policed).
2911  */
2912 static inline uint64_t
2913 __bbr_get_bw(struct tcp_bbr *bbr)
2914 {
2915 	uint64_t bw, min_bw;
2916 	uint64_t rtt;
2917 	int gm_measure_cnt = 1;
2918 
2919 	/*
2920 	 * For startup we make, like google, a
2921 	 * minimum b/w. This is generated from the
2922 	 * IW and the rttProp. We do fall back to srtt
2923 	 * if for some reason (initial handshake) we don't
2924 	 * have a rttProp. We, in the worst case, fall back
2925 	 * to the configured min_bw (rc_initial_hptsi_bw).
2926 	 */
2927 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2928 		/* Attempt first to use rttProp */
2929 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2930 		if (rtt && (rtt < 0xffffffff)) {
2931 measure:
2932 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2933 				((uint64_t)1000000);
2934 			min_bw /= rtt;
2935 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2936 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2937 			}
2938 
2939 		} else if (bbr->rc_tp->t_srtt != 0) {
2940 			/* No rttProp, use srtt? */
2941 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2942 			goto measure;
2943 		} else {
2944 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2945 		}
2946 	} else
2947 		min_bw = 0;
2948 
2949 	if ((bbr->rc_past_init_win == 0) &&
2950 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2951 		bbr->rc_past_init_win = 1;
2952 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2953 		gm_measure_cnt = 0;
2954 	if (gm_measure_cnt &&
2955 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2956 	     (bbr->rc_past_init_win == 0))) {
2957 		/* For google we use our guess rate until we get 1 measurement */
2958 
2959 use_initial_window:
2960 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2961 		if (rtt && (rtt < 0xffffffff)) {
2962 			/*
2963 			 * We have an RTT measurement. Use that in
2964 			 * combination with our initial window to calculate
2965 			 * a b/w.
2966 			 */
2967 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2968 				((uint64_t)1000000);
2969 			bw /= rtt;
2970 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2971 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2972 			}
2973 		} else {
2974 			/* Drop back to the 40 and punt to a default */
2975 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2976 		}
2977 		if (bw < 1)
2978 			/* Probably should panic */
2979 			bw = 1;
2980 		if (bw > min_bw)
2981 			return (bw);
2982 		else
2983 			return (min_bw);
2984 	}
2985 	if (bbr->rc_lt_use_bw)
2986 		bw = bbr->r_ctl.rc_lt_bw;
2987 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2988 		bw = bbr->r_ctl.red_bw;
2989 	else
2990 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2991 	if (bw == 0) {
2992 		/* We should not be at 0, go to the initial window then  */
2993 		goto use_initial_window;
2994 	}
2995 	if (bw < 1)
2996 		/* Probably should panic */
2997 		bw = 1;
2998 	if (bw < min_bw)
2999 		bw = min_bw;
3000 	return (bw);
3001 }
3002 
3003 static inline uint64_t
3004 bbr_get_bw(struct tcp_bbr *bbr)
3005 {
3006 	uint64_t bw;
3007 
3008 	bw = __bbr_get_bw(bbr);
3009 	return (bw);
3010 }
3011 
3012 static inline void
3013 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3014 {
3015 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3016 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3017 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3018 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3019 }
3020 
3021 static inline void
3022 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3023 {
3024 	bbr->rc_lt_is_sampling = 0;
3025 	bbr->rc_lt_use_bw = 0;
3026 	bbr->r_ctl.rc_lt_bw = 0;
3027 	bbr_reset_lt_bw_interval(bbr, cts);
3028 }
3029 
3030 static inline void
3031 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3032 {
3033 	uint64_t diff;
3034 
3035 	/* Do we have a previous sample? */
3036 	if (bbr->r_ctl.rc_lt_bw) {
3037 		/* Get the diff in bytes per second */
3038 		if (bbr->r_ctl.rc_lt_bw > bw)
3039 			diff = bbr->r_ctl.rc_lt_bw - bw;
3040 		else
3041 			diff = bw - bbr->r_ctl.rc_lt_bw;
3042 		if ((diff <= bbr_lt_bw_diff) ||
3043 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3044 			/* Consider us policed */
3045 			uint32_t saved_bw;
3046 
3047 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3048 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3049 			bbr->rc_lt_use_bw = 1;
3050 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3051 			/*
3052 			 * Use pkt based epoch for measuring length of
3053 			 * policer up
3054 			 */
3055 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3056 			/*
3057 			 * reason 4 is we need to start consider being
3058 			 * policed
3059 			 */
3060 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3061 			return;
3062 		}
3063 	}
3064 	bbr->r_ctl.rc_lt_bw = bw;
3065 	bbr_reset_lt_bw_interval(bbr, cts);
3066 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3067 }
3068 
3069 static void
3070 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3071 {
3072 	uint32_t ran, deduct;
3073 
3074 	ran = arc4random_uniform(bbr_rand_ot);
3075 	if (ran) {
3076 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3077 		bbr->r_ctl.rc_level_state_extra -= deduct;
3078 	}
3079 }
3080 /*
3081  * Return randomly the starting state
3082  * to use in probebw.
3083  */
3084 static uint8_t
3085 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3086 {
3087 	uint32_t ran;
3088 	uint8_t ret_val;
3089 
3090 	/* Initialize the offset to 0 */
3091 	bbr->r_ctl.rc_exta_time_gd = 0;
3092 	bbr->rc_hit_state_1 = 0;
3093 	bbr->r_ctl.rc_level_state_extra = 0;
3094 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3095 	/*
3096 	 * The math works funny here :) the return value is used to set the
3097 	 * substate and then the state change is called which increments by
3098 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3099 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3100 	 * we return 1 - 7, so we dont return 0 and end up starting in
3101 	 * state 1 (DRAIN).
3102 	 */
3103 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3104 	/* Set an epoch */
3105 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3106 		bbr_set_epoch(bbr, cts, __LINE__);
3107 
3108 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3109 	return (ret_val);
3110 }
3111 
3112 static void
3113 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3114 {
3115 	uint32_t diff, d_time;
3116 	uint64_t del_time, bw, lost, delivered;
3117 
3118 	if (bbr->r_use_policer == 0)
3119 		return;
3120 	if (bbr->rc_lt_use_bw) {
3121 		/* We are using lt bw do we stop yet? */
3122 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3123 		if (diff > bbr_lt_bw_max_rtts) {
3124 			/* Reset it all */
3125 reset_all:
3126 			bbr_reset_lt_bw_sampling(bbr, cts);
3127 			if (bbr->rc_filled_pipe) {
3128 				bbr_set_epoch(bbr, cts, __LINE__);
3129 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3130 				bbr_substate_change(bbr, cts, __LINE__, 0);
3131 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3132 				bbr_log_type_statechange(bbr, cts, __LINE__);
3133 			} else {
3134 				/*
3135 				 * This should not happen really
3136 				 * unless we remove the startup/drain
3137 				 * restrictions above.
3138 				 */
3139 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3140 				bbr_set_epoch(bbr, cts, __LINE__);
3141 				bbr->r_ctl.rc_bbr_state_time = cts;
3142 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3143 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3144 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3145 				bbr_set_state_target(bbr, __LINE__);
3146 				bbr_log_type_statechange(bbr, cts, __LINE__);
3147 			}
3148 			/* reason 0 is to stop using lt-bw */
3149 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3150 			return;
3151 		}
3152 		if (bbr_lt_intvl_fp == 0) {
3153 			/* Not doing false-positive detection */
3154 			return;
3155 		}
3156 		/* False positive detection */
3157 		if (diff == bbr_lt_intvl_fp) {
3158 			/* At bbr_lt_intvl_fp we record the lost */
3159 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3160 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3161 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3162 			/* Now is our loss rate still high? */
3163 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3164 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3165 			if ((delivered == 0) ||
3166 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3167 				/* No still below our threshold */
3168 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3169 			} else {
3170 				/* Yikes its still high, it must be a false positive */
3171 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3172 				goto reset_all;
3173 			}
3174 		}
3175 		return;
3176 	}
3177 	/*
3178 	 * Wait for the first loss before sampling, to let the policer
3179 	 * exhaust its tokens and estimate the steady-state rate allowed by
3180 	 * the policer. Starting samples earlier includes bursts that
3181 	 * over-estimate the bw.
3182 	 */
3183 	if (bbr->rc_lt_is_sampling == 0) {
3184 		/* reason 1 is to begin doing the sampling  */
3185 		if (loss_detected == 0)
3186 			return;
3187 		bbr_reset_lt_bw_interval(bbr, cts);
3188 		bbr->rc_lt_is_sampling = 1;
3189 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3190 		return;
3191 	}
3192 	/* Now how long were we delivering long term last> */
3193 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3194 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3195 	else
3196 		d_time = 0;
3197 
3198 	/* To avoid underestimates, reset sampling if we run out of data. */
3199 	if (bbr->r_ctl.r_app_limited_until) {
3200 		/* Can not measure in app-limited state */
3201 		bbr_reset_lt_bw_sampling(bbr, cts);
3202 		/* reason 2 is to reset sampling due to app limits  */
3203 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3204 		return;
3205 	}
3206 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3207 	if (diff < bbr_lt_intvl_min_rtts) {
3208 		/*
3209 		 * need more samples (we don't
3210 		 * start on a round like linux so
3211 		 * we need 1 more).
3212 		 */
3213 		/* 6 is not_enough time or no-loss */
3214 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3215 		return;
3216 	}
3217 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3218 		/*
3219 		 * For now if we wait too long, reset all sampling. We need
3220 		 * to do some research here, its possible that we should
3221 		 * base this on how much loss as occurred.. something like
3222 		 * if its under 10% (or some thresh) reset all otherwise
3223 		 * don't.  Thats for phase II I guess.
3224 		 */
3225 		bbr_reset_lt_bw_sampling(bbr, cts);
3226  		/* reason 3 is to reset sampling due too long of sampling */
3227 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3228 		return;
3229 	}
3230 	/*
3231 	 * End sampling interval when a packet is lost, so we estimate the
3232 	 * policer tokens were exhausted. Stopping the sampling before the
3233 	 * tokens are exhausted under-estimates the policed rate.
3234 	 */
3235 	if (loss_detected == 0) {
3236 		/* 6 is not_enough time or no-loss */
3237 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3238 		return;
3239 	}
3240 	/* Calculate packets lost and delivered in sampling interval. */
3241 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3242 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3243 	if ((delivered == 0) ||
3244 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3245 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3246 		return;
3247 	}
3248 	if (d_time < 1000) {
3249 		/* Not enough time. wait */
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 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3255 		/* Too long */
3256 		bbr_reset_lt_bw_sampling(bbr, cts);
3257  		/* reason 3 is to reset sampling due too long of sampling */
3258 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3259 		return;
3260 	}
3261 	del_time = d_time;
3262 	bw = delivered;
3263 	bw *= (uint64_t)USECS_IN_SECOND;
3264 	bw /= del_time;
3265 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3266 }
3267 
3268 /*
3269  * Allocate a sendmap from our zone.
3270  */
3271 static struct bbr_sendmap *
3272 bbr_alloc(struct tcp_bbr *bbr)
3273 {
3274 	struct bbr_sendmap *rsm;
3275 
3276 	BBR_STAT_INC(bbr_to_alloc);
3277 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3278 	if (rsm) {
3279 		bbr->r_ctl.rc_num_maps_alloced++;
3280 		return (rsm);
3281 	}
3282 	if (bbr->r_ctl.rc_free_cnt) {
3283 		BBR_STAT_INC(bbr_to_alloc_emerg);
3284 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3285 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3286 		bbr->r_ctl.rc_free_cnt--;
3287 		return (rsm);
3288 	}
3289 	BBR_STAT_INC(bbr_to_alloc_failed);
3290 	return (NULL);
3291 }
3292 
3293 static struct bbr_sendmap *
3294 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3295 {
3296 	if ((V_tcp_map_entries_limit > 0) &&
3297 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3298 		BBR_STAT_INC(bbr_alloc_limited);
3299 		if (!bbr->alloc_limit_reported) {
3300 			bbr->alloc_limit_reported = 1;
3301 			BBR_STAT_INC(bbr_alloc_limited_conns);
3302 		}
3303 		return (NULL);
3304 	}
3305 	return (bbr_alloc(bbr));
3306 }
3307 
3308 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3309 static struct bbr_sendmap *
3310 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3311 {
3312 	struct bbr_sendmap *rsm;
3313 
3314 	if (limit_type) {
3315 		/* currently there is only one limit type */
3316 		if (V_tcp_map_split_limit > 0 &&
3317 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3318 			BBR_STAT_INC(bbr_split_limited);
3319 			if (!bbr->alloc_limit_reported) {
3320 				bbr->alloc_limit_reported = 1;
3321 				BBR_STAT_INC(bbr_alloc_limited_conns);
3322 			}
3323 			return (NULL);
3324 		}
3325 	}
3326 
3327 	/* allocate and mark in the limit type, if set */
3328 	rsm = bbr_alloc(bbr);
3329 	if (rsm != NULL && limit_type) {
3330 		rsm->r_limit_type = limit_type;
3331 		bbr->r_ctl.rc_num_split_allocs++;
3332 	}
3333 	return (rsm);
3334 }
3335 
3336 static void
3337 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3338 {
3339 	if (rsm->r_limit_type) {
3340 		/* currently there is only one limit type */
3341 		bbr->r_ctl.rc_num_split_allocs--;
3342 	}
3343 	if (rsm->r_is_smallmap)
3344 		bbr->r_ctl.rc_num_small_maps_alloced--;
3345 	if (bbr->r_ctl.rc_tlp_send == rsm)
3346 		bbr->r_ctl.rc_tlp_send = NULL;
3347 	if (bbr->r_ctl.rc_resend == rsm) {
3348 		bbr->r_ctl.rc_resend = NULL;
3349 	}
3350 	if (bbr->r_ctl.rc_next == rsm)
3351 		bbr->r_ctl.rc_next = NULL;
3352 	if (bbr->r_ctl.rc_sacklast == rsm)
3353 		bbr->r_ctl.rc_sacklast = NULL;
3354 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3355 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3356 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3357 		rsm->r_limit_type = 0;
3358 		bbr->r_ctl.rc_free_cnt++;
3359 		return;
3360 	}
3361 	bbr->r_ctl.rc_num_maps_alloced--;
3362 	uma_zfree(bbr_zone, rsm);
3363 }
3364 
3365 /*
3366  * Returns the BDP.
3367  */
3368 static uint64_t
3369 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3370 	/*
3371 	 * Calculate the bytes in flight needed given the bw (in bytes per
3372 	 * second) and the specifyed rtt in useconds. We need to put out the
3373 	 * returned value per RTT to match that rate. Gain will normally
3374 	 * raise it up from there.
3375 	 *
3376 	 * This should not overflow as long as the bandwidth is below 1
3377 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3378 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3379 	 */
3380 	uint64_t usec_per_sec;
3381 
3382 	usec_per_sec = USECS_IN_SECOND;
3383 	return ((rtt * bw) / usec_per_sec);
3384 }
3385 
3386 /*
3387  * Return the initial cwnd.
3388  */
3389 static uint32_t
3390 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3391 {
3392 	uint32_t i_cwnd;
3393 
3394 	if (bbr->rc_init_win) {
3395 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3396 	} else if (V_tcp_initcwnd_segments)
3397 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3398 		    max(2 * tp->t_maxseg, 14600));
3399 	else if (V_tcp_do_rfc3390)
3400 		i_cwnd = min(4 * tp->t_maxseg,
3401 		    max(2 * tp->t_maxseg, 4380));
3402 	else {
3403 		/* Per RFC5681 Section 3.1 */
3404 		if (tp->t_maxseg > 2190)
3405 			i_cwnd = 2 * tp->t_maxseg;
3406 		else if (tp->t_maxseg > 1095)
3407 			i_cwnd = 3 * tp->t_maxseg;
3408 		else
3409 			i_cwnd = 4 * tp->t_maxseg;
3410 	}
3411 	return (i_cwnd);
3412 }
3413 
3414 /*
3415  * Given a specified gain, return the target
3416  * cwnd based on that gain.
3417  */
3418 static uint32_t
3419 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3420 {
3421 	uint64_t bdp, rtt;
3422 	uint32_t cwnd;
3423 
3424 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3425 	    (bbr_get_full_bw(bbr) == 0)) {
3426 		/* No measurements yet */
3427 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3428 	}
3429 	/*
3430 	 * Get bytes per RTT needed (rttProp is normally in
3431 	 * bbr_cwndtarget_rtt_touse)
3432 	 */
3433 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3434 	/* Get the bdp from the two values */
3435 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3436 	/* Now apply the gain */
3437 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3438 
3439 	return (cwnd);
3440 }
3441 
3442 static uint32_t
3443 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3444 {
3445 	uint32_t cwnd, mss;
3446 
3447 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3448 	/* Get the base cwnd with gain rounded to a mss */
3449 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3450 	/*
3451 	 * Add in N (2 default since we do not have a
3452 	 * fq layer to trap packets in) quanta's per the I-D
3453 	 * section 4.2.3.2 quanta adjust.
3454 	 */
3455 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3456 	if (bbr->rc_use_google) {
3457 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3458 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3459 			/*
3460 			 * The linux implementation adds
3461 			 * an extra 2 x mss in gain cycle which
3462 			 * is documented no-where except in the code.
3463 			 * so we add more for Neal undocumented feature
3464 			 */
3465 			cwnd += 2 * mss;
3466 		}
3467  		if ((cwnd / mss) & 0x1) {
3468 			/* Round up for odd num mss */
3469 			cwnd += mss;
3470 		}
3471 	}
3472 	/* Are we below the min cwnd? */
3473 	if (cwnd < get_min_cwnd(bbr))
3474 		return (get_min_cwnd(bbr));
3475 	return (cwnd);
3476 }
3477 
3478 static uint16_t
3479 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3480 {
3481 	if (gain < 1)
3482 		gain = 1;
3483 	return (gain);
3484 }
3485 
3486 static uint32_t
3487 bbr_get_header_oh(struct tcp_bbr *bbr)
3488 {
3489 	int seg_oh;
3490 
3491 	seg_oh = 0;
3492 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3493 		/* Do we include TCP overhead? */
3494 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3495 	}
3496 	if (bbr->r_ctl.rc_inc_ip_oh) {
3497 		/* Do we include IP overhead? */
3498 #ifdef INET6
3499 		if (bbr->r_is_v6) {
3500 			seg_oh += sizeof(struct ip6_hdr);
3501 		} else
3502 #endif
3503 		{
3504 
3505 #ifdef INET
3506 			seg_oh += sizeof(struct ip);
3507 #endif
3508 		}
3509 	}
3510 	if (bbr->r_ctl.rc_inc_enet_oh) {
3511 		/* Do we include the ethernet overhead?  */
3512 		seg_oh += sizeof(struct ether_header);
3513 	}
3514 	return(seg_oh);
3515 }
3516 
3517 static uint32_t
3518 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3519 {
3520 	uint64_t divor, res, tim;
3521 
3522 	if (useconds_time == 0)
3523 		return (0);
3524 	gain = bbr_gain_adjust(bbr, gain);
3525 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3526 	tim = useconds_time;
3527 	res = (tim * bw * gain) / divor;
3528 	if (res == 0)
3529 		res = 1;
3530 	return ((uint32_t)res);
3531 }
3532 
3533 /*
3534  * Given a gain and a length return the delay in useconds that
3535  * should be used to evenly space out packets
3536  * on the connection (based on the gain factor).
3537  */
3538 static uint32_t
3539 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3540 {
3541 	uint64_t bw, lentim, res;
3542 	uint32_t usecs, srtt, over = 0;
3543 	uint32_t seg_oh, num_segs, maxseg;
3544 
3545 	if (len == 0)
3546 		return (0);
3547 
3548 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3549 	num_segs = (len + maxseg - 1) / maxseg;
3550 	if (bbr->rc_use_google == 0) {
3551 		seg_oh = bbr_get_header_oh(bbr);
3552 		len += (num_segs * seg_oh);
3553 	}
3554 	gain = bbr_gain_adjust(bbr, gain);
3555 	bw = bbr_get_bw(bbr);
3556 	if (bbr->rc_use_google) {
3557 		uint64_t cbw;
3558 
3559 		/*
3560 		 * Reduce the b/w by the google discount
3561 		 * factor 10 = 1%.
3562 		 */
3563 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3564 		cbw /= (uint64_t)1000;
3565 		/* We don't apply a discount if it results in 0 */
3566 		if (cbw > 0)
3567 			bw = cbw;
3568 	}
3569 	lentim = ((uint64_t)len *
3570 		  (uint64_t)USECS_IN_SECOND *
3571 		  (uint64_t)BBR_UNIT);
3572 	res = lentim / ((uint64_t)gain * bw);
3573 	if (res == 0)
3574 		res = 1;
3575 	usecs = (uint32_t)res;
3576 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3577 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3578 	    (bbr->rc_use_google == 0) &&
3579 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3580 		/*
3581 		 * We cannot let the delay be more than 1/2 the srtt time.
3582 		 * Otherwise we cannot pace out or send properly.
3583 		 */
3584 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3585 		BBR_STAT_INC(bbr_hpts_min_time);
3586 	}
3587 	if (!nolog)
3588 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3589 	return (usecs);
3590 }
3591 
3592 static void
3593 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3594 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3595 {
3596 	uint64_t bw;
3597 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3598 	int32_t meth;
3599 
3600 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3601 
3602 #ifdef STATS
3603 	if ((tp->t_flags & TF_GPUTINPROG) &&
3604 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3605 		/*
3606 		 * Strech acks and compressed acks will cause this to
3607 		 * oscillate but we are doing it the same way as the main
3608 		 * stack so it will be compariable (though possibly not
3609 		 * ideal).
3610 		 */
3611 		int32_t cgput;
3612 		int64_t gput, time_stamp;
3613 
3614 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3615 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3616 		cgput = gput / time_stamp;
3617 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3618 					 cgput);
3619 		if (tp->t_stats_gput_prev > 0)
3620 			stats_voi_update_abs_s32(tp->t_stats,
3621 						 VOI_TCP_GPUT_ND,
3622 						 ((gput - tp->t_stats_gput_prev) * 100) /
3623 						 tp->t_stats_gput_prev);
3624 		tp->t_flags &= ~TF_GPUTINPROG;
3625 		tp->t_stats_gput_prev = cgput;
3626 	}
3627 #endif
3628 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3629 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3630 		/* We don't change anything in probe-rtt */
3631 		return;
3632 	}
3633 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3634 	saved_bytes = bytes_this_ack;
3635 	bytes_this_ack += sack_changed;
3636 	if (bytes_this_ack > prev_acked) {
3637 		bytes_this_ack -= prev_acked;
3638 		/*
3639 		 * A byte ack'd gives us a full mss
3640 		 * to be like linux i.e. they count packets.
3641 		 */
3642 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3643 			bytes_this_ack = maxseg;
3644 	} else {
3645 		/* Unlikely */
3646 		bytes_this_ack = 0;
3647 	}
3648 	cwnd = tp->snd_cwnd;
3649 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3650 	if (bw)
3651 		target_cwnd = bbr_get_target_cwnd(bbr,
3652 						  bw,
3653 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3654 	else
3655 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3656 	if (IN_RECOVERY(tp->t_flags) &&
3657 	    (bbr->bbr_prev_in_rec == 0)) {
3658 		/*
3659 		 * We are entering recovery and
3660 		 * thus packet conservation.
3661 		 */
3662 		bbr->pkt_conservation = 1;
3663 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3664 		cwnd = ctf_flight_size(tp,
3665 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3666 			bytes_this_ack;
3667 	}
3668 	if (IN_RECOVERY(tp->t_flags)) {
3669 		uint32_t flight;
3670 
3671 		bbr->bbr_prev_in_rec = 1;
3672 		if (cwnd > losses) {
3673 			cwnd -= losses;
3674 			if (cwnd < maxseg)
3675 				cwnd = maxseg;
3676 		} else
3677 			cwnd = maxseg;
3678 		flight = ctf_flight_size(tp,
3679 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3680 		bbr_log_type_cwndupd(bbr, flight, 0,
3681 				     losses, 10, 0, 0, line);
3682 		if (bbr->pkt_conservation) {
3683 			uint32_t time_in;
3684 
3685 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3686 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3687 			else
3688 				time_in = 0;
3689 
3690 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3691 				/* Clear packet conservation after an rttProp */
3692 				bbr->pkt_conservation = 0;
3693 			} else {
3694 				if ((flight + bytes_this_ack) > cwnd)
3695 					cwnd = flight + bytes_this_ack;
3696 				if (cwnd < get_min_cwnd(bbr))
3697 					cwnd = get_min_cwnd(bbr);
3698 				tp->snd_cwnd = cwnd;
3699 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3700 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3701 				return;
3702 			}
3703 		}
3704 	} else
3705 		bbr->bbr_prev_in_rec = 0;
3706 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3707 		bbr->r_ctl.restrict_growth--;
3708 		if (bytes_this_ack > maxseg)
3709 			bytes_this_ack = maxseg;
3710 	}
3711 	if (bbr->rc_filled_pipe) {
3712 		/*
3713 		 * Here we have exited startup and filled the pipe. We will
3714 		 * thus allow the cwnd to shrink to the target. We hit here
3715 		 * mostly.
3716 		 */
3717 		uint32_t s_cwnd;
3718 
3719 		meth = 2;
3720 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3721 		if (s_cwnd > cwnd)
3722 			cwnd = s_cwnd;
3723 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3724 			cwnd = s_cwnd;
3725 	} else {
3726 		/*
3727 		 * Here we are still in startup, we increase cwnd by what
3728 		 * has been acked.
3729 		 */
3730 		if ((cwnd < target_cwnd) ||
3731 		    (bbr->rc_past_init_win == 0)) {
3732 			meth = 3;
3733 			cwnd += bytes_this_ack;
3734 		} else {
3735 			/*
3736 			 * Method 4 means we are at target so no gain in
3737 			 * startup and past the initial window.
3738 			 */
3739 			meth = 4;
3740 		}
3741 	}
3742 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3743 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3744 }
3745 
3746 static void
3747 tcp_bbr_partialack(struct tcpcb *tp)
3748 {
3749 	struct tcp_bbr *bbr;
3750 
3751 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3752 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3753 	if (ctf_flight_size(tp,
3754 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3755 	    tp->snd_cwnd) {
3756 		bbr->r_wanted_output = 1;
3757 	}
3758 }
3759 
3760 static void
3761 bbr_post_recovery(struct tcpcb *tp)
3762 {
3763 	struct tcp_bbr *bbr;
3764 	uint32_t  flight;
3765 
3766 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3767 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3768 	/*
3769 	 * Here we just exit recovery.
3770 	 */
3771 	EXIT_RECOVERY(tp->t_flags);
3772 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3773 	bbr->r_recovery_bw = 0;
3774 	tp->snd_recover = tp->snd_una;
3775 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3776 	bbr->pkt_conservation = 0;
3777 	if (bbr->rc_use_google == 0) {
3778 		/*
3779 		 * For non-google mode lets
3780 		 * go ahead and make sure we clear
3781 		 * the recovery state so if we
3782 		 * bounce back in to recovery we
3783 		 * will do PC.
3784 		 */
3785 		bbr->bbr_prev_in_rec = 0;
3786 	}
3787 	bbr_log_type_exit_rec(bbr);
3788 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3789 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3790 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3791 	} else {
3792 		/* For probe-rtt case lets fix up its saved_cwnd */
3793 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3794 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3795 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3796 		}
3797 	}
3798 	flight = ctf_flight_size(tp,
3799 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3800 	if ((bbr->rc_use_google == 0) &&
3801 	    bbr_do_red) {
3802 		uint64_t val, lr2use;
3803 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3804 		uint32_t *cwnd_p;
3805 
3806 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3807 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3808 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3809 			ratio = (uint32_t)val;
3810 		} else
3811 			ratio = 1000;
3812 
3813 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3814 				     bbr->r_ctl.recovery_lr, 21,
3815 				     ratio,
3816 				     bbr->r_ctl.rc_red_cwnd_pe,
3817 				     __LINE__);
3818 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3819 			goto done;
3820 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3821 		     bbr_prtt_slam_cwnd) ||
3822 		    (bbr_sub_drain_slam_cwnd &&
3823 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3824 		     bbr->rc_hit_state_1 &&
3825 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3826 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3827 		     bbr_slam_cwnd_in_main_drain)) {
3828 			/*
3829 			 * Here we must poke at the saved cwnd
3830 			 * as well as the cwnd.
3831 			 */
3832 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3833 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3834 		} else {
3835  			cwnd = tp->snd_cwnd;
3836 			cwnd_p = &tp->snd_cwnd;
3837 		}
3838 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3839 		/* Add the overall lr with the recovery lr */
3840 		if (bbr->r_ctl.rc_lost == 0)
3841 			lr2use = 0;
3842 		else if (bbr->r_ctl.rc_delivered == 0)
3843 			lr2use = 1000;
3844 		else {
3845 			lr2use = bbr->r_ctl.rc_lost * 1000;
3846 			lr2use /= bbr->r_ctl.rc_delivered;
3847 		}
3848 		lr2use += bbr->r_ctl.recovery_lr;
3849 		acks_inflight = (flight / (maxseg * 2));
3850 		if (bbr_red_scale) {
3851 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3852 			lr2use /= bbr_red_scale;
3853 			if ((bbr_red_growth_restrict) &&
3854 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3855 			    bbr->r_ctl.restrict_growth += acks_inflight;
3856 		}
3857 		if (lr2use) {
3858 			val = (uint64_t)cwnd * lr2use;
3859 			val /= 1000;
3860 			if (cwnd > val)
3861 				newcwnd = roundup((cwnd - val), maxseg);
3862 			else
3863 				newcwnd = maxseg;
3864 		} else {
3865 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3866 			val /= (uint64_t)bbr_red_div;
3867 			newcwnd = roundup((uint32_t)val, maxseg);
3868 		}
3869 		/* with standard delayed acks how many acks can I expect? */
3870 		if (bbr_drop_limit == 0) {
3871 			/*
3872 			 * Anticpate how much we will
3873 			 * raise the cwnd based on the acks.
3874 			 */
3875 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3876 				/* We do enforce the min (with the acks) */
3877 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3878 			}
3879 		} else {
3880 			/*
3881 			 * A strict drop limit of N is inplace
3882 			 */
3883 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3884 				newcwnd = bbr_drop_limit * maxseg;
3885 			}
3886 		}
3887 		/* For the next N acks do we restrict the growth */
3888 		*cwnd_p = newcwnd;
3889 		if (tp->snd_cwnd > newcwnd)
3890 			tp->snd_cwnd = newcwnd;
3891 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3892 				     (uint32_t)lr2use,
3893 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3894 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3895 	}
3896 done:
3897 	bbr->r_ctl.recovery_lr = 0;
3898 	if (flight <= tp->snd_cwnd) {
3899 		bbr->r_wanted_output = 1;
3900 	}
3901 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3902 }
3903 
3904 static void
3905 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3906 {
3907 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3908 	/* Limit the drop in b/w to 1/2 our current filter. */
3909 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3910 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3911 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3912 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3913 	tcp_bbr_tso_size_check(bbr, cts);
3914 }
3915 
3916 static void
3917 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3918 {
3919 	struct tcp_bbr *bbr;
3920 
3921 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3922 #ifdef STATS
3923 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3924 #endif
3925 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3926 	switch (type) {
3927 	case CC_NDUPACK:
3928 		if (!IN_RECOVERY(tp->t_flags)) {
3929 			tp->snd_recover = tp->snd_max;
3930 			/* Start a new epoch */
3931 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3932 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3933 				/*
3934 				 * Move forward the lt epoch
3935 				 * so it won't count the truncated
3936 				 * epoch.
3937 				 */
3938 				bbr->r_ctl.rc_lt_epoch++;
3939 			}
3940 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3941 				/*
3942 				 * Just like the policer detection code
3943 				 * if we are in startup we must push
3944 				 * forward the last startup epoch
3945 				 * to hide the truncated PE.
3946 				 */
3947 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3948 			}
3949 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3950 			ENTER_RECOVERY(tp->t_flags);
3951 			bbr->rc_tlp_rtx_out = 0;
3952 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3953 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3954 			if (tcp_in_hpts(bbr->rc_tp) &&
3955 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3956 				/*
3957 				 * When we enter recovery, we need to restart
3958 				 * any timers. This may mean we gain an agg
3959 				 * early, which will be made up for at the last
3960 				 * rxt out.
3961 				 */
3962 				bbr->rc_timer_first = 1;
3963 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3964 			}
3965 			/*
3966 			 * Calculate a new cwnd based on to the current
3967 			 * delivery rate with no gain. We get the bdp
3968 			 * without gaining it up like we normally would and
3969 			 * we use the last cur_del_rate.
3970 			 */
3971 			if ((bbr->rc_use_google == 0) &&
3972 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3973 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3974 				tp->snd_cwnd = ctf_flight_size(tp,
3975 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3976 					(tp->t_maxseg - bbr->rc_last_options);
3977 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3978 					/* We always gate to min cwnd */
3979 					tp->snd_cwnd = get_min_cwnd(bbr);
3980 				}
3981 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3982 			}
3983 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3984 		}
3985 		break;
3986 	case CC_RTO_ERR:
3987 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
3988 		/* RTO was unnecessary, so reset everything. */
3989 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
3990 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3991 			tp->snd_cwnd = tp->snd_cwnd_prev;
3992 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
3993 			tp->snd_recover = tp->snd_recover_prev;
3994 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3995 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
3996 		}
3997 		tp->t_badrxtwin = 0;
3998 		break;
3999 	}
4000 }
4001 
4002 /*
4003  * Indicate whether this ack should be delayed.  We can delay the ack if
4004  * following conditions are met:
4005  *	- There is no delayed ack timer in progress.
4006  *	- Our last ack wasn't a 0-sized window. We never want to delay
4007  *	  the ack that opens up a 0-sized window.
4008  *	- LRO wasn't used for this segment. We make sure by checking that the
4009  *	  segment size is not larger than the MSS.
4010  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4011  *	  connection.
4012  *	- The data being acked is less than a full segment (a stretch ack
4013  *        of more than a segment we should ack.
4014  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4015  */
4016 #define DELAY_ACK(tp, bbr, nsegs)				\
4017 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4018 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4019 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4020 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4021 
4022 /*
4023  * Return the lowest RSM in the map of
4024  * packets still in flight that is not acked.
4025  * This should normally find on the first one
4026  * since we remove packets from the send
4027  * map after they are marked ACKED.
4028  */
4029 static struct bbr_sendmap *
4030 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4031 {
4032 	struct bbr_sendmap *rsm;
4033 
4034 	/*
4035 	 * Walk the time-order transmitted list looking for an rsm that is
4036 	 * not acked. This will be the one that was sent the longest time
4037 	 * ago that is still outstanding.
4038 	 */
4039 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4040 		if (rsm->r_flags & BBR_ACKED) {
4041 			continue;
4042 		}
4043 		goto finish;
4044 	}
4045 finish:
4046 	return (rsm);
4047 }
4048 
4049 static struct bbr_sendmap *
4050 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4051 {
4052 	struct bbr_sendmap *prsm;
4053 
4054 	/*
4055 	 * Walk the sequence order list backward until we hit and arrive at
4056 	 * the highest seq not acked. In theory when this is called it
4057 	 * should be the last segment (which it was not).
4058 	 */
4059 	prsm = rsm;
4060 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4061 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4062 			continue;
4063 		}
4064 		return (prsm);
4065 	}
4066 	return (NULL);
4067 }
4068 
4069 /*
4070  * Returns to the caller the number of microseconds that
4071  * the packet can be outstanding before we think we
4072  * should have had an ack returned.
4073  */
4074 static uint32_t
4075 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4076 {
4077 	/*
4078 	 * lro is the flag we use to determine if we have seen reordering.
4079 	 * If it gets set we have seen reordering. The reorder logic either
4080 	 * works in one of two ways:
4081 	 *
4082 	 * If reorder-fade is configured, then we track the last time we saw
4083 	 * re-ordering occur. If we reach the point where enough time as
4084 	 * passed we no longer consider reordering has occuring.
4085 	 *
4086 	 * Or if reorder-face is 0, then once we see reordering we consider
4087 	 * the connection to alway be subject to reordering and just set lro
4088 	 * to 1.
4089 	 *
4090 	 * In the end if lro is non-zero we add the extra time for
4091 	 * reordering in.
4092 	 */
4093 	int32_t lro;
4094 	uint32_t thresh, t_rxtcur;
4095 
4096 	if (srtt == 0)
4097 		srtt = 1;
4098 	if (bbr->r_ctl.rc_reorder_ts) {
4099 		if (bbr->r_ctl.rc_reorder_fade) {
4100 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4101 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4102 				if (lro == 0) {
4103 					/*
4104 					 * No time as passed since the last
4105 					 * reorder, mark it as reordering.
4106 					 */
4107 					lro = 1;
4108 				}
4109 			} else {
4110 				/* Negative time? */
4111 				lro = 0;
4112 			}
4113 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4114 				/* Turn off reordering seen too */
4115 				bbr->r_ctl.rc_reorder_ts = 0;
4116 				lro = 0;
4117 			}
4118 		} else {
4119 			/* Reodering does not fade */
4120 			lro = 1;
4121 		}
4122 	} else {
4123 		lro = 0;
4124 	}
4125 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4126 	if (lro) {
4127 		/* It must be set, if not you get 1/4 rtt */
4128 		if (bbr->r_ctl.rc_reorder_shift)
4129 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4130 		else
4131 			thresh += (srtt >> 2);
4132 	} else {
4133 		thresh += 1000;
4134 	}
4135 	/* We don't let the rack timeout be above a RTO */
4136 	if ((bbr->rc_tp)->t_srtt == 0)
4137 		t_rxtcur = BBR_INITIAL_RTO;
4138 	else
4139 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4140 	if (thresh > t_rxtcur) {
4141 		thresh = t_rxtcur;
4142 	}
4143 	/* And we don't want it above the RTO max either */
4144 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4145 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4146 	}
4147 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4148 	return (thresh);
4149 }
4150 
4151 /*
4152  * Return to the caller the amount of time in mico-seconds
4153  * that should be used for the TLP timer from the last
4154  * send time of this packet.
4155  */
4156 static uint32_t
4157 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4158     struct bbr_sendmap *rsm, uint32_t srtt,
4159     uint32_t cts)
4160 {
4161 	uint32_t thresh, len, maxseg, t_rxtcur;
4162 	struct bbr_sendmap *prsm;
4163 
4164 	if (srtt == 0)
4165 		srtt = 1;
4166 	if (bbr->rc_tlp_threshold)
4167 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4168 	else
4169 		thresh = (srtt * 2);
4170 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4171 	/* Get the previous sent packet, if any  */
4172 	len = rsm->r_end - rsm->r_start;
4173 
4174 	/* 2.1 behavior */
4175 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4176 	if (prsm && (len <= maxseg)) {
4177 		/*
4178 		 * Two packets outstanding, thresh should be (2*srtt) +
4179 		 * possible inter-packet delay (if any).
4180 		 */
4181 		uint32_t inter_gap = 0;
4182 		int idx, nidx;
4183 
4184 		idx = rsm->r_rtr_cnt - 1;
4185 		nidx = prsm->r_rtr_cnt - 1;
4186 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4187 			/* Yes it was sent later (or at the same time) */
4188 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4189 		}
4190 		thresh += inter_gap;
4191 	} else if (len <= maxseg) {
4192 		/*
4193 		 * Possibly compensate for delayed-ack.
4194 		 */
4195 		uint32_t alt_thresh;
4196 
4197 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4198 		if (alt_thresh > thresh)
4199 			thresh = alt_thresh;
4200 	}
4201 	/* Not above the current  RTO */
4202 	if (tp->t_srtt == 0)
4203 		t_rxtcur = BBR_INITIAL_RTO;
4204 	else
4205 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4206 
4207 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4208 	/* Not above an RTO */
4209 	if (thresh > t_rxtcur) {
4210 		thresh = t_rxtcur;
4211 	}
4212 	/* Not above a RTO max */
4213 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4214 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4215 	}
4216 	/* And now apply the user TLP min */
4217 	if (thresh < bbr_tlp_min) {
4218 		thresh = bbr_tlp_min;
4219 	}
4220 	return (thresh);
4221 }
4222 
4223 /*
4224  * Return one of three RTTs to use (in microseconds).
4225  */
4226 static __inline uint32_t
4227 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4228 {
4229 	uint32_t f_rtt;
4230 	uint32_t srtt;
4231 
4232 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4233 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4234 		/* We have no rtt at all */
4235 		if (bbr->rc_tp->t_srtt == 0)
4236 			f_rtt = BBR_INITIAL_RTO;
4237 		else
4238 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4239 		/*
4240 		 * Since we don't know how good the rtt is apply a
4241 		 * delayed-ack min
4242 		 */
4243 		if (f_rtt < bbr_delayed_ack_time) {
4244 			f_rtt = bbr_delayed_ack_time;
4245 		}
4246 	}
4247 	/* Take the filter version or last measured pkt-rtt */
4248 	if (rtt_type == BBR_RTT_PROP) {
4249 		srtt = f_rtt;
4250 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4251 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4252 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4253 		} else {
4254 			/* No pkt rtt yet */
4255 			srtt = f_rtt;
4256 		}
4257 	} else if (rtt_type == BBR_RTT_RACK) {
4258 		srtt = bbr->r_ctl.rc_last_rtt;
4259 		/* We need to add in any internal delay for our timer */
4260 		if (bbr->rc_ack_was_delayed)
4261 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4262 	} else if (rtt_type == BBR_SRTT) {
4263 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4264 	} else {
4265 		/* TSNH */
4266 		srtt = f_rtt;
4267 #ifdef BBR_INVARIANTS
4268 		panic("Unknown rtt request type %d", rtt_type);
4269 #endif
4270 	}
4271 	return (srtt);
4272 }
4273 
4274 static int
4275 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4276 {
4277 	uint32_t thresh;
4278 
4279 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4280 				      cts, rsm);
4281 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4282 		/* It is lost (past time) */
4283 		return (1);
4284 	}
4285 	return (0);
4286 }
4287 
4288 /*
4289  * Return a sendmap if we need to retransmit something.
4290  */
4291 static struct bbr_sendmap *
4292 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4293 {
4294 	/*
4295 	 * Check to see that we don't need to fall into recovery. We will
4296 	 * need to do so if our oldest transmit is past the time we should
4297 	 * have had an ack.
4298 	 */
4299 
4300 	struct bbr_sendmap *rsm;
4301 	int32_t idx;
4302 
4303 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4304 		/* Nothing outstanding that we know of */
4305 		return (NULL);
4306 	}
4307 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4308 	if (rsm == NULL) {
4309 		/* Nothing in the transmit map */
4310 		return (NULL);
4311 	}
4312 	if (tp->t_flags & TF_SENTFIN) {
4313 		/* Fin restricted, don't find anything once a fin is sent */
4314 		return (NULL);
4315 	}
4316 	if (rsm->r_flags & BBR_ACKED) {
4317 		/*
4318 		 * Ok the first one is acked (this really should not happen
4319 		 * since we remove the from the tmap once they are acked)
4320 		 */
4321 		rsm = bbr_find_lowest_rsm(bbr);
4322 		if (rsm == NULL)
4323 			return (NULL);
4324 	}
4325 	idx = rsm->r_rtr_cnt - 1;
4326 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4327 		/* Send timestamp is the same or less? can't be ready */
4328 		return (NULL);
4329 	}
4330 	/* Get our RTT time */
4331 	if (bbr_is_lost(bbr, rsm, cts) &&
4332 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4333 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4334 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4335 			rsm->r_flags |= BBR_MARKED_LOST;
4336 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4337 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4338 		}
4339 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4340 #ifdef BBR_INVARIANTS
4341 		if ((rsm->r_end - rsm->r_start) == 0)
4342 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4343 #endif
4344 		return (rsm);
4345 	}
4346 	return (NULL);
4347 }
4348 
4349 /*
4350  * RACK Timer, here we simply do logging and house keeping.
4351  * the normal bbr_output_wtime() function will call the
4352  * appropriate thing to check if we need to do a RACK retransmit.
4353  * We return 1, saying don't proceed with bbr_output_wtime only
4354  * when all timers have been stopped (destroyed PCB?).
4355  */
4356 static int
4357 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4358 {
4359 	/*
4360 	 * This timer simply provides an internal trigger to send out data.
4361 	 * The check_recovery_mode call will see if there are needed
4362 	 * retransmissions, if so we will enter fast-recovery. The output
4363 	 * call may or may not do the same thing depending on sysctl
4364 	 * settings.
4365 	 */
4366 	uint32_t lost;
4367 
4368 	if (bbr->rc_all_timers_stopped) {
4369 		return (1);
4370 	}
4371 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4372 		/* Its not time yet */
4373 		return (0);
4374 	}
4375 	BBR_STAT_INC(bbr_to_tot);
4376 	lost = bbr->r_ctl.rc_lost;
4377 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4378 		bbr_set_state(tp, bbr, 0);
4379 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4380 	if (bbr->r_ctl.rc_resend == NULL) {
4381 		/* Lets do the check here */
4382 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4383 	}
4384 	if (bbr_policer_call_from_rack_to)
4385 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4386 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4387 	return (0);
4388 }
4389 
4390 static __inline void
4391 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4392 {
4393 	int idx;
4394 
4395 	nrsm->r_start = start;
4396 	nrsm->r_end = rsm->r_end;
4397 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4398 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4399 	nrsm->r_flags = rsm->r_flags;
4400 	/* We don't transfer forward the SYN flag */
4401 	nrsm->r_flags &= ~BBR_HAS_SYN;
4402 	/* We move forward the FIN flag, not that this should happen */
4403 	rsm->r_flags &= ~BBR_HAS_FIN;
4404 	nrsm->r_dupack = rsm->r_dupack;
4405 	nrsm->r_rtr_bytes = 0;
4406 	nrsm->r_is_gain = rsm->r_is_gain;
4407 	nrsm->r_is_drain = rsm->r_is_drain;
4408 	nrsm->r_delivered = rsm->r_delivered;
4409 	nrsm->r_ts_valid = rsm->r_ts_valid;
4410 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4411 	nrsm->r_del_time = rsm->r_del_time;
4412 	nrsm->r_app_limited = rsm->r_app_limited;
4413 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4414 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4415 	/* We split a piece the lower section looses any just_ret flag. */
4416 	nrsm->r_bbr_state = rsm->r_bbr_state;
4417 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4418 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4419 	}
4420 	rsm->r_end = nrsm->r_start;
4421 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4422 	idx /= 8;
4423 	/* Check if we got too small */
4424 	if ((rsm->r_is_smallmap == 0) &&
4425 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4426 		bbr->r_ctl.rc_num_small_maps_alloced++;
4427 		rsm->r_is_smallmap = 1;
4428 	}
4429 	/* Check the new one as well */
4430 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4431 		bbr->r_ctl.rc_num_small_maps_alloced++;
4432 		nrsm->r_is_smallmap = 1;
4433 	}
4434 }
4435 
4436 static int
4437 bbr_sack_mergable(struct bbr_sendmap *at,
4438 		  uint32_t start, uint32_t end)
4439 {
4440 	/*
4441 	 * Given a sack block defined by
4442 	 * start and end, and a current position
4443 	 * at. Return 1 if either side of at
4444 	 * would show that the block is mergable
4445 	 * to that side. A block to be mergable
4446 	 * must have overlap with the start/end
4447 	 * and be in the SACK'd state.
4448 	 */
4449 	struct bbr_sendmap *l_rsm;
4450 	struct bbr_sendmap *r_rsm;
4451 
4452 	/* first get the either side blocks */
4453 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4454 	r_rsm = TAILQ_NEXT(at, r_next);
4455 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4456 		/* Potentially mergeable */
4457 		if ((l_rsm->r_end == start) ||
4458 		    (SEQ_LT(start, l_rsm->r_end) &&
4459 		     SEQ_GT(end, l_rsm->r_end))) {
4460 			    /*
4461 			     * map blk   |------|
4462 			     * sack blk         |------|
4463 			     * <or>
4464 			     * map blk   |------|
4465 			     * sack blk      |------|
4466 			     */
4467 			    return (1);
4468 		    }
4469 	}
4470 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4471 		/* Potentially mergeable */
4472 		if ((r_rsm->r_start == end) ||
4473 		    (SEQ_LT(start, r_rsm->r_start) &&
4474 		     SEQ_GT(end, r_rsm->r_start))) {
4475 			/*
4476 			 * map blk          |---------|
4477 			 * sack blk    |----|
4478 			 * <or>
4479 			 * map blk          |---------|
4480 			 * sack blk    |-------|
4481 			 */
4482 			return (1);
4483 		}
4484 	}
4485 	return (0);
4486 }
4487 
4488 static struct bbr_sendmap *
4489 bbr_merge_rsm(struct tcp_bbr *bbr,
4490 	      struct bbr_sendmap *l_rsm,
4491 	      struct bbr_sendmap *r_rsm)
4492 {
4493 	/*
4494 	 * We are merging two ack'd RSM's,
4495 	 * the l_rsm is on the left (lower seq
4496 	 * values) and the r_rsm is on the right
4497 	 * (higher seq value). The simplest way
4498 	 * to merge these is to move the right
4499 	 * one into the left. I don't think there
4500 	 * is any reason we need to try to find
4501 	 * the oldest (or last oldest retransmitted).
4502 	 */
4503 	l_rsm->r_end = r_rsm->r_end;
4504 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4505 		l_rsm->r_dupack = r_rsm->r_dupack;
4506 	if (r_rsm->r_rtr_bytes)
4507 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4508 	if (r_rsm->r_in_tmap) {
4509 		/* This really should not happen */
4510 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4511 	}
4512 	if (r_rsm->r_app_limited)
4513 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4514 	/* Now the flags */
4515 	if (r_rsm->r_flags & BBR_HAS_FIN)
4516 		l_rsm->r_flags |= BBR_HAS_FIN;
4517 	if (r_rsm->r_flags & BBR_TLP)
4518 		l_rsm->r_flags |= BBR_TLP;
4519 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4520 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4521 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4522 		/* This really should not happen */
4523 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4524 	}
4525 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4526 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4527 		/* Transfer the split limit to the map we free */
4528 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4529 		l_rsm->r_limit_type = 0;
4530 	}
4531 	bbr_free(bbr, r_rsm);
4532 	return(l_rsm);
4533 }
4534 
4535 /*
4536  * TLP Timer, here we simply setup what segment we want to
4537  * have the TLP expire on, the normal bbr_output_wtime() will then
4538  * send it out.
4539  *
4540  * We return 1, saying don't proceed with bbr_output_wtime only
4541  * when all timers have been stopped (destroyed PCB?).
4542  */
4543 static int
4544 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4545 {
4546 	/*
4547 	 * Tail Loss Probe.
4548 	 */
4549 	struct bbr_sendmap *rsm = NULL;
4550 	struct socket *so;
4551 	uint32_t amm;
4552 	uint32_t out, avail;
4553 	uint32_t maxseg;
4554 	int collapsed_win = 0;
4555 
4556 	if (bbr->rc_all_timers_stopped) {
4557 		return (1);
4558 	}
4559 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4560 		/* Its not time yet */
4561 		return (0);
4562 	}
4563 	if (ctf_progress_timeout_check(tp, true)) {
4564 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4565 		return (-ETIMEDOUT);	/* tcp_drop() */
4566 	}
4567 	/* Did we somehow get into persists? */
4568 	if (bbr->rc_in_persist) {
4569 		return (0);
4570 	}
4571 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4572 		bbr_set_state(tp, bbr, 0);
4573 	BBR_STAT_INC(bbr_tlp_tot);
4574 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4575 	/*
4576 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4577 	 * need to figure out how to force a full MSS segment out.
4578 	 */
4579 	so = tptosocket(tp);
4580 	avail = sbavail(&so->so_snd);
4581 	out = ctf_outstanding(tp);
4582 	if (out > tp->snd_wnd) {
4583 		/* special case, we need a retransmission */
4584 		collapsed_win = 1;
4585 		goto need_retran;
4586 	}
4587 	if (avail > out) {
4588 		/* New data is available */
4589 		amm = avail - out;
4590 		if (amm > maxseg) {
4591 			amm = maxseg;
4592 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4593 			/* not enough to fill a MTU and no-delay is off */
4594 			goto need_retran;
4595 		}
4596 		/* Set the send-new override */
4597 		if ((out + amm) <= tp->snd_wnd) {
4598 			bbr->rc_tlp_new_data = 1;
4599 		} else {
4600 			goto need_retran;
4601 		}
4602 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4603 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4604 		bbr->r_ctl.rc_tlp_send = NULL;
4605 		/* cap any slots */
4606 		BBR_STAT_INC(bbr_tlp_newdata);
4607 		goto send;
4608 	}
4609 need_retran:
4610 	/*
4611 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4612 	 * optionally the first un-acked segment.
4613 	 */
4614 	if (collapsed_win == 0) {
4615 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4616 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4617 			rsm = bbr_find_high_nonack(bbr, rsm);
4618 		}
4619 		if (rsm == NULL) {
4620 			goto restore;
4621 		}
4622 	} else {
4623 		/*
4624 		 * We must find the last segment
4625 		 * that was acceptable by the client.
4626 		 */
4627 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4628 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4629 				/* Found one */
4630 				break;
4631 			}
4632 		}
4633 		if (rsm == NULL) {
4634 			/* None? if so send the first */
4635 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4636 			if (rsm == NULL)
4637 				goto restore;
4638 		}
4639 	}
4640 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4641 		/*
4642 		 * We need to split this the last segment in two.
4643 		 */
4644 		struct bbr_sendmap *nrsm;
4645 
4646 		nrsm = bbr_alloc_full_limit(bbr);
4647 		if (nrsm == NULL) {
4648 			/*
4649 			 * We can't get memory to split, we can either just
4650 			 * not split it. Or retransmit the whole piece, lets
4651 			 * do the large send (BTLP :-) ).
4652 			 */
4653 			goto go_for_it;
4654 		}
4655 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4656 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4657 		if (rsm->r_in_tmap) {
4658 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4659 			nrsm->r_in_tmap = 1;
4660 		}
4661 		rsm->r_flags &= (~BBR_HAS_FIN);
4662 		rsm = nrsm;
4663 	}
4664 go_for_it:
4665 	bbr->r_ctl.rc_tlp_send = rsm;
4666 	bbr->rc_tlp_rtx_out = 1;
4667 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4668 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4669 		tp->t_rxtshift++;
4670 	} else {
4671 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4672 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4673 	}
4674 send:
4675 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4676 		/*
4677 		 * Can't [re]/transmit a segment we have retransmitted the
4678 		 * max times. We need the retransmit timer to take over.
4679 		 */
4680 restore:
4681 		bbr->rc_tlp_new_data = 0;
4682 		bbr->r_ctl.rc_tlp_send = NULL;
4683 		if (rsm)
4684 			rsm->r_flags &= ~BBR_TLP;
4685 		BBR_STAT_INC(bbr_tlp_retran_fail);
4686 		return (0);
4687 	} else if (rsm) {
4688 		rsm->r_flags |= BBR_TLP;
4689 	}
4690 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4691 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4692 		/*
4693 		 * We have retransmitted to many times for TLP. Switch to
4694 		 * the regular RTO timer
4695 		 */
4696 		goto restore;
4697 	}
4698 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4699 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4700 	return (0);
4701 }
4702 
4703 /*
4704  * Delayed ack Timer, here we simply need to setup the
4705  * ACK_NOW flag and remove the DELACK flag. From there
4706  * the output routine will send the ack out.
4707  *
4708  * We only return 1, saying don't proceed, if all timers
4709  * are stopped (destroyed PCB?).
4710  */
4711 static int
4712 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4713 {
4714 	if (bbr->rc_all_timers_stopped) {
4715 		return (1);
4716 	}
4717 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4718 	tp->t_flags &= ~TF_DELACK;
4719 	tp->t_flags |= TF_ACKNOW;
4720 	KMOD_TCPSTAT_INC(tcps_delack);
4721 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4722 	return (0);
4723 }
4724 
4725 /*
4726  * Here we send a KEEP-ALIVE like probe to the
4727  * peer, we do not send data.
4728  *
4729  * We only return 1, saying don't proceed, if all timers
4730  * are stopped (destroyed PCB?).
4731  */
4732 static int
4733 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4734 {
4735 	struct tcptemp *t_template;
4736 	int32_t retval = 1;
4737 
4738 	if (bbr->rc_all_timers_stopped) {
4739 		return (1);
4740 	}
4741 	if (bbr->rc_in_persist == 0)
4742 		return (0);
4743 
4744 	/*
4745 	 * Persistence timer into zero window. Force a byte to be output, if
4746 	 * possible.
4747 	 */
4748 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4749 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4750 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4751 	/*
4752 	 * Have we exceeded the user specified progress time?
4753 	 */
4754 	if (ctf_progress_timeout_check(tp, true)) {
4755 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4756 		return (-ETIMEDOUT);	/* tcp_drop() */
4757 	}
4758 	/*
4759 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4760 	 * window is closed.  After a full backoff, drop the connection if
4761 	 * the idle time (no responses to probes) reaches the maximum
4762 	 * backoff that we would use if retransmitting.
4763 	 */
4764 	if (tp->t_rxtshift >= V_tcp_retries &&
4765 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4766 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4767 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4768 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4769 		return (-ETIMEDOUT);	/* tcp_drop() */
4770 	}
4771 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4772 	    tp->snd_una == tp->snd_max) {
4773 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4774 		retval = 0;
4775 		goto out;
4776 	}
4777 	/*
4778 	 * If the user has closed the socket then drop a persisting
4779 	 * connection after a much reduced timeout.
4780 	 */
4781 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4782 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4783 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4784 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4785 		return (-ETIMEDOUT);	/* tcp_drop() */
4786 	}
4787 	t_template = tcpip_maketemplate(bbr->rc_inp);
4788 	if (t_template) {
4789 		tcp_respond(tp, t_template->tt_ipgen,
4790 			    &t_template->tt_t, (struct mbuf *)NULL,
4791 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4792 		/* This sends an ack */
4793 		if (tp->t_flags & TF_DELACK)
4794 			tp->t_flags &= ~TF_DELACK;
4795 		free(t_template, M_TEMP);
4796 	}
4797 	if (tp->t_rxtshift < V_tcp_retries)
4798 		tp->t_rxtshift++;
4799 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4800 out:
4801 	return (retval);
4802 }
4803 
4804 /*
4805  * If a keepalive goes off, we had no other timers
4806  * happening. We always return 1 here since this
4807  * routine either drops the connection or sends
4808  * out a segment with respond.
4809  */
4810 static int
4811 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4812 {
4813 	struct tcptemp *t_template;
4814 	struct inpcb *inp = tptoinpcb(tp);
4815 
4816 	if (bbr->rc_all_timers_stopped) {
4817 		return (1);
4818 	}
4819 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4820 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4821 	/*
4822 	 * Keep-alive timer went off; send something or drop connection if
4823 	 * idle for too long.
4824 	 */
4825 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4826 	if (tp->t_state < TCPS_ESTABLISHED)
4827 		goto dropit;
4828 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4829 	    tp->t_state <= TCPS_CLOSING) {
4830 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4831 			goto dropit;
4832 		/*
4833 		 * Send a packet designed to force a response if the peer is
4834 		 * up and reachable: either an ACK if the connection is
4835 		 * still alive, or an RST if the peer has closed the
4836 		 * connection due to timeout or reboot. Using sequence
4837 		 * number tp->snd_una-1 causes the transmitted zero-length
4838 		 * segment to lie outside the receive window; by the
4839 		 * protocol spec, this requires the correspondent TCP to
4840 		 * respond.
4841 		 */
4842 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4843 		t_template = tcpip_maketemplate(inp);
4844 		if (t_template) {
4845 			tcp_respond(tp, t_template->tt_ipgen,
4846 			    &t_template->tt_t, (struct mbuf *)NULL,
4847 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4848 			free(t_template, M_TEMP);
4849 		}
4850 	}
4851 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4852 	return (1);
4853 dropit:
4854 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4855 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4856 	return (-ETIMEDOUT);	/* tcp_drop() */
4857 }
4858 
4859 /*
4860  * Retransmit helper function, clear up all the ack
4861  * flags and take care of important book keeping.
4862  */
4863 static void
4864 bbr_remxt_tmr(struct tcpcb *tp)
4865 {
4866 	/*
4867 	 * The retransmit timer went off, all sack'd blocks must be
4868 	 * un-acked.
4869 	 */
4870 	struct bbr_sendmap *rsm, *trsm = NULL;
4871 	struct tcp_bbr *bbr;
4872 	uint32_t cts, lost;
4873 
4874 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4875 	cts = tcp_get_usecs(&bbr->rc_tv);
4876 	lost = bbr->r_ctl.rc_lost;
4877 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4878 		bbr_set_state(tp, bbr, 0);
4879 
4880 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4881 		if (rsm->r_flags & BBR_ACKED) {
4882 			uint32_t old_flags;
4883 
4884 			rsm->r_dupack = 0;
4885 			if (rsm->r_in_tmap == 0) {
4886 				/* We must re-add it back to the tlist */
4887 				if (trsm == NULL) {
4888 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4889 				} else {
4890 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4891 				}
4892 				rsm->r_in_tmap = 1;
4893 			}
4894 			old_flags = rsm->r_flags;
4895 			rsm->r_flags |= BBR_RXT_CLEARED;
4896 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4897 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4898 		} else {
4899 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4900 			    (rsm->r_start == tp->snd_una)) {
4901 				/*
4902 				 * Special case for TCP FO. Where
4903 				 * we sent more data beyond the snd_max.
4904 				 * We don't mark that as lost and stop here.
4905 				 */
4906 				break;
4907 			}
4908 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4909 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4910 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4911 			}
4912 			if (bbr_marks_rxt_sack_passed) {
4913 				/*
4914 				 * With this option, we will rack out
4915 				 * in 1ms increments the rest of the packets.
4916 				 */
4917 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4918 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4919 			} else {
4920 				/*
4921 				 * With this option we only mark them lost
4922 				 * and remove all sack'd markings. We will run
4923 				 * another RXT or a TLP. This will cause
4924 				 * us to eventually send more based on what
4925 				 * ack's come in.
4926 				 */
4927 				rsm->r_flags |= BBR_MARKED_LOST;
4928 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4929 				rsm->r_flags &= ~BBR_SACK_PASSED;
4930 			}
4931 		}
4932 		trsm = rsm;
4933 	}
4934 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4935 	/* Clear the count (we just un-acked them) */
4936 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4937 	bbr->rc_tlp_new_data = 0;
4938 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4939 	/* zap the behindness on a rxt */
4940 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4941 	bbr->r_agg_early_set = 0;
4942 	bbr->r_ctl.rc_agg_early = 0;
4943 	bbr->rc_tlp_rtx_out = 0;
4944 	bbr->r_ctl.rc_sacked = 0;
4945 	bbr->r_ctl.rc_sacklast = NULL;
4946 	bbr->r_timer_override = 1;
4947 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4948 }
4949 
4950 /*
4951  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4952  * we will setup to retransmit the lowest seq number outstanding.
4953  */
4954 static int
4955 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4956 {
4957 	struct inpcb *inp = tptoinpcb(tp);
4958 	int32_t rexmt;
4959 	int32_t retval = 0;
4960 	bool isipv6;
4961 
4962 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4963 	if (bbr->rc_all_timers_stopped) {
4964 		return (1);
4965 	}
4966 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4967 	    (tp->snd_una == tp->snd_max)) {
4968 		/* Nothing outstanding .. nothing to do */
4969 		return (0);
4970 	}
4971 	/*
4972 	 * Retransmission timer went off.  Message has not been acked within
4973 	 * retransmit interval.  Back off to a longer retransmit interval
4974 	 * and retransmit one segment.
4975 	 */
4976 	if (ctf_progress_timeout_check(tp, true)) {
4977 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4978 		return (-ETIMEDOUT);	/* tcp_drop() */
4979 	}
4980 	bbr_remxt_tmr(tp);
4981 	if ((bbr->r_ctl.rc_resend == NULL) ||
4982 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4983 		/*
4984 		 * If the rwnd collapsed on
4985 		 * the one we are retransmitting
4986 		 * it does not count against the
4987 		 * rxt count.
4988 		 */
4989 		tp->t_rxtshift++;
4990 	}
4991 	if (tp->t_rxtshift > V_tcp_retries) {
4992 		tp->t_rxtshift = V_tcp_retries;
4993 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
4994 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
4995 		/* XXXGL: previously t_softerror was casted to uint16_t */
4996 		MPASS(tp->t_softerror >= 0);
4997 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
4998 		return (retval);	/* tcp_drop() */
4999 	}
5000 	if (tp->t_state == TCPS_SYN_SENT) {
5001 		/*
5002 		 * If the SYN was retransmitted, indicate CWND to be limited
5003 		 * to 1 segment in cc_conn_init().
5004 		 */
5005 		tp->snd_cwnd = 1;
5006 	} else if (tp->t_rxtshift == 1) {
5007 		/*
5008 		 * first retransmit; record ssthresh and cwnd so they can be
5009 		 * recovered if this turns out to be a "bad" retransmit. A
5010 		 * retransmit is considered "bad" if an ACK for this segment
5011 		 * is received within RTT/2 interval; the assumption here is
5012 		 * that the ACK was already in flight.  See "On Estimating
5013 		 * End-to-End Network Path Properties" by Allman and Paxson
5014 		 * for more details.
5015 		 */
5016 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5017 		if (!IN_RECOVERY(tp->t_flags)) {
5018 			tp->snd_cwnd_prev = tp->snd_cwnd;
5019 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5020 			tp->snd_recover_prev = tp->snd_recover;
5021 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5022 			tp->t_flags |= TF_PREVVALID;
5023 		} else {
5024 			tp->t_flags &= ~TF_PREVVALID;
5025 		}
5026 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5027 	} else {
5028 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5029 		tp->t_flags &= ~TF_PREVVALID;
5030 	}
5031 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5032 	if ((tp->t_state == TCPS_SYN_SENT) ||
5033 	    (tp->t_state == TCPS_SYN_RECEIVED))
5034 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5035 	else
5036 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5037 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5038 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5039 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5040 	/*
5041 	 * We enter the path for PLMTUD if connection is established or, if
5042 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5043 	 * amount of data we send is very small, we could send it in couple
5044 	 * of packets and process straight to FIN. In that case we won't
5045 	 * catch ESTABLISHED state.
5046 	 */
5047 #ifdef INET6
5048 	isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
5049 #else
5050 	isipv6 = false;
5051 #endif
5052 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5053 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5054 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5055 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5056 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5057 		/*
5058 		 * Idea here is that at each stage of mtu probe (usually,
5059 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5060 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5061 		 * should take care of that.
5062 		 */
5063 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5064 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5065 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5066 		    tp->t_rxtshift % 2 == 0)) {
5067 			/*
5068 			 * Enter Path MTU Black-hole Detection mechanism: -
5069 			 * Disable Path MTU Discovery (IP "DF" bit). -
5070 			 * Reduce MTU to lower value than what we negotiated
5071 			 * with peer.
5072 			 */
5073 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5074 				/*
5075 				 * Record that we may have found a black
5076 				 * hole.
5077 				 */
5078 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5079 				/* Keep track of previous MSS. */
5080 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5081 			}
5082 			/*
5083 			 * Reduce the MSS to blackhole value or to the
5084 			 * default in an attempt to retransmit.
5085 			 */
5086 #ifdef INET6
5087 			isipv6 = bbr->r_is_v6;
5088 			if (isipv6 &&
5089 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5090 				/* Use the sysctl tuneable blackhole MSS. */
5091 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5092 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5093 			} else if (isipv6) {
5094 				/* Use the default MSS. */
5095 				tp->t_maxseg = V_tcp_v6mssdflt;
5096 				/*
5097 				 * Disable Path MTU Discovery when we switch
5098 				 * to minmss.
5099 				 */
5100 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5101 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5102 			}
5103 #endif
5104 #if defined(INET6) && defined(INET)
5105 			else
5106 #endif
5107 #ifdef INET
5108 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5109 				/* Use the sysctl tuneable blackhole MSS. */
5110 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5111 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5112 			} else {
5113 				/* Use the default MSS. */
5114 				tp->t_maxseg = V_tcp_mssdflt;
5115 				/*
5116 				 * Disable Path MTU Discovery when we switch
5117 				 * to minmss.
5118 				 */
5119 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5120 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5121 			}
5122 #endif
5123 		} else {
5124 			/*
5125 			 * If further retransmissions are still unsuccessful
5126 			 * with a lowered MTU, maybe this isn't a blackhole
5127 			 * and we restore the previous MSS and blackhole
5128 			 * detection flags. The limit '6' is determined by
5129 			 * giving each probe stage (1448, 1188, 524) 2
5130 			 * chances to recover.
5131 			 */
5132 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5133 			    (tp->t_rxtshift >= 6)) {
5134 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5135 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5136 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5137 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5138 			}
5139 		}
5140 	}
5141 	/*
5142 	 * Disable RFC1323 and SACK if we haven't got any response to our
5143 	 * third SYN to work-around some broken terminal servers (most of
5144 	 * which have hopefully been retired) that have bad VJ header
5145 	 * compression code which trashes TCP segments containing
5146 	 * unknown-to-them TCP options.
5147 	 */
5148 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5149 	    (tp->t_rxtshift == 3))
5150 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5151 	/*
5152 	 * If we backed off this far, our srtt estimate is probably bogus.
5153 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5154 	 * move the current srtt into rttvar to keep the current retransmit
5155 	 * times until then.
5156 	 */
5157 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5158 #ifdef INET6
5159 		if (bbr->r_is_v6)
5160 			in6_losing(inp);
5161 		else
5162 #endif
5163 			in_losing(inp);
5164 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5165 		tp->t_srtt = 0;
5166 	}
5167 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5168 	tp->snd_recover = tp->snd_max;
5169 	tp->t_flags |= TF_ACKNOW;
5170 	tp->t_rtttime = 0;
5171 
5172 	return (retval);
5173 }
5174 
5175 static int
5176 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5177 {
5178 	int32_t ret = 0;
5179 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5180 
5181 	if (timers == 0) {
5182 		return (0);
5183 	}
5184 	if (tp->t_state == TCPS_LISTEN) {
5185 		/* no timers on listen sockets */
5186 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5187 			return (0);
5188 		return (1);
5189 	}
5190 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5191 		uint32_t left;
5192 
5193 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5194 			ret = -1;
5195 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5196 			return (0);
5197 		}
5198 		if (hpts_calling == 0) {
5199 			ret = -2;
5200 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5201 			return (0);
5202 		}
5203 		/*
5204 		 * Ok our timer went off early and we are not paced false
5205 		 * alarm, go back to sleep.
5206 		 */
5207 		left = bbr->r_ctl.rc_timer_exp - cts;
5208 		ret = -3;
5209 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5210 		tcp_hpts_insert(tp, HPTS_USEC_TO_SLOTS(left));
5211 		return (1);
5212 	}
5213 	bbr->rc_tmr_stopped = 0;
5214 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5215 	if (timers & PACE_TMR_DELACK) {
5216 		ret = bbr_timeout_delack(tp, bbr, cts);
5217 	} else if (timers & PACE_TMR_PERSIT) {
5218 		ret = bbr_timeout_persist(tp, bbr, cts);
5219 	} else if (timers & PACE_TMR_RACK) {
5220 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5221 		ret = bbr_timeout_rack(tp, bbr, cts);
5222 	} else if (timers & PACE_TMR_TLP) {
5223 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5224 		ret = bbr_timeout_tlp(tp, bbr, cts);
5225 	} else if (timers & PACE_TMR_RXT) {
5226 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5227 		ret = bbr_timeout_rxt(tp, bbr, cts);
5228 	} else if (timers & PACE_TMR_KEEP) {
5229 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5230 	}
5231 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5232 	return (ret);
5233 }
5234 
5235 static void
5236 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5237 {
5238 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5239 		uint8_t hpts_removed = 0;
5240 
5241 		if (tcp_in_hpts(bbr->rc_tp) &&
5242 		    (bbr->rc_timer_first == 1)) {
5243 			/*
5244 			 * If we are canceling timer's when we have the
5245 			 * timer ahead of the output being paced. We also
5246 			 * must remove ourselves from the hpts.
5247 			 */
5248 			hpts_removed = 1;
5249 			tcp_hpts_remove(bbr->rc_tp);
5250 			if (bbr->r_ctl.rc_last_delay_val) {
5251 				/* Update the last hptsi delay too */
5252 				uint32_t time_since_send;
5253 
5254 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5255 					time_since_send = cts - bbr->rc_pacer_started;
5256 				else
5257 					time_since_send = 0;
5258 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5259 					/* Cut down our slot time */
5260 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5261 				} else {
5262 					bbr->r_ctl.rc_last_delay_val = 0;
5263 				}
5264 				bbr->rc_pacer_started = cts;
5265 			}
5266 		}
5267 		bbr->rc_timer_first = 0;
5268 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5269 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5270 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5271 	}
5272 }
5273 
5274 static int
5275 bbr_stopall(struct tcpcb *tp)
5276 {
5277 	struct tcp_bbr *bbr;
5278 
5279 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5280 	bbr->rc_all_timers_stopped = 1;
5281 
5282 	tcp_hpts_remove(tp);
5283 
5284 	return (0);
5285 }
5286 
5287 static uint32_t
5288 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5289 {
5290 	struct bbr_sendmap *rsm;
5291 
5292 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5293 	if ((rsm == NULL) || (u_rsm == rsm))
5294 		return (cts);
5295 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5296 }
5297 
5298 static void
5299 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5300      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5301 {
5302 	int32_t idx;
5303 
5304 	rsm->r_rtr_cnt++;
5305 	rsm->r_dupack = 0;
5306 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5307 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5308 		rsm->r_flags |= BBR_OVERMAX;
5309 	}
5310 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5311 		/* Take off the collapsed flag at rxt */
5312 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5313 	}
5314 	if (rsm->r_flags & BBR_MARKED_LOST) {
5315 		/* We have retransmitted, its no longer lost */
5316 		rsm->r_flags &= ~BBR_MARKED_LOST;
5317 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5318 	}
5319 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5320 		/*
5321 		 * We hit a RXT timer on it and
5322 		 * we cleared the "acked" flag.
5323 		 * We now have it going back into
5324 		 * flight, we can remove the cleared
5325 		 * flag and possibly do accounting on
5326 		 * this piece.
5327 		 */
5328 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5329 	}
5330 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5331 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5332 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5333 	}
5334 	idx = rsm->r_rtr_cnt - 1;
5335 	rsm->r_tim_lastsent[idx] = cts;
5336 	rsm->r_pacing_delay = pacing_time;
5337 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5338 	rsm->r_ts_valid = bbr->rc_ts_valid;
5339 	if (bbr->rc_ts_valid)
5340 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5341 	if (bbr->r_ctl.r_app_limited_until)
5342 		rsm->r_app_limited = 1;
5343 	else
5344 		rsm->r_app_limited = 0;
5345 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5346 		rsm->r_bbr_state = bbr_state_val(bbr);
5347 	else
5348 		rsm->r_bbr_state = 8;
5349 	if (rsm->r_flags & BBR_ACKED) {
5350 		/* Problably MTU discovery messing with us */
5351 		uint32_t old_flags;
5352 
5353 		old_flags = rsm->r_flags;
5354 		rsm->r_flags &= ~BBR_ACKED;
5355 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5356 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5357 		if (bbr->r_ctl.rc_sacked == 0)
5358 			bbr->r_ctl.rc_sacklast = NULL;
5359 	}
5360 	if (rsm->r_in_tmap) {
5361 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5362 	}
5363 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5364 	rsm->r_in_tmap = 1;
5365 	if (rsm->r_flags & BBR_SACK_PASSED) {
5366 		/* We have retransmitted due to the SACK pass */
5367 		rsm->r_flags &= ~BBR_SACK_PASSED;
5368 		rsm->r_flags |= BBR_WAS_SACKPASS;
5369 	}
5370 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5371 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5372 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5373 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5374 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5375 		rsm->r_is_gain = 1;
5376 		rsm->r_is_drain = 0;
5377 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5378 		rsm->r_is_drain = 1;
5379 		rsm->r_is_gain = 0;
5380 	} else {
5381 		rsm->r_is_drain = 0;
5382 		rsm->r_is_gain = 0;
5383 	}
5384 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5385 }
5386 
5387 /*
5388  * Returns 0, or the sequence where we stopped
5389  * updating. We also update the lenp to be the amount
5390  * of data left.
5391  */
5392 
5393 static uint32_t
5394 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5395     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5396 {
5397 	/*
5398 	 * We (re-)transmitted starting at rsm->r_start for some length
5399 	 * (possibly less than r_end.
5400 	 */
5401 	struct bbr_sendmap *nrsm;
5402 	uint32_t c_end;
5403 	int32_t len;
5404 
5405 	len = *lenp;
5406 	c_end = rsm->r_start + len;
5407 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5408 		/*
5409 		 * We retransmitted the whole piece or more than the whole
5410 		 * slopping into the next rsm.
5411 		 */
5412 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5413 		if (c_end == rsm->r_end) {
5414 			*lenp = 0;
5415 			return (0);
5416 		} else {
5417 			int32_t act_len;
5418 
5419 			/* Hangs over the end return whats left */
5420 			act_len = rsm->r_end - rsm->r_start;
5421 			*lenp = (len - act_len);
5422 			return (rsm->r_end);
5423 		}
5424 		/* We don't get out of this block. */
5425 	}
5426 	/*
5427 	 * Here we retransmitted less than the whole thing which means we
5428 	 * have to split this into what was transmitted and what was not.
5429 	 */
5430 	nrsm = bbr_alloc_full_limit(bbr);
5431 	if (nrsm == NULL) {
5432 		*lenp = 0;
5433 		return (0);
5434 	}
5435 	/*
5436 	 * So here we are going to take the original rsm and make it what we
5437 	 * retransmitted. nrsm will be the tail portion we did not
5438 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5439 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5440 	 * 1, 6 and the new piece will be 6, 11.
5441 	 */
5442 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5443 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5444 	nrsm->r_dupack = 0;
5445 	if (rsm->r_in_tmap) {
5446 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5447 		nrsm->r_in_tmap = 1;
5448 	}
5449 	rsm->r_flags &= (~BBR_HAS_FIN);
5450 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5451 	*lenp = 0;
5452 	return (0);
5453 }
5454 
5455 static uint64_t
5456 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5457 {
5458 	uint64_t bw;
5459 
5460 	bw = bbr_get_bw(bbr);
5461 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5462 	bw /= (uint64_t)BBR_UNIT;
5463 	return(bw);
5464 }
5465 
5466 static void
5467 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5468 		       uint64_t act_rate, uint64_t rate_wanted)
5469 {
5470 	/*
5471 	 * We could not get a full gains worth
5472 	 * of rate.
5473 	 */
5474 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5475 		/* we can't even get the real rate */
5476 		uint64_t red;
5477 
5478 		bbr->skip_gain = 1;
5479 		bbr->gain_is_limited = 0;
5480 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5481 		if (red)
5482 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5483 	} else {
5484 		/* We can use a lower gain */
5485 		bbr->skip_gain = 0;
5486 		bbr->gain_is_limited = 1;
5487 	}
5488 }
5489 
5490 static void
5491 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5492 {
5493 	const struct tcp_hwrate_limit_table *nrte;
5494 	int error, rate = -1;
5495 
5496 	if (bbr->r_ctl.crte == NULL)
5497 		return;
5498 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5499 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5500 		/* Lost our routes? */
5501 		/* Clear the way for a re-attempt */
5502 		bbr->bbr_attempt_hdwr_pace = 0;
5503 lost_rate:
5504 		bbr->gain_is_limited = 0;
5505 		bbr->skip_gain = 0;
5506 		bbr->bbr_hdrw_pacing = 0;
5507 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5508 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5509 		tcp_bbr_tso_size_check(bbr, cts);
5510 		return;
5511 	}
5512 	rate = bbr_get_hardware_rate(bbr);
5513 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5514 				   bbr->rc_tp,
5515 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5516 				   rate,
5517 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5518 				   &error, NULL);
5519 	if (nrte == NULL) {
5520 		goto lost_rate;
5521 	}
5522 	if (nrte != bbr->r_ctl.crte) {
5523 		bbr->r_ctl.crte = nrte;
5524 		if (error == 0)  {
5525 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5526 			if (bbr->r_ctl.crte->rate < rate) {
5527 				/* We have a problem */
5528 				bbr_setup_less_of_rate(bbr, cts,
5529 						       bbr->r_ctl.crte->rate, rate);
5530 			} else {
5531 				/* We are good */
5532 				bbr->gain_is_limited = 0;
5533 				bbr->skip_gain = 0;
5534 			}
5535 		} else {
5536 			/* A failure should release the tag */
5537 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5538 			bbr->gain_is_limited = 0;
5539 			bbr->skip_gain = 0;
5540 			bbr->bbr_hdrw_pacing = 0;
5541 		}
5542 		bbr_type_log_hdwr_pacing(bbr,
5543 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5544 					 rate,
5545 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5546 					 __LINE__,
5547 					 cts,
5548 					 error);
5549 	}
5550 }
5551 
5552 static void
5553 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5554 {
5555 	/*
5556 	 * If we have hardware pacing support
5557 	 * we need to factor that in for our
5558 	 * TSO size.
5559 	 */
5560 	const struct tcp_hwrate_limit_table *rlp;
5561 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5562 
5563 	if ((bbr->bbr_hdrw_pacing == 0) ||
5564 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5565 	    (bbr->r_ctl.crte == NULL))
5566 		return;
5567 	if (bbr->hw_pacing_set == 0) {
5568 		/* Not yet by the hdwr pacing count delay */
5569 		return;
5570 	}
5571 	if (bbr_hdwr_pace_adjust == 0) {
5572 		/* No adjustment */
5573 		return;
5574 	}
5575 	rlp = bbr->r_ctl.crte;
5576 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5577 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5578 	else
5579 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5580 	/*
5581 	 * So lets first get the
5582 	 * time we will take between
5583 	 * TSO sized sends currently without
5584 	 * hardware help.
5585 	 */
5586 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5587 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5588 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5589 	hdwr_delay *= rlp->time_between;
5590 	if (cur_delay > hdwr_delay)
5591 		delta = cur_delay - hdwr_delay;
5592 	else
5593 		delta = 0;
5594 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5595 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5596 			     1);
5597 	if (delta &&
5598 	    (delta < (max(rlp->time_between,
5599 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5600 		/*
5601 		 * Now lets divide by the pacing
5602 		 * time between each segment the
5603 		 * hardware sends rounding up and
5604 		 * derive a bytes from that. We multiply
5605 		 * that by bbr_hdwr_pace_adjust to get
5606 		 * more bang for our buck.
5607 		 *
5608 		 * The goal is to have the software pacer
5609 		 * waiting no more than an additional
5610 		 * pacing delay if we can (without the
5611 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5612 		 */
5613 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5614 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5615 		seg_sz *= bbr_hdwr_pace_adjust;
5616 		if (bbr_hdwr_pace_floor &&
5617 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5618 			/* Currently hardware paces
5619 			 * out rs_min_seg segments at a time.
5620 			 * We need to make sure we always send at least
5621 			 * a full burst of bbr_hdwr_pace_floor down.
5622 			 */
5623 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5624 		}
5625 		seg_sz *= maxseg;
5626 	} else if (delta == 0) {
5627 		/*
5628 		 * The highest pacing rate is
5629 		 * above our b/w gained. This means
5630 		 * we probably are going quite fast at
5631 		 * the hardware highest rate. Lets just multiply
5632 		 * the calculated TSO size by the
5633 		 * multiplier factor (its probably
5634 		 * 4 segments in the default config for
5635 		 * mlx).
5636 		 */
5637 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5638 		if (bbr_hdwr_pace_floor &&
5639 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5640 			/* Currently hardware paces
5641 			 * out rs_min_seg segments at a time.
5642 			 * We need to make sure we always send at least
5643 			 * a full burst of bbr_hdwr_pace_floor down.
5644 			 */
5645 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5646 		}
5647 	} else {
5648 		/*
5649 		 * The pacing time difference is so
5650 		 * big that the hardware will
5651 		 * pace out more rapidly then we
5652 		 * really want and then we
5653 		 * will have a long delay. Lets just keep
5654 		 * the same TSO size so its as if
5655 		 * we were not using hdwr pacing (we
5656 		 * just gain a bit of spacing from the
5657 		 * hardware if seg_sz > 1).
5658 		 */
5659 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5660 	}
5661 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5662 		new_tso = seg_sz;
5663 	else
5664 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5665 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5666 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5667 
5668 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5669 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5670 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5671 	}
5672 }
5673 
5674 static void
5675 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5676 {
5677 	uint64_t bw;
5678 	uint32_t old_tso = 0, new_tso;
5679 	uint32_t maxseg, bytes;
5680 	uint32_t tls_seg=0;
5681 	/*
5682 	 * Google/linux uses the following algorithm to determine
5683 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5684 	 *
5685 	 *  bytes = bw_in_bytes_per_second / 1000
5686 	 *  bytes = min(bytes, 64k)
5687 	 *  tso_segs = bytes / MSS
5688 	 *  if (bw < 1.2Mbs)
5689 	 *      min_tso_segs = 1
5690 	 *  else
5691 	 *	min_tso_segs = 2
5692 	 * tso_segs = max(tso_segs, min_tso_segs)
5693 	 *
5694 	 * * Note apply a device specific limit (we apply this in the
5695 	 *   tcp_m_copym).
5696 	 * Note that before the initial measurement is made google bursts out
5697 	 * a full iwnd just like new-reno/cubic.
5698 	 *
5699 	 * We do not use this algorithm. Instead we
5700 	 * use a two phased approach:
5701 	 *
5702 	 *  if ( bw <= per-tcb-cross-over)
5703 	 *     goal_tso =  calculate how much with this bw we
5704 	 *                 can send in goal-time seconds.
5705 	 *     if (goal_tso > mss)
5706 	 *         seg = goal_tso / mss
5707 	 *         tso = seg * mss
5708 	 *     else
5709 	 *         tso = mss
5710 	 *     if (tso > per-tcb-max)
5711 	 *         tso = per-tcb-max
5712 	 *  else if ( bw > 512Mbps)
5713 	 *     tso = max-tso (64k/mss)
5714 	 *  else
5715 	 *     goal_tso = bw / per-tcb-divsor
5716 	 *     seg = (goal_tso + mss-1)/mss
5717 	 *     tso = seg * mss
5718 	 *
5719 	 * if (tso < per-tcb-floor)
5720 	 *    tso = per-tcb-floor
5721 	 * if (tso > per-tcb-utter_max)
5722 	 *    tso = per-tcb-utter_max
5723 	 *
5724 	 * Note the default per-tcb-divisor is 1000 (same as google).
5725 	 * the goal cross over is 30Mbps however. To recreate googles
5726 	 * algorithm you need to set:
5727 	 *
5728 	 * cross-over = 23,168,000 bps
5729 	 * goal-time = 18000
5730 	 * per-tcb-max = 2
5731 	 * per-tcb-divisor = 1000
5732 	 * per-tcb-floor = 1
5733 	 *
5734 	 * This will get you "google bbr" behavior with respect to tso size.
5735 	 *
5736 	 * Note we do set anything TSO size until we are past the initial
5737 	 * window. Before that we gnerally use either a single MSS
5738 	 * or we use the full IW size (so we burst a IW at a time)
5739 	 */
5740 
5741 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5742 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5743 	} else {
5744 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5745 	}
5746 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5747 	if (bbr->rc_past_init_win == 0) {
5748 		/*
5749 		 * Not enough data has been acknowledged to make a
5750 		 * judgement. Set up the initial TSO based on if we
5751 		 * are sending a full IW at once or not.
5752 		 */
5753 		if (bbr->rc_use_google)
5754 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5755 		else if (bbr->bbr_init_win_cheat)
5756 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5757 		else
5758 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5759 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5760 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5761 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5762 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5763 		}
5764 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5765 			bbr_adjust_for_hw_pacing(bbr, cts);
5766 		return;
5767 	}
5768 	/**
5769 	 * Now lets set the TSO goal based on our delivery rate in
5770 	 * bytes per second. Note we only do this if
5771 	 * we have acked at least the initial cwnd worth of data.
5772 	 */
5773 	bw = bbr_get_bw(bbr);
5774 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5775 	     (bbr->rc_use_google == 0)) {
5776 		/* We clamp to one MSS in recovery */
5777 		new_tso = maxseg;
5778 	} else if (bbr->rc_use_google) {
5779 		int min_tso_segs;
5780 
5781 		/* Google considers the gain too */
5782 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5783 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5784 			bw /= BBR_UNIT;
5785 		}
5786 		bytes = bw / 1024;
5787 		if (bytes > (64 * 1024))
5788 			bytes = 64 * 1024;
5789 		new_tso = bytes / maxseg;
5790 		if (bw < ONE_POINT_TWO_MEG)
5791 			min_tso_segs = 1;
5792 		else
5793 			min_tso_segs = 2;
5794 		if (new_tso < min_tso_segs)
5795 			new_tso = min_tso_segs;
5796 		new_tso *= maxseg;
5797 	} else if (bbr->rc_no_pacing) {
5798 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5799 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5800 		/*
5801 		 * Calculate the worse case b/w TSO if we are inserting no
5802 		 * more than a delay_target number of TSO's.
5803 		 */
5804 		uint32_t tso_len, min_tso;
5805 
5806 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5807 		if (tso_len > maxseg) {
5808 			new_tso = tso_len / maxseg;
5809 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5810 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5811 			new_tso *= maxseg;
5812 		} else {
5813 			/*
5814 			 * less than a full sized frame yikes.. long rtt or
5815 			 * low bw?
5816 			 */
5817 			min_tso = bbr_minseg(bbr);
5818 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5819 				new_tso = rounddown(tso_len, min_tso);
5820 			else
5821 				new_tso = min_tso;
5822 		}
5823 	} else if (bw > FIVETWELVE_MBPS) {
5824 		/*
5825 		 * This guy is so fast b/w wise that we can TSO as large as
5826 		 * possible of segments that the NIC will allow.
5827 		 */
5828 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5829 	} else {
5830 		/*
5831 		 * This formula is based on attempting to send a segment or
5832 		 * more every bbr_hptsi_per_second. The default is 1000
5833 		 * which means you are targeting what you can send every 1ms
5834 		 * based on the peers bw.
5835 		 *
5836 		 * If the number drops to say 500, then you are looking more
5837 		 * at 2ms and you will raise how much we send in a single
5838 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5839 		 * trade off of course is you will send more at once and
5840 		 * thus tend to clump up the sends into larger "bursts"
5841 		 * building a queue.
5842 		 */
5843 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5844 		new_tso = roundup(bw, (uint64_t)maxseg);
5845 		/*
5846 		 * Gate the floor to match what our lower than 48Mbps
5847 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5848 		 * becomes the floor for this calculation.
5849 		 */
5850 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5851 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5852 	}
5853 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5854 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5855 	if (new_tso > PACE_MAX_IP_BYTES)
5856 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5857 	/* Enforce an utter maximum. */
5858 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5859 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5860 	}
5861 	if (old_tso != new_tso) {
5862 		/* Only log changes */
5863 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5864 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5865 	}
5866 	/* We have hardware pacing! */
5867 	bbr_adjust_for_hw_pacing(bbr, cts);
5868 }
5869 
5870 static void
5871 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5872     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5873     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5874     struct sockbuf *sb)
5875 {
5876 
5877 	struct bbr_sendmap *rsm, *nrsm;
5878 	register uint32_t snd_max, snd_una;
5879 	uint32_t pacing_time;
5880 	/*
5881 	 * Add to the RACK log of packets in flight or retransmitted. If
5882 	 * there is a TS option we will use the TS echoed, if not we will
5883 	 * grab a TS.
5884 	 *
5885 	 * Retransmissions will increment the count and move the ts to its
5886 	 * proper place. Note that if options do not include TS's then we
5887 	 * won't be able to effectively use the ACK for an RTT on a retran.
5888 	 *
5889 	 * Notes about r_start and r_end. Lets consider a send starting at
5890 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5891 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5892 	 * This means that r_end is actually the first sequence for the next
5893 	 * slot (11).
5894 	 *
5895 	 */
5896 	INP_WLOCK_ASSERT(tptoinpcb(tp));
5897 	if (err) {
5898 		/*
5899 		 * We don't log errors -- we could but snd_max does not
5900 		 * advance in this case either.
5901 		 */
5902 		return;
5903 	}
5904 	if (th_flags & TH_RST) {
5905 		/*
5906 		 * We don't log resets and we return immediately from
5907 		 * sending
5908 		 */
5909 		*abandon = 1;
5910 		return;
5911 	}
5912 	snd_una = tp->snd_una;
5913 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5914 		/*
5915 		 * The call to bbr_log_output is made before bumping
5916 		 * snd_max. This means we can record one extra byte on a SYN
5917 		 * or FIN if seq_out is adding more on and a FIN is present
5918 		 * (and we are not resending).
5919 		 */
5920 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5921 			len++;
5922 		if (th_flags & TH_FIN)
5923 			len++;
5924 	}
5925 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5926 		/* Are sending an old segment to induce an ack (keep-alive)? */
5927 		return;
5928 	}
5929 	if (SEQ_LT(seq_out, snd_una)) {
5930 		/* huh? should we panic? */
5931 		uint32_t end;
5932 
5933 		end = seq_out + len;
5934 		seq_out = snd_una;
5935 		len = end - seq_out;
5936 	}
5937 	snd_max = tp->snd_max;
5938 	if (len == 0) {
5939 		/* We don't log zero window probes */
5940 		return;
5941 	}
5942 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5943 	/* First question is it a retransmission? */
5944 	if (seq_out == snd_max) {
5945 again:
5946 		rsm = bbr_alloc(bbr);
5947 		if (rsm == NULL) {
5948 			return;
5949 		}
5950 		rsm->r_flags = 0;
5951 		if (th_flags & TH_SYN)
5952 			rsm->r_flags |= BBR_HAS_SYN;
5953 		if (th_flags & TH_FIN)
5954 			rsm->r_flags |= BBR_HAS_FIN;
5955 		rsm->r_tim_lastsent[0] = cts;
5956 		rsm->r_rtr_cnt = 1;
5957 		rsm->r_rtr_bytes = 0;
5958 		rsm->r_start = seq_out;
5959 		rsm->r_end = rsm->r_start + len;
5960 		rsm->r_dupack = 0;
5961 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5962 		rsm->r_pacing_delay = pacing_time;
5963 		rsm->r_ts_valid = bbr->rc_ts_valid;
5964 		if (bbr->rc_ts_valid)
5965 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5966 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
5967 		if (bbr->r_ctl.r_app_limited_until)
5968 			rsm->r_app_limited = 1;
5969 		else
5970 			rsm->r_app_limited = 0;
5971 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5972 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5973 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5974 		/*
5975 		 * Here we must also add in this rsm since snd_max
5976 		 * is updated after we return from a new send.
5977 		 */
5978 		rsm->r_flight_at_send += len;
5979 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
5980 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5981 		rsm->r_in_tmap = 1;
5982 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5983 			rsm->r_bbr_state = bbr_state_val(bbr);
5984 		else
5985 			rsm->r_bbr_state = 8;
5986 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5987 			rsm->r_is_gain = 1;
5988 			rsm->r_is_drain = 0;
5989 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5990 			rsm->r_is_drain = 1;
5991 			rsm->r_is_gain = 0;
5992 		} else {
5993 			rsm->r_is_drain = 0;
5994 			rsm->r_is_gain = 0;
5995 		}
5996 		return;
5997 	}
5998 	/*
5999 	 * If we reach here its a retransmission and we need to find it.
6000 	 */
6001 more:
6002 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6003 		rsm = hintrsm;
6004 		hintrsm = NULL;
6005 	} else if (bbr->r_ctl.rc_next) {
6006 		/* We have a hint from a previous run */
6007 		rsm = bbr->r_ctl.rc_next;
6008 	} else {
6009 		/* No hints sorry */
6010 		rsm = NULL;
6011 	}
6012 	if ((rsm) && (rsm->r_start == seq_out)) {
6013 		/*
6014 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6015 		 * likely case.
6016 		 */
6017 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6018 		if (len == 0) {
6019 			return;
6020 		} else {
6021 			goto more;
6022 		}
6023 	}
6024 	/* Ok it was not the last pointer go through it the hard way. */
6025 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6026 		if (rsm->r_start == seq_out) {
6027 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6028 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6029 			if (len == 0) {
6030 				return;
6031 			} else {
6032 				continue;
6033 			}
6034 		}
6035 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6036 			/* Transmitted within this piece */
6037 			/*
6038 			 * Ok we must split off the front and then let the
6039 			 * update do the rest
6040 			 */
6041 			nrsm = bbr_alloc_full_limit(bbr);
6042 			if (nrsm == NULL) {
6043 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6044 				return;
6045 			}
6046 			/*
6047 			 * copy rsm to nrsm and then trim the front of rsm
6048 			 * to not include this part.
6049 			 */
6050 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6051 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6052 			if (rsm->r_in_tmap) {
6053 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6054 				nrsm->r_in_tmap = 1;
6055 			}
6056 			rsm->r_flags &= (~BBR_HAS_FIN);
6057 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6058 			if (len == 0) {
6059 				return;
6060 			}
6061 		}
6062 	}
6063 	/*
6064 	 * Hmm not found in map did they retransmit both old and on into the
6065 	 * new?
6066 	 */
6067 	if (seq_out == tp->snd_max) {
6068 		goto again;
6069 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6070 #ifdef BBR_INVARIANTS
6071 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6072 		    seq_out, len, tp->snd_una, tp->snd_max);
6073 		printf("Starting Dump of all rack entries\n");
6074 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6075 			printf("rsm:%p start:%u end:%u\n",
6076 			    rsm, rsm->r_start, rsm->r_end);
6077 		}
6078 		printf("Dump complete\n");
6079 		panic("seq_out not found rack:%p tp:%p",
6080 		    bbr, tp);
6081 #endif
6082 	} else {
6083 #ifdef BBR_INVARIANTS
6084 		/*
6085 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6086 		 * flag)
6087 		 */
6088 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6089 		    seq_out, len, tp->snd_max, tp);
6090 #endif
6091 	}
6092 }
6093 
6094 static void
6095 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6096 {
6097 	/*
6098 	 * Collapse timeout back the cum-ack moved.
6099 	 */
6100 	tp->t_rxtshift = 0;
6101 	tp->t_softerror = 0;
6102 }
6103 
6104 static void
6105 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6106 {
6107 	bbr->rtt_valid = 1;
6108 	bbr->r_ctl.cur_rtt = rtt_usecs;
6109 	bbr->r_ctl.ts_in = tsin;
6110 	if (rsm_send_time)
6111 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6112 }
6113 
6114 static void
6115 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6116 {
6117 	/**
6118 	 * We have in our bbr control:
6119 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6120 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6121 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6122 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6123 	 *
6124 	 * Now we can calculate the time between the sends by doing:
6125 	 *
6126 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6127 	 *
6128 	 * And the peer's time between receiving them by doing:
6129 	 *
6130 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6131 	 *
6132 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6133 	 * We also may find that we can't use the timestamps if say we see
6134 	 * that the peer_delta indicates that though we may have taken 10ms to
6135 	 * pace out the data, it only saw 1ms between the two packets. This would
6136 	 * indicate that somewhere on the path is a batching entity that is giving
6137 	 * out time-slices of the actual b/w. This would mean we could not use
6138 	 * reliably the peers timestamps.
6139 	 *
6140 	 * We expect delta > peer_delta initially. Until we figure out the
6141 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6142 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6143 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6144 	 * put a 1 there. If the value is faster then ours, we will disable the
6145 	 * use of timestamps (though we could revist this later if we find it to be not
6146 	 * just an isolated one or two flows)).
6147 	 *
6148 	 * To detect the batching middle boxes we will come up with our compensation and
6149 	 * if with it in place, we find the peer is drastically off (by some margin) in
6150 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6151 	 *
6152 	 */
6153 	uint64_t delta, peer_delta, delta_up;
6154 
6155 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6156 	if (delta < bbr_min_usec_delta) {
6157 		/*
6158 		 * Have not seen a min amount of time
6159 		 * between our send times so we can
6160 		 * make a determination of the timestamp
6161 		 * yet.
6162 		 */
6163 		return;
6164 	}
6165 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6166 	if (peer_delta < bbr_min_peer_delta) {
6167 		/*
6168 		 * We may have enough in the form of
6169 		 * our delta but the peers number
6170 		 * has not changed that much. It could
6171 		 * be its clock ratio is such that
6172 		 * we need more data (10ms tick) or
6173 		 * there may be other compression scenarios
6174 		 * going on. In any event we need the
6175 		 * spread to be larger.
6176 		 */
6177 		return;
6178 	}
6179 	/* Ok lets first see which way our delta is going */
6180 	if (peer_delta > delta) {
6181 		/* Very unlikely, the peer without
6182 		 * compensation shows that it saw
6183 		 * the two sends arrive further apart
6184 		 * then we saw then in micro-seconds.
6185 		 */
6186 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6187 			/* well it looks like the peer is a micro-second clock. */
6188 			bbr->rc_ts_clock_set = 1;
6189 			bbr->r_ctl.bbr_peer_tsratio = 1;
6190 		} else {
6191 			bbr->rc_ts_cant_be_used = 1;
6192 			bbr->rc_ts_clock_set = 1;
6193 		}
6194 		return;
6195 	}
6196 	/* Ok we know that the peer_delta is smaller than our send distance */
6197 	bbr->rc_ts_clock_set = 1;
6198 	/* First question is it within the percentage that they are using usec time? */
6199 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6200 	if ((peer_delta + delta_up) >= delta) {
6201 		/* Its a usec clock */
6202 		bbr->r_ctl.bbr_peer_tsratio = 1;
6203 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6204 		return;
6205 	}
6206 	/* Ok if not usec, what about 10usec (though unlikely)? */
6207 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6208 	if (((peer_delta * 10) + delta_up) >= delta) {
6209 		bbr->r_ctl.bbr_peer_tsratio = 10;
6210 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6211 		return;
6212 	}
6213 	/* And what about 100usec (though again unlikely)? */
6214 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6215 	if (((peer_delta * 100) + delta_up) >= delta) {
6216 		bbr->r_ctl.bbr_peer_tsratio = 100;
6217 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6218 		return;
6219 	}
6220 	/* And how about 1 msec (the most likely one)? */
6221 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6222 	if (((peer_delta * 1000) + delta_up) >= delta) {
6223 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6224 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6225 		return;
6226 	}
6227 	/* Ok if not msec could it be 10 msec? */
6228 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6229 	if (((peer_delta * 10000) + delta_up) >= delta) {
6230 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6231 		return;
6232 	}
6233 	/* If we fall down here the clock tick so slowly we can't use it */
6234 	bbr->rc_ts_cant_be_used = 1;
6235 	bbr->r_ctl.bbr_peer_tsratio = 0;
6236 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6237 }
6238 
6239 /*
6240  * Collect new round-trip time estimate
6241  * and update averages and current timeout.
6242  */
6243 static void
6244 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6245 {
6246 	int32_t delta;
6247 	uint32_t rtt, tsin;
6248 	int32_t rtt_ticks;
6249 
6250 	if (bbr->rtt_valid == 0)
6251 		/* No valid sample */
6252 		return;
6253 
6254 	rtt = bbr->r_ctl.cur_rtt;
6255 	tsin = bbr->r_ctl.ts_in;
6256 	if (bbr->rc_prtt_set_ts) {
6257 		/*
6258 		 * We are to force feed the rttProp filter due
6259 		 * to an entry into PROBE_RTT. This assures
6260 		 * that the times are sync'd between when we
6261 		 * go into PROBE_RTT and the filter expiration.
6262 		 *
6263 		 * Google does not use a true filter, so they do
6264 		 * this implicitly since they only keep one value
6265 		 * and when they enter probe-rtt they update the
6266 		 * value to the newest rtt.
6267 		 */
6268 		uint32_t rtt_prop;
6269 
6270 		bbr->rc_prtt_set_ts = 0;
6271 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6272 		if (rtt > rtt_prop)
6273 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6274 		else
6275 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6276 	}
6277 #ifdef STATS
6278 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_PATHRTT, imax(0, rtt));
6279 #endif
6280 	if (bbr->rc_ack_was_delayed)
6281 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6282 
6283 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6284 		bbr->r_ctl.rc_lowest_rtt = rtt;
6285 	bbr_log_rtt_sample(bbr, rtt, tsin);
6286 	if (bbr->r_init_rtt) {
6287 		/*
6288 		 * The initial rtt is not-trusted, nuke it and lets get
6289 		 * our first valid measurement in.
6290 		 */
6291 		bbr->r_init_rtt = 0;
6292 		tp->t_srtt = 0;
6293 	}
6294 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6295 		/*
6296 		 * So we have not yet figured out
6297 		 * what the peers TSTMP value is
6298 		 * in (most likely ms). We need a
6299 		 * series of cum-ack's to determine
6300 		 * this reliably.
6301 		 */
6302 		if (bbr->rc_ack_is_cumack) {
6303 			if (bbr->rc_ts_data_set) {
6304 				/* Lets attempt to determine the timestamp granularity. */
6305 				bbr_make_timestamp_determination(bbr);
6306 			} else {
6307 				bbr->rc_ts_data_set = 1;
6308 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6309 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6310 			}
6311 		} else {
6312 			/*
6313 			 * We have to have consecutive acks
6314 			 * reset any "filled" state to none.
6315 			 */
6316 			bbr->rc_ts_data_set = 0;
6317 		}
6318 	}
6319 	/* Round it up */
6320 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6321 	if (rtt_ticks == 0)
6322 		rtt_ticks = 1;
6323 	if (tp->t_srtt != 0) {
6324 		/*
6325 		 * srtt is stored as fixed point with 5 bits after the
6326 		 * binary point (i.e., scaled by 8).  The following magic is
6327 		 * equivalent to the smoothing algorithm in rfc793 with an
6328 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6329 		 * Adjust rtt to origin 0.
6330 		 */
6331 
6332 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6333 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6334 
6335 		tp->t_srtt += delta;
6336 		if (tp->t_srtt <= 0)
6337 			tp->t_srtt = 1;
6338 
6339 		/*
6340 		 * We accumulate a smoothed rtt variance (actually, a
6341 		 * smoothed mean difference), then set the retransmit timer
6342 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6343 		 * is stored as fixed point with 4 bits after the binary
6344 		 * point (scaled by 16).  The following is equivalent to
6345 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6346 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6347 		 * wired-in beta.
6348 		 */
6349 		if (delta < 0)
6350 			delta = -delta;
6351 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6352 		tp->t_rttvar += delta;
6353 		if (tp->t_rttvar <= 0)
6354 			tp->t_rttvar = 1;
6355 	} else {
6356 		/*
6357 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6358 		 * variance to half the rtt (so our first retransmit happens
6359 		 * at 3*rtt).
6360 		 */
6361 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6362 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6363 	}
6364 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6365 	if (tp->t_rttupdated < UCHAR_MAX)
6366 		tp->t_rttupdated++;
6367 #ifdef STATS
6368 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6369 #endif
6370 	/*
6371 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6372 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6373 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6374 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6375 	 * uncertainty in the firing of the timer.  The bias will give us
6376 	 * exactly the 1.5 tick we need.  But, because the bias is
6377 	 * statistical, we have to test that we don't drop below the minimum
6378 	 * feasible timer (which is 2 ticks).
6379 	 */
6380 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6381 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6382 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6383 
6384 	/*
6385 	 * We received an ack for a packet that wasn't retransmitted; it is
6386 	 * probably safe to discard any error indications we've received
6387 	 * recently.  This isn't quite right, but close enough for now (a
6388 	 * route might have failed after we sent a segment, and the return
6389 	 * path might not be symmetrical).
6390 	 */
6391 	tp->t_softerror = 0;
6392 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6393 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6394 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6395 }
6396 
6397 static void
6398 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6399 {
6400 	bbr->r_ctl.rc_rtt_shrinks = cts;
6401 	if (bbr_can_force_probertt &&
6402 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6403 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6404 		/*
6405 		 * We should enter probe-rtt its been too long
6406 		 * since we have been there.
6407 		 */
6408 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6409 	} else
6410 		bbr_check_probe_rtt_limits(bbr, cts);
6411 }
6412 
6413 static void
6414 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6415 {
6416 	uint64_t orig_bw;
6417 
6418 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6419 		/* We never apply a zero measurement */
6420 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6421 				    0, 0, 0, 0, 0, 0);
6422 		return;
6423 	}
6424 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6425 		bbr->r_ctl.r_measurement_count++;
6426 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6427 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6428 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6429 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6430 			    0, 0, 0, 0, 0, 0);
6431 	if (orig_bw &&
6432 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6433 		if (bbr->bbr_hdrw_pacing) {
6434 			/*
6435 			 * Apply a new rate to the hardware
6436 			 * possibly.
6437 			 */
6438 			bbr_update_hardware_pacing_rate(bbr, cts);
6439 		}
6440 		bbr_set_state_target(bbr, __LINE__);
6441 		tcp_bbr_tso_size_check(bbr, cts);
6442 		if (bbr->r_recovery_bw)  {
6443 			bbr_setup_red_bw(bbr, cts);
6444 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6445 		}
6446 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6447 		tcp_bbr_tso_size_check(bbr, cts);
6448 }
6449 
6450 static void
6451 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6452 {
6453 	if (bbr->rc_in_persist == 0) {
6454 		/* We log only when not in persist */
6455 		/* Translate to a Bytes Per Second */
6456 		uint64_t tim, bw, ts_diff, ts_bw;
6457 		uint32_t delivered;
6458 
6459 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6460 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6461 		else
6462 			tim = 1;
6463 		/*
6464 		 * Now that we have processed the tim (skipping the sample
6465 		 * or possibly updating the time, go ahead and
6466 		 * calculate the cdr.
6467 		 */
6468 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6469 		bw = (uint64_t)delivered;
6470 		bw *= (uint64_t)USECS_IN_SECOND;
6471 		bw /= tim;
6472 		if (bw == 0) {
6473 			/* We must have a calculatable amount */
6474 			return;
6475 		}
6476 		/*
6477 		 * If we are using this b/w shove it in now so we
6478 		 * can see in the trace viewer if it gets over-ridden.
6479 		 */
6480 		if (rsm->r_ts_valid &&
6481 		    bbr->rc_ts_valid &&
6482 		    bbr->rc_ts_clock_set &&
6483 		    (bbr->rc_ts_cant_be_used == 0) &&
6484 		    bbr->rc_use_ts_limit) {
6485 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6486 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6487 			if ((delivered == 0) ||
6488 			    (rtt < 1000)) {
6489 				/* Can't use the ts */
6490 				bbr_log_type_bbrupd(bbr, 61, cts,
6491 						    ts_diff,
6492 						    bbr->r_ctl.last_inbound_ts,
6493 						    rsm->r_del_ack_ts, 0,
6494 						    0, 0, 0, delivered);
6495 			} else {
6496 				ts_bw = (uint64_t)delivered;
6497 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6498 				ts_bw /= ts_diff;
6499 				bbr_log_type_bbrupd(bbr, 62, cts,
6500 						    (ts_bw >> 32),
6501 						    (ts_bw & 0xffffffff), 0, 0,
6502 						    0, 0, ts_diff, delivered);
6503 				if ((bbr->ts_can_raise) &&
6504 				    (ts_bw > bw)) {
6505 					bbr_log_type_bbrupd(bbr, 8, cts,
6506 							    delivered,
6507 							    ts_diff,
6508 							    (bw >> 32),
6509 							    (bw & 0x00000000ffffffff),
6510 							    0, 0, 0, 0);
6511 					bw = ts_bw;
6512 				} else if (ts_bw && (ts_bw < bw)) {
6513 					bbr_log_type_bbrupd(bbr, 7, cts,
6514 							    delivered,
6515 							    ts_diff,
6516 							    (bw >> 32),
6517 							    (bw & 0x00000000ffffffff),
6518 							    0, 0, 0, 0);
6519 					bw = ts_bw;
6520 				}
6521 			}
6522 		}
6523 		if (rsm->r_first_sent_time &&
6524 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6525 			uint64_t sbw, sti;
6526 			/*
6527 			 * We use what was in flight at the time of our
6528 			 * send  and the size of this send to figure
6529 			 * out what we have been sending at (amount).
6530 			 * For the time we take from the time of
6531 			 * the send of the first send outstanding
6532 			 * until this send plus this sends pacing
6533 			 * time. This gives us a good calculation
6534 			 * as to the rate we have been sending at.
6535 			 */
6536 
6537 			sbw = (uint64_t)(rsm->r_flight_at_send);
6538 			sbw *= (uint64_t)USECS_IN_SECOND;
6539 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6540 			sti += rsm->r_pacing_delay;
6541 			sbw /= sti;
6542 			if (sbw < bw) {
6543 				bbr_log_type_bbrupd(bbr, 6, cts,
6544 						    delivered,
6545 						    (uint32_t)sti,
6546 						    (bw >> 32),
6547 						    (uint32_t)bw,
6548 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6549 						    (uint32_t)sbw);
6550 				bw = sbw;
6551 			}
6552 		}
6553 		/* Use the google algorithm for b/w measurements */
6554 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6555 		if ((rsm->r_app_limited == 0) ||
6556 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6557 			tcp_bbr_commit_bw(bbr, cts);
6558 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6559 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6560 		}
6561 	}
6562 }
6563 
6564 static void
6565 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6566 {
6567 	if (bbr->rc_in_persist == 0) {
6568 		/* We log only when not in persist */
6569 		/* Translate to a Bytes Per Second */
6570 		uint64_t tim, bw;
6571 		uint32_t delivered;
6572 		int no_apply = 0;
6573 
6574 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6575 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6576 		else
6577 			tim = 1;
6578 		/*
6579 		 * Now that we have processed the tim (skipping the sample
6580 		 * or possibly updating the time, go ahead and
6581 		 * calculate the cdr.
6582 		 */
6583 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6584 		bw = (uint64_t)delivered;
6585 		bw *= (uint64_t)USECS_IN_SECOND;
6586 		bw /= tim;
6587 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6588 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6589 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6590 
6591 			no_apply = 1;
6592 		}
6593 		/*
6594 		 * If we are using this b/w shove it in now so we
6595 		 * can see in the trace viewer if it gets over-ridden.
6596 		 */
6597 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6598 		/* Gate by the sending rate */
6599 		if (rsm->r_first_sent_time &&
6600 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6601 			uint64_t sbw, sti;
6602 			/*
6603 			 * We use what was in flight at the time of our
6604 			 * send  and the size of this send to figure
6605 			 * out what we have been sending at (amount).
6606 			 * For the time we take from the time of
6607 			 * the send of the first send outstanding
6608 			 * until this send plus this sends pacing
6609 			 * time. This gives us a good calculation
6610 			 * as to the rate we have been sending at.
6611 			 */
6612 
6613 			sbw = (uint64_t)(rsm->r_flight_at_send);
6614 			sbw *= (uint64_t)USECS_IN_SECOND;
6615 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6616 			sti += rsm->r_pacing_delay;
6617 			sbw /= sti;
6618 			if (sbw < bw) {
6619 				bbr_log_type_bbrupd(bbr, 6, cts,
6620 						    delivered,
6621 						    (uint32_t)sti,
6622 						    (bw >> 32),
6623 						    (uint32_t)bw,
6624 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6625 						    (uint32_t)sbw);
6626 				bw = sbw;
6627 			}
6628 			if ((sti > tim) &&
6629 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6630 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6631 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6632 				no_apply = 1;
6633 			} else
6634 				no_apply = 0;
6635 		}
6636 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6637 		if ((no_apply == 0) &&
6638 		    ((rsm->r_app_limited == 0) ||
6639 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6640 			tcp_bbr_commit_bw(bbr, cts);
6641 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6642 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6643 		}
6644 	}
6645 }
6646 
6647 static void
6648 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6649     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6650 {
6651 	uint64_t old_rttprop;
6652 
6653 	/* Update our delivery time and amount */
6654 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6655 	bbr->r_ctl.rc_del_time = cts;
6656 	if (rtt == 0) {
6657 		/*
6658 		 * 0 means its a retransmit, for now we don't use these for
6659 		 * the rest of BBR.
6660 		 */
6661 		return;
6662 	}
6663 	if ((bbr->rc_use_google == 0) &&
6664 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6665 	    (match != BBR_RTT_BY_TIMESTAMP)){
6666 		/*
6667 		 * We get a lot of rtt updates, lets not pay attention to
6668 		 * any that are not an exact match. That way we don't have
6669 		 * to worry about timestamps and the whole nonsense of
6670 		 * unsure if its a retransmission etc (if we ever had the
6671 		 * timestamp fixed to always have the last thing sent this
6672 		 * would not be a issue).
6673 		 */
6674 		return;
6675 	}
6676 	if ((bbr_no_retran && bbr->rc_use_google) &&
6677 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6678 	    (match != BBR_RTT_BY_TIMESTAMP)){
6679 		/*
6680 		 * We only do measurements in google mode
6681 		 * with bbr_no_retran on for sure things.
6682 		 */
6683 		return;
6684 	}
6685 	/* Only update srtt if we know by exact match */
6686 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6687 	if (ack_type == BBR_CUM_ACKED)
6688 		bbr->rc_ack_is_cumack = 1;
6689 	else
6690 		bbr->rc_ack_is_cumack = 0;
6691 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6692 	/*
6693 	 * Note the following code differs to the original
6694 	 * BBR spec. It calls for <= not <. However after a
6695 	 * long discussion in email with Neal, he acknowledged
6696 	 * that it should be < than so that we will have flows
6697 	 * going into probe-rtt (we were seeing cases where that
6698 	 * did not happen and caused ugly things to occur). We
6699 	 * have added this agreed upon fix to our code base.
6700 	 */
6701 	if (rtt < old_rttprop) {
6702 		/* Update when we last saw a rtt drop */
6703 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6704 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6705 	}
6706 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6707 	    match, rsm->r_start, rsm->r_flags);
6708 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6709 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6710 		/*
6711 		 * The RTT-prop moved, reset the target (may be a
6712 		 * nop for some states).
6713 		 */
6714 		bbr_set_state_target(bbr, __LINE__);
6715 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6716 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6717 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6718 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6719 			/* It went up */
6720 			bbr_check_probe_rtt_limits(bbr, cts);
6721 	}
6722 	if ((bbr->rc_use_google == 0) &&
6723 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6724 		/*
6725 		 * We don't do b/w update with
6726 		 * these since they are not really
6727 		 * reliable.
6728 		 */
6729 		return;
6730 	}
6731 	if (bbr->r_ctl.r_app_limited_until &&
6732 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6733 		/* We are no longer app-limited */
6734 		bbr->r_ctl.r_app_limited_until = 0;
6735 	}
6736 	if (bbr->rc_use_google) {
6737 		bbr_google_measurement(bbr, rsm, rtt, cts);
6738 	} else {
6739 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6740 	}
6741 }
6742 
6743 /*
6744  * Convert a timestamp that the main stack
6745  * uses (milliseconds) into one that bbr uses
6746  * (microseconds). Return that converted timestamp.
6747  */
6748 static uint32_t
6749 bbr_ts_convert(uint32_t cts) {
6750 	uint32_t sec, msec;
6751 
6752 	sec = cts / MS_IN_USEC;
6753 	msec = cts - (MS_IN_USEC * sec);
6754 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6755 }
6756 
6757 /*
6758  * Return 0 if we did not update the RTT time, return
6759  * 1 if we did.
6760  */
6761 static int
6762 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6763     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6764 {
6765 	int32_t i;
6766 	uint32_t t, uts = 0;
6767 
6768 	if ((rsm->r_flags & BBR_ACKED) ||
6769 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6770 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6771 		/* Already done */
6772 		return (0);
6773 	}
6774 	if (rsm->r_rtt_not_allowed) {
6775 		/* Not allowed */
6776 		return (0);
6777 	}
6778 	if (rsm->r_rtr_cnt == 1) {
6779 		/*
6780 		 * Only one transmit. Hopefully the normal case.
6781 		 */
6782 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6783 			t = cts - rsm->r_tim_lastsent[0];
6784 		else
6785 			t = 1;
6786 		if ((int)t <= 0)
6787 			t = 1;
6788 		bbr->r_ctl.rc_last_rtt = t;
6789 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6790 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6791 		return (1);
6792 	}
6793 	/* Convert to usecs */
6794 	if ((bbr_can_use_ts_for_rtt == 1) &&
6795 	    (bbr->rc_use_google == 1) &&
6796 	    (ack_type == BBR_CUM_ACKED) &&
6797 	    (to->to_flags & TOF_TS) &&
6798 	    (to->to_tsecr != 0)) {
6799 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6800 		if (t < 1)
6801 			t = 1;
6802 		t *= MS_IN_USEC;
6803 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6804 				    BBR_RTT_BY_TIMESTAMP,
6805 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6806 				    ack_type, to);
6807 		return (1);
6808 	}
6809 	uts = bbr_ts_convert(to->to_tsecr);
6810 	if ((to->to_flags & TOF_TS) &&
6811 	    (to->to_tsecr != 0) &&
6812 	    (ack_type == BBR_CUM_ACKED) &&
6813 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6814 		/*
6815 		 * Now which timestamp does it match? In this block the ACK
6816 		 * may be coming from a previous transmission.
6817 		 */
6818 		uint32_t fudge;
6819 
6820 		fudge = BBR_TIMER_FUDGE;
6821 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6822 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6823 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6824 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6825 					t = cts - rsm->r_tim_lastsent[i];
6826 				else
6827 					t = 1;
6828 				if ((int)t <= 0)
6829 					t = 1;
6830 				bbr->r_ctl.rc_last_rtt = t;
6831 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6832 						    rsm->r_tim_lastsent[i], ack_type, to);
6833 				if ((i + 1) < rsm->r_rtr_cnt) {
6834 					/* Likely */
6835 					return (0);
6836 				} else if (rsm->r_flags & BBR_TLP) {
6837 					bbr->rc_tlp_rtx_out = 0;
6838 				}
6839 				return (1);
6840 			}
6841 		}
6842 		/* Fall through if we can't find a matching timestamp */
6843 	}
6844 	/*
6845 	 * Ok its a SACK block that we retransmitted. or a windows
6846 	 * machine without timestamps. We can tell nothing from the
6847 	 * time-stamp since its not there or the time the peer last
6848 	 * received a segment that moved forward its cum-ack point.
6849 	 *
6850 	 * Lets look at the last retransmit and see what we can tell
6851 	 * (with BBR for space we only keep 2 note we have to keep
6852 	 * at least 2 so the map can not be condensed more).
6853 	 */
6854 	i = rsm->r_rtr_cnt - 1;
6855 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6856 		t = cts - rsm->r_tim_lastsent[i];
6857 	else
6858 		goto not_sure;
6859 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6860 		/*
6861 		 * We retransmitted and the ack came back in less
6862 		 * than the smallest rtt we have observed in the
6863 		 * windowed rtt. We most likey did an improper
6864 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6865 		 * the rack-draft.
6866 		 *
6867 		 * Use the prior transmission to update all the
6868 		 * information as long as there is only one prior
6869 		 * transmission.
6870 		 */
6871 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6872 #ifdef BBR_INVARIANTS
6873 			if (rsm->r_rtr_cnt == 1)
6874 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6875 #endif
6876 			i = rsm->r_rtr_cnt - 2;
6877 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6878 				t = cts - rsm->r_tim_lastsent[i];
6879 			else
6880 				t = 1;
6881 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6882 					    rsm->r_tim_lastsent[i], ack_type, to);
6883 			return (0);
6884 		} else {
6885 			/*
6886 			 * Too many prior transmissions, just
6887 			 * updated BBR delivered
6888 			 */
6889 not_sure:
6890 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6891 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6892 		}
6893 	} else {
6894 		/*
6895 		 * We retransmitted it and the retransmit did the
6896 		 * job.
6897 		 */
6898 		if (rsm->r_flags & BBR_TLP)
6899 			bbr->rc_tlp_rtx_out = 0;
6900 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6901 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6902 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6903 		else
6904 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6905 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6906 		return (1);
6907 	}
6908 	return (0);
6909 }
6910 
6911 /*
6912  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6913  */
6914 static void
6915 bbr_log_sack_passed(struct tcpcb *tp,
6916     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6917 {
6918 	struct bbr_sendmap *nrsm;
6919 
6920 	nrsm = rsm;
6921 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6922 	    bbr_head, r_tnext) {
6923 		if (nrsm == rsm) {
6924 			/* Skip original segment he is acked */
6925 			continue;
6926 		}
6927 		if (nrsm->r_flags & BBR_ACKED) {
6928 			/* Skip ack'd segments */
6929 			continue;
6930 		}
6931 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6932 			/*
6933 			 * We found one that is already marked
6934 			 * passed, we have been here before and
6935 			 * so all others below this are marked.
6936 			 */
6937 			break;
6938 		}
6939 		BBR_STAT_INC(bbr_sack_passed);
6940 		nrsm->r_flags |= BBR_SACK_PASSED;
6941 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6942 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6943 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6944 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6945 			nrsm->r_flags |= BBR_MARKED_LOST;
6946 		}
6947 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6948 	}
6949 }
6950 
6951 /*
6952  * Returns the number of bytes that were
6953  * newly ack'd by sack blocks.
6954  */
6955 static uint32_t
6956 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6957     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6958 {
6959 	int32_t times = 0;
6960 	uint32_t start, end, changed = 0;
6961 	struct bbr_sendmap *rsm, *nrsm;
6962 	int32_t used_ref = 1;
6963 	uint8_t went_back = 0, went_fwd = 0;
6964 
6965 	start = sack->start;
6966 	end = sack->end;
6967 	rsm = *prsm;
6968 	if (rsm == NULL)
6969 		used_ref = 0;
6970 
6971 	/* Do we locate the block behind where we last were? */
6972 	if (rsm && SEQ_LT(start, rsm->r_start)) {
6973 		went_back = 1;
6974 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
6975 			if (SEQ_GEQ(start, rsm->r_start) &&
6976 			    SEQ_LT(start, rsm->r_end)) {
6977 				goto do_rest_ofb;
6978 			}
6979 		}
6980 	}
6981 start_at_beginning:
6982 	went_fwd = 1;
6983 	/*
6984 	 * Ok lets locate the block where this guy is fwd from rsm (if its
6985 	 * set)
6986 	 */
6987 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
6988 		if (SEQ_GEQ(start, rsm->r_start) &&
6989 		    SEQ_LT(start, rsm->r_end)) {
6990 			break;
6991 		}
6992 	}
6993 do_rest_ofb:
6994 	if (rsm == NULL) {
6995 		/*
6996 		 * This happens when we get duplicate sack blocks with the
6997 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
6998 		 * will not change there location so we would just start at
6999 		 * the end of the first one and get lost.
7000 		 */
7001 		if (tp->t_flags & TF_SENTFIN) {
7002 			/*
7003 			 * Check to see if we have not logged the FIN that
7004 			 * went out.
7005 			 */
7006 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7007 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7008 				/*
7009 				 * Ok we did not get the FIN logged.
7010 				 */
7011 				nrsm->r_end++;
7012 				rsm = nrsm;
7013 				goto do_rest_ofb;
7014 			}
7015 		}
7016 		if (times == 1) {
7017 #ifdef BBR_INVARIANTS
7018 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7019 			    tp, bbr, sack, to, prsm);
7020 #else
7021 			goto out;
7022 #endif
7023 		}
7024 		times++;
7025 		BBR_STAT_INC(bbr_sack_proc_restart);
7026 		rsm = NULL;
7027 		goto start_at_beginning;
7028 	}
7029 	/* Ok we have an ACK for some piece of rsm */
7030 	if (rsm->r_start != start) {
7031 		/*
7032 		 * Need to split this in two pieces the before and after.
7033 		 */
7034 		if (bbr_sack_mergable(rsm, start, end))
7035 			nrsm = bbr_alloc_full_limit(bbr);
7036 		else
7037 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7038 		if (nrsm == NULL) {
7039 			/* We could not allocate ignore the sack */
7040 			struct sackblk blk;
7041 
7042 			blk.start = start;
7043 			blk.end = end;
7044 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7045 			goto out;
7046 		}
7047 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7048 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7049 		if (rsm->r_in_tmap) {
7050 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7051 			nrsm->r_in_tmap = 1;
7052 		}
7053 		rsm->r_flags &= (~BBR_HAS_FIN);
7054 		rsm = nrsm;
7055 	}
7056 	if (SEQ_GEQ(end, rsm->r_end)) {
7057 		/*
7058 		 * The end of this block is either beyond this guy or right
7059 		 * at this guy.
7060 		 */
7061 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7062 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7063 			changed += (rsm->r_end - rsm->r_start);
7064 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7065 			bbr_log_sack_passed(tp, bbr, rsm);
7066 			if (rsm->r_flags & BBR_MARKED_LOST) {
7067 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7068 			}
7069 			/* Is Reordering occuring? */
7070 			if (rsm->r_flags & BBR_SACK_PASSED) {
7071 				BBR_STAT_INC(bbr_reorder_seen);
7072 				bbr->r_ctl.rc_reorder_ts = cts;
7073 				if (rsm->r_flags & BBR_MARKED_LOST) {
7074 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7075 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7076 						/* LT sampling also needs adjustment */
7077 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7078 				}
7079 			}
7080 			rsm->r_flags |= BBR_ACKED;
7081 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7082 			if (rsm->r_in_tmap) {
7083 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7084 				rsm->r_in_tmap = 0;
7085 			}
7086 		}
7087 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7088 		if (end == rsm->r_end) {
7089 			/* This block only - done */
7090 			goto out;
7091 		}
7092 		/* There is more not coverend by this rsm move on */
7093 		start = rsm->r_end;
7094 		nrsm = TAILQ_NEXT(rsm, r_next);
7095 		rsm = nrsm;
7096 		times = 0;
7097 		goto do_rest_ofb;
7098 	}
7099 	if (rsm->r_flags & BBR_ACKED) {
7100 		/* Been here done that */
7101 		goto out;
7102 	}
7103 	/* Ok we need to split off this one at the tail */
7104 	if (bbr_sack_mergable(rsm, start, end))
7105 		nrsm = bbr_alloc_full_limit(bbr);
7106 	else
7107 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7108 	if (nrsm == NULL) {
7109 		/* failed XXXrrs what can we do but loose the sack info? */
7110 		struct sackblk blk;
7111 
7112 		blk.start = start;
7113 		blk.end = end;
7114 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7115 		goto out;
7116 	}
7117 	/* Clone it */
7118 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7119 	/* The sack block does not cover this guy fully */
7120 	rsm->r_flags &= (~BBR_HAS_FIN);
7121 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7122 	if (rsm->r_in_tmap) {
7123 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7124 		nrsm->r_in_tmap = 1;
7125 	}
7126 	nrsm->r_dupack = 0;
7127 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7128 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7129 	changed += (rsm->r_end - rsm->r_start);
7130 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7131 	bbr_log_sack_passed(tp, bbr, rsm);
7132 	/* Is Reordering occuring? */
7133 	if (rsm->r_flags & BBR_MARKED_LOST) {
7134 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7135 	}
7136 	if (rsm->r_flags & BBR_SACK_PASSED) {
7137 		BBR_STAT_INC(bbr_reorder_seen);
7138 		bbr->r_ctl.rc_reorder_ts = cts;
7139 		if (rsm->r_flags & BBR_MARKED_LOST) {
7140 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7141 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7142 				/* LT sampling also needs adjustment */
7143 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7144 		}
7145 	}
7146 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7147 	rsm->r_flags |= BBR_ACKED;
7148 	if (rsm->r_in_tmap) {
7149 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7150 		rsm->r_in_tmap = 0;
7151 	}
7152 out:
7153 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7154 		/*
7155 		 * Now can we merge this newly acked
7156 		 * block with either the previous or
7157 		 * next block?
7158 		 */
7159 		nrsm = TAILQ_NEXT(rsm, r_next);
7160 		if (nrsm &&
7161 		    (nrsm->r_flags & BBR_ACKED)) {
7162 			/* yep this and next can be merged */
7163 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7164 		}
7165 		/* Now what about the previous? */
7166 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7167 		if (nrsm &&
7168 		    (nrsm->r_flags & BBR_ACKED)) {
7169 			/* yep the previous and this can be merged */
7170 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7171 		}
7172 	}
7173 	if (used_ref == 0) {
7174 		BBR_STAT_INC(bbr_sack_proc_all);
7175 	} else {
7176 		BBR_STAT_INC(bbr_sack_proc_short);
7177 	}
7178 	if (went_fwd && went_back) {
7179 		BBR_STAT_INC(bbr_sack_search_both);
7180 	} else if (went_fwd) {
7181 		BBR_STAT_INC(bbr_sack_search_fwd);
7182 	} else if (went_back) {
7183 		BBR_STAT_INC(bbr_sack_search_back);
7184 	}
7185 	/* Save off where the next seq is */
7186 	if (rsm)
7187 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7188 	else
7189 		bbr->r_ctl.rc_sacklast = NULL;
7190 	*prsm = rsm;
7191 	return (changed);
7192 }
7193 
7194 static void inline
7195 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7196 {
7197 	struct bbr_sendmap *tmap;
7198 
7199 	BBR_STAT_INC(bbr_reneges_seen);
7200 	tmap = NULL;
7201 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7202 		/* Its no longer sacked, mark it so */
7203 		uint32_t oflags;
7204 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7205 #ifdef BBR_INVARIANTS
7206 		if (rsm->r_in_tmap) {
7207 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7208 			    bbr, rsm, rsm->r_flags);
7209 		}
7210 #endif
7211 		oflags = rsm->r_flags;
7212 		if (rsm->r_flags & BBR_MARKED_LOST) {
7213 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7214 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7215 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7216 				/* LT sampling also needs adjustment */
7217 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7218 		}
7219 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7220 		rsm->r_flags |= BBR_WAS_RENEGED;
7221 		rsm->r_flags |= BBR_RXT_CLEARED;
7222 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7223 		/* Rebuild it into our tmap */
7224 		if (tmap == NULL) {
7225 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7226 			tmap = rsm;
7227 		} else {
7228 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7229 			tmap = rsm;
7230 		}
7231 		tmap->r_in_tmap = 1;
7232 		/*
7233 		 * XXXrrs Delivered? Should we do anything here?
7234 		 *
7235 		 * Of course we don't on a rxt timeout so maybe its ok that
7236 		 * we don't?
7237 		 *
7238 		 * For now lets not.
7239 		 */
7240 		rsm = TAILQ_NEXT(rsm, r_next);
7241 	}
7242 	/*
7243 	 * Now lets possibly clear the sack filter so we start recognizing
7244 	 * sacks that cover this area.
7245 	 */
7246 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7247 }
7248 
7249 static void
7250 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7251 {
7252 	struct tcp_bbr *bbr;
7253 	struct bbr_sendmap *rsm;
7254 	uint32_t cts;
7255 
7256 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7257 	cts = bbr->r_ctl.rc_rcvtime;
7258 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7259 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7260 		if ((rsm->r_end - rsm->r_start) <= 1) {
7261 			/* Log out the SYN completely */
7262 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7263 			rsm->r_rtr_bytes = 0;
7264 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7265 			if (rsm->r_in_tmap) {
7266 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7267 				rsm->r_in_tmap = 0;
7268 			}
7269 			if (bbr->r_ctl.rc_next == rsm) {
7270 				/* scoot along the marker */
7271 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7272 			}
7273 			if (to != NULL)
7274 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7275 			bbr_free(bbr, rsm);
7276 		} else {
7277 			/* There is more (Fast open)? strip out SYN. */
7278 			rsm->r_flags &= ~BBR_HAS_SYN;
7279 			rsm->r_start++;
7280 		}
7281 	}
7282 }
7283 
7284 /*
7285  * Returns the number of bytes that were
7286  * acknowledged by SACK blocks.
7287  */
7288 
7289 static uint32_t
7290 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7291     uint32_t *prev_acked)
7292 {
7293 	uint32_t changed, last_seq, entered_recovery = 0;
7294 	struct tcp_bbr *bbr;
7295 	struct bbr_sendmap *rsm;
7296 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7297 	register uint32_t th_ack;
7298 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7299 	uint32_t cts, acked, ack_point, sack_changed = 0;
7300 	uint32_t p_maxseg, maxseg, p_acked = 0;
7301 
7302 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7303 	if (tcp_get_flags(th) & TH_RST) {
7304 		/* We don't log resets */
7305 		return (0);
7306 	}
7307 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7308 	cts = bbr->r_ctl.rc_rcvtime;
7309 
7310 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7311 	changed = 0;
7312 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7313 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7314 	th_ack = th->th_ack;
7315 	if (SEQ_GT(th_ack, tp->snd_una)) {
7316 		acked = th_ack - tp->snd_una;
7317 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7318 		bbr->rc_tp->t_acktime = ticks;
7319 	} else
7320 		acked = 0;
7321 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7322 		/* Only sent here for sack processing */
7323 		goto proc_sack;
7324 	}
7325 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7326 		changed = th_ack - rsm->r_start;
7327 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7328 		/*
7329 		 * For the SYN incoming case we will not have called
7330 		 * tcp_output for the sending of the SYN, so there will be
7331 		 * no map. All other cases should probably be a panic.
7332 		 */
7333 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7334 			/*
7335 			 * We have a timestamp that can be used to generate
7336 			 * an initial RTT.
7337 			 */
7338 			uint32_t ts, now, rtt;
7339 
7340 			ts = bbr_ts_convert(to->to_tsecr);
7341 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7342 			rtt = now - ts;
7343 			if (rtt < 1)
7344 				rtt = 1;
7345 			bbr_log_type_bbrrttprop(bbr, rtt,
7346 						tp->iss, 0, cts,
7347 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7348 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7349 			changed = 1;
7350 			bbr->r_wanted_output = 1;
7351 			goto out;
7352 		}
7353 		goto proc_sack;
7354 	} else if (rsm == NULL) {
7355 		goto out;
7356 	}
7357 	if (changed) {
7358 		/*
7359 		 * The ACK point is advancing to th_ack, we must drop off
7360 		 * the packets in the rack log and calculate any eligble
7361 		 * RTT's.
7362 		 */
7363 		bbr->r_wanted_output = 1;
7364 more:
7365 		if (rsm == NULL) {
7366 			if (tp->t_flags & TF_SENTFIN) {
7367 				/* if we send a FIN we will not hav a map */
7368 				goto proc_sack;
7369 			}
7370 #ifdef BBR_INVARIANTS
7371 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7372 			    tp,
7373 			    th, tp->t_state, bbr,
7374 			    tp->snd_una, tp->snd_max, changed);
7375 #endif
7376 			goto proc_sack;
7377 		}
7378 	}
7379 	if (SEQ_LT(th_ack, rsm->r_start)) {
7380 		/* Huh map is missing this */
7381 #ifdef BBR_INVARIANTS
7382 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7383 		    rsm->r_start,
7384 		    th_ack, tp->t_state,
7385 		    bbr->r_state, bbr);
7386 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7387 #endif
7388 		goto proc_sack;
7389 	} else if (th_ack == rsm->r_start) {
7390 		/* None here to ack */
7391 		goto proc_sack;
7392 	}
7393 	/*
7394 	 * Clear the dup ack counter, it will
7395 	 * either be freed or if there is some
7396 	 * remaining we need to start it at zero.
7397 	 */
7398 	rsm->r_dupack = 0;
7399 	/* Now do we consume the whole thing? */
7400 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7401 		/* Its all consumed. */
7402 		uint32_t left;
7403 
7404 		if (rsm->r_flags & BBR_ACKED) {
7405 			/*
7406 			 * It was acked on the scoreboard -- remove it from
7407 			 * total
7408 			 */
7409 			p_acked += (rsm->r_end - rsm->r_start);
7410 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7411 			if (bbr->r_ctl.rc_sacked == 0)
7412 				bbr->r_ctl.rc_sacklast = NULL;
7413 		} else {
7414 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7415 			if (rsm->r_flags & BBR_MARKED_LOST) {
7416 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7417 			}
7418 			if (rsm->r_flags & BBR_SACK_PASSED) {
7419 				/*
7420 				 * There are acked segments ACKED on the
7421 				 * scoreboard further up. We are seeing
7422 				 * reordering.
7423 				 */
7424 				BBR_STAT_INC(bbr_reorder_seen);
7425 				bbr->r_ctl.rc_reorder_ts = cts;
7426 				if (rsm->r_flags & BBR_MARKED_LOST) {
7427 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7428 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7429 						/* LT sampling also needs adjustment */
7430 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7431 				}
7432 			}
7433 			rsm->r_flags &= ~BBR_MARKED_LOST;
7434 		}
7435 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7436 		rsm->r_rtr_bytes = 0;
7437 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7438 		if (rsm->r_in_tmap) {
7439 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7440 			rsm->r_in_tmap = 0;
7441 		}
7442 		if (bbr->r_ctl.rc_next == rsm) {
7443 			/* scoot along the marker */
7444 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7445 		}
7446 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7447 		/* Adjust the packet counts */
7448 		left = th_ack - rsm->r_end;
7449 		/* Free back to zone */
7450 		bbr_free(bbr, rsm);
7451 		if (left) {
7452 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7453 			goto more;
7454 		}
7455 		goto proc_sack;
7456 	}
7457 	if (rsm->r_flags & BBR_ACKED) {
7458 		/*
7459 		 * It was acked on the scoreboard -- remove it from total
7460 		 * for the part being cum-acked.
7461 		 */
7462 		p_acked += (rsm->r_end - rsm->r_start);
7463 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7464 		if (bbr->r_ctl.rc_sacked == 0)
7465 			bbr->r_ctl.rc_sacklast = NULL;
7466 	} else {
7467 		/*
7468 		 * It was acked up to th_ack point for the first time
7469 		 */
7470 		struct bbr_sendmap lrsm;
7471 
7472 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7473 		lrsm.r_end = th_ack;
7474 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7475 	}
7476 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7477 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7478 		/*
7479 		 * It was marked lost and partly ack'd now
7480 		 * for the first time. We lower the rc_lost_bytes
7481 		 * and still leave it MARKED.
7482 		 */
7483 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7484 	}
7485 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7486 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7487 	rsm->r_rtr_bytes = 0;
7488 	/* adjust packet count */
7489 	rsm->r_start = th_ack;
7490 proc_sack:
7491 	/* Check for reneging */
7492 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7493 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7494 		/*
7495 		 * The peer has moved snd_una up to the edge of this send,
7496 		 * i.e. one that it had previously acked. The only way that
7497 		 * can be true if the peer threw away data (space issues)
7498 		 * that it had previously sacked (else it would have given
7499 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7500 		 * markings here.
7501 		 *
7502 		 * Note we have to look to make sure th_ack is our
7503 		 * rsm->r_start in case we get an old ack where th_ack is
7504 		 * behind snd_una.
7505 		 */
7506 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7507 	}
7508 	if ((to->to_flags & TOF_SACK) == 0) {
7509 		/* We are done nothing left to log */
7510 		goto out;
7511 	}
7512 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7513 	if (rsm) {
7514 		last_seq = rsm->r_end;
7515 	} else {
7516 		last_seq = tp->snd_max;
7517 	}
7518 	/* Sack block processing */
7519 	if (SEQ_GT(th_ack, tp->snd_una))
7520 		ack_point = th_ack;
7521 	else
7522 		ack_point = tp->snd_una;
7523 	for (i = 0; i < to->to_nsacks; i++) {
7524 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7525 		    &sack, sizeof(sack));
7526 		sack.start = ntohl(sack.start);
7527 		sack.end = ntohl(sack.end);
7528 		if (SEQ_GT(sack.end, sack.start) &&
7529 		    SEQ_GT(sack.start, ack_point) &&
7530 		    SEQ_LT(sack.start, tp->snd_max) &&
7531 		    SEQ_GT(sack.end, ack_point) &&
7532 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7533 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7534 			    (SEQ_LT(sack.end, last_seq)) &&
7535 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7536 				/*
7537 				 * Not the last piece and its smaller than
7538 				 * 1/8th of a p_maxseg. We ignore this.
7539 				 */
7540 				BBR_STAT_INC(bbr_runt_sacks);
7541 				continue;
7542 			}
7543 			sack_blocks[num_sack_blks] = sack;
7544 			num_sack_blks++;
7545 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7546 		    SEQ_LEQ(sack.end, th_ack)) {
7547 			/*
7548 			 * Its a D-SACK block.
7549 			 */
7550 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7551 		}
7552 	}
7553 	if (num_sack_blks == 0)
7554 		goto out;
7555 	/*
7556 	 * Sort the SACK blocks so we can update the rack scoreboard with
7557 	 * just one pass.
7558 	 */
7559 	new_sb = sack_filter_blks(&bbr->r_ctl.bbr_sf, sack_blocks,
7560 				  num_sack_blks, th->th_ack);
7561 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7562 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7563 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7564 	num_sack_blks = new_sb;
7565 	if (num_sack_blks < 2) {
7566 		goto do_sack_work;
7567 	}
7568 	/* Sort the sacks */
7569 	for (i = 0; i < num_sack_blks; i++) {
7570 		for (j = i + 1; j < num_sack_blks; j++) {
7571 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7572 				sack = sack_blocks[i];
7573 				sack_blocks[i] = sack_blocks[j];
7574 				sack_blocks[j] = sack;
7575 			}
7576 		}
7577 	}
7578 	/*
7579 	 * Now are any of the sack block ends the same (yes some
7580 	 * implememtations send these)?
7581 	 */
7582 again:
7583 	if (num_sack_blks > 1) {
7584 		for (i = 0; i < num_sack_blks; i++) {
7585 			for (j = i + 1; j < num_sack_blks; j++) {
7586 				if (sack_blocks[i].end == sack_blocks[j].end) {
7587 					/*
7588 					 * Ok these two have the same end we
7589 					 * want the smallest end and then
7590 					 * throw away the larger and start
7591 					 * again.
7592 					 */
7593 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7594 						/*
7595 						 * The second block covers
7596 						 * more area use that
7597 						 */
7598 						sack_blocks[i].start = sack_blocks[j].start;
7599 					}
7600 					/*
7601 					 * Now collapse out the dup-sack and
7602 					 * lower the count
7603 					 */
7604 					for (k = (j + 1); k < num_sack_blks; k++) {
7605 						sack_blocks[j].start = sack_blocks[k].start;
7606 						sack_blocks[j].end = sack_blocks[k].end;
7607 						j++;
7608 					}
7609 					num_sack_blks--;
7610 					goto again;
7611 				}
7612 			}
7613 		}
7614 	}
7615 do_sack_work:
7616 	rsm = bbr->r_ctl.rc_sacklast;
7617 	for (i = 0; i < num_sack_blks; i++) {
7618 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7619 		if (acked) {
7620 			bbr->r_wanted_output = 1;
7621 			changed += acked;
7622 			sack_changed += acked;
7623 		}
7624 	}
7625 out:
7626 	*prev_acked = p_acked;
7627 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7628 		/*
7629 		 * Ok we have a high probability that we need to go in to
7630 		 * recovery since we have data sack'd
7631 		 */
7632 		struct bbr_sendmap *rsm;
7633 
7634 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7635 		if (rsm) {
7636 			/* Enter recovery */
7637 			entered_recovery = 1;
7638 			bbr->r_wanted_output = 1;
7639 			/*
7640 			 * When we enter recovery we need to assure we send
7641 			 * one packet.
7642 			 */
7643 			if (bbr->r_ctl.rc_resend == NULL) {
7644 				bbr->r_ctl.rc_resend = rsm;
7645 			}
7646 		}
7647 	}
7648 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7649 		/*
7650 		 * See if we need to rack-retransmit anything if so set it
7651 		 * up as the thing to resend assuming something else is not
7652 		 * already in that position.
7653 		 */
7654 		if (bbr->r_ctl.rc_resend == NULL) {
7655 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7656 		}
7657 	}
7658 	/*
7659 	 * We return the amount that changed via sack, this is used by the
7660 	 * ack-received code to augment what was changed between th_ack <->
7661 	 * snd_una.
7662 	 */
7663 	return (sack_changed);
7664 }
7665 
7666 static void
7667 bbr_strike_dupack(struct tcp_bbr *bbr)
7668 {
7669 	struct bbr_sendmap *rsm;
7670 
7671 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7672 	if (rsm && (rsm->r_dupack < 0xff)) {
7673 		rsm->r_dupack++;
7674 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7675 			bbr->r_wanted_output = 1;
7676 	}
7677 }
7678 
7679 /*
7680  * Return value of 1, we do not need to call bbr_process_data().
7681  * return value of 0, bbr_process_data can be called.
7682  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7683  * its unlocked and probably unsafe to touch the TCB.
7684  */
7685 static int
7686 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7687     struct tcpcb *tp, struct tcpopt *to,
7688     uint32_t tiwin, int32_t tlen,
7689     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7690 {
7691 	int32_t ourfinisacked = 0;
7692 	int32_t acked_amount;
7693 	uint16_t nsegs;
7694 	int32_t acked;
7695 	uint32_t lost, sack_changed = 0;
7696 	struct mbuf *mfree;
7697 	struct tcp_bbr *bbr;
7698 	uint32_t prev_acked = 0;
7699 
7700 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7701 	lost = bbr->r_ctl.rc_lost;
7702 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7703 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7704 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7705 		bbr->r_wanted_output = 1;
7706 		return (1);
7707 	}
7708 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7709 		/* Process the ack */
7710 		if (bbr->rc_in_persist)
7711 			tp->t_rxtshift = 0;
7712 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7713 			bbr_strike_dupack(bbr);
7714 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7715 	}
7716 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7717 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7718 		/*
7719 		 * Old ack, behind the last one rcv'd or a duplicate ack
7720 		 * with SACK info.
7721 		 */
7722 		if (th->th_ack == tp->snd_una) {
7723 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7724 			if (bbr->r_state == TCPS_SYN_SENT) {
7725 				/*
7726 				 * Special case on where we sent SYN. When
7727 				 * the SYN-ACK is processed in syn_sent
7728 				 * state it bumps the snd_una. This causes
7729 				 * us to hit here even though we did ack 1
7730 				 * byte.
7731 				 *
7732 				 * Go through the nothing left case so we
7733 				 * send data.
7734 				 */
7735 				goto nothing_left;
7736 			}
7737 		}
7738 		return (0);
7739 	}
7740 	/*
7741 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7742 	 * something we sent.
7743 	 */
7744 	if (tp->t_flags & TF_NEEDSYN) {
7745 		/*
7746 		 * T/TCP: Connection was half-synchronized, and our SYN has
7747 		 * been ACK'd (so connection is now fully synchronized).  Go
7748 		 * to non-starred state, increment snd_una for ACK of SYN,
7749 		 * and check if we can do window scaling.
7750 		 */
7751 		tp->t_flags &= ~TF_NEEDSYN;
7752 		tp->snd_una++;
7753 		/* Do window scaling? */
7754 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7755 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7756 			tp->rcv_scale = tp->request_r_scale;
7757 			/* Send window already scaled. */
7758 		}
7759 	}
7760 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7761 
7762 	acked = BYTES_THIS_ACK(tp, th);
7763 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7764 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7765 
7766 	/*
7767 	 * If we just performed our first retransmit, and the ACK arrives
7768 	 * within our recovery window, then it was a mistake to do the
7769 	 * retransmit in the first place.  Recover our original cwnd and
7770 	 * ssthresh, and proceed to transmit where we left off.
7771 	 */
7772 	if (tp->t_flags & TF_PREVVALID) {
7773 		tp->t_flags &= ~TF_PREVVALID;
7774 		if (tp->t_rxtshift == 1 &&
7775 		    (int)(ticks - tp->t_badrxtwin) < 0)
7776 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7777 	}
7778 	SOCKBUF_LOCK(&so->so_snd);
7779 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7780 	tp->snd_wnd -= acked_amount;
7781 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7782 	/* NB: sowwakeup_locked() does an implicit unlock. */
7783 	sowwakeup_locked(so);
7784 	m_freem(mfree);
7785 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7786 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7787 	}
7788 	tp->snd_una = th->th_ack;
7789 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7790 	if (IN_RECOVERY(tp->t_flags)) {
7791 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7792 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7793 			tcp_bbr_partialack(tp);
7794 		} else {
7795 			bbr_post_recovery(tp);
7796 		}
7797 	}
7798 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7799 		tp->snd_recover = tp->snd_una;
7800 	}
7801 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7802 		tp->snd_nxt = tp->snd_max;
7803 	}
7804 	if (tp->snd_una == tp->snd_max) {
7805 		/* Nothing left outstanding */
7806 nothing_left:
7807 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7808 		if (sbavail(&so->so_snd) == 0)
7809 			bbr->rc_tp->t_acktime = 0;
7810 		if ((sbused(&so->so_snd) == 0) &&
7811 		    (tp->t_flags & TF_SENTFIN)) {
7812 			ourfinisacked = 1;
7813 		}
7814 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7815 		if (bbr->rc_in_persist == 0) {
7816 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7817 		}
7818 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7819 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7820 		/*
7821 		 * We invalidate the last ack here since we
7822 		 * don't want to transfer forward the time
7823 		 * for our sum's calculations.
7824 		 */
7825 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7826 		    (sbavail(&so->so_snd) == 0) &&
7827 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7828 			/*
7829 			 * The socket was gone and the peer sent data, time
7830 			 * to reset him.
7831 			 */
7832 			*ret_val = 1;
7833 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7834 			/* tcp_close will kill the inp pre-log the Reset */
7835 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7836 			tp = tcp_close(tp);
7837 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7838 			BBR_STAT_INC(bbr_dropped_af_data);
7839 			return (1);
7840 		}
7841 		/* Set need output so persist might get set */
7842 		bbr->r_wanted_output = 1;
7843 	}
7844 	if (ofia)
7845 		*ofia = ourfinisacked;
7846 	return (0);
7847 }
7848 
7849 static void
7850 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7851 {
7852 	if (bbr->rc_in_persist == 0) {
7853 		bbr_timer_cancel(bbr, __LINE__, cts);
7854 		bbr->r_ctl.rc_last_delay_val = 0;
7855 		tp->t_rxtshift = 0;
7856 		bbr->rc_in_persist = 1;
7857 		bbr->r_ctl.rc_went_idle_time = cts;
7858 		/* We should be capped when rw went to 0 but just in case */
7859 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7860 		/* Time freezes for the state, so do the accounting now */
7861 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7862 			uint32_t time_in;
7863 
7864 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7865 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7866 				int32_t idx;
7867 
7868 				idx = bbr_state_val(bbr);
7869 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7870 			} else {
7871 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7872 			}
7873 		}
7874 		bbr->r_ctl.rc_bbr_state_time = cts;
7875 	}
7876 }
7877 
7878 static void
7879 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7880 {
7881 	/*
7882 	 * Note that if idle time does not exceed our
7883 	 * threshold, we do nothing continuing the state
7884 	 * transitions we were last walking through.
7885 	 */
7886 	if (idle_time >= bbr_idle_restart_threshold) {
7887 		if (bbr->rc_use_idle_restart) {
7888 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7889 			/*
7890 			 * Set our target using BBR_UNIT, so
7891 			 * we increase at a dramatic rate but
7892 			 * we stop when we get the pipe
7893 			 * full again for our current b/w estimate.
7894 			 */
7895 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7896 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7897 			bbr_set_state_target(bbr, __LINE__);
7898 			/* Now setup our gains to ramp up */
7899 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7900 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7901 			bbr_log_type_statechange(bbr, cts, __LINE__);
7902 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7903 			bbr_substate_change(bbr, cts, __LINE__, 1);
7904 		}
7905 	}
7906 }
7907 
7908 static void
7909 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7910 {
7911 	uint32_t idle_time;
7912 
7913 	if (bbr->rc_in_persist == 0)
7914 		return;
7915 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7916 	bbr->rc_in_persist = 0;
7917 	bbr->rc_hit_state_1 = 0;
7918 	bbr->r_ctl.rc_del_time = cts;
7919 	/*
7920 	 * We invalidate the last ack here since we
7921 	 * don't want to transfer forward the time
7922 	 * for our sum's calculations.
7923 	 */
7924 	if (tcp_in_hpts(bbr->rc_tp)) {
7925 		tcp_hpts_remove(bbr->rc_tp);
7926 		bbr->rc_timer_first = 0;
7927 		bbr->r_ctl.rc_hpts_flags = 0;
7928 		bbr->r_ctl.rc_last_delay_val = 0;
7929 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7930 		bbr->r_agg_early_set = 0;
7931 		bbr->r_ctl.rc_agg_early = 0;
7932 	}
7933 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7934 	if (idle_time >= bbr_rtt_probe_time) {
7935 		/*
7936 		 * This qualifies as a RTT_PROBE session since we drop the
7937 		 * data outstanding to nothing and waited more than
7938 		 * bbr_rtt_probe_time.
7939 		 */
7940 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7941 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7942 	}
7943 	tp->t_rxtshift = 0;
7944 	/*
7945 	 * If in probeBW and we have persisted more than an RTT lets do
7946 	 * special handling.
7947 	 */
7948 	/* Force a time based epoch */
7949 	bbr_set_epoch(bbr, cts, __LINE__);
7950 	/*
7951 	 * Setup the lost so we don't count anything against the guy
7952 	 * we have been stuck with during persists.
7953 	 */
7954 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7955 	/* Time un-freezes for the state */
7956 	bbr->r_ctl.rc_bbr_state_time = cts;
7957 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7958 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7959 		/*
7960 		 * If we are going back to probe-bw
7961 		 * or probe_rtt, we may need to possibly
7962 		 * do a fast restart.
7963 		 */
7964 		bbr_restart_after_idle(bbr, cts, idle_time);
7965 	}
7966 }
7967 
7968 static void
7969 bbr_collapsed_window(struct tcp_bbr *bbr)
7970 {
7971 	/*
7972 	 * Now we must walk the
7973 	 * send map and divide the
7974 	 * ones left stranded. These
7975 	 * guys can't cause us to abort
7976 	 * the connection and are really
7977 	 * "unsent". However if a buggy
7978 	 * client actually did keep some
7979 	 * of the data i.e. collapsed the win
7980 	 * and refused to ack and then opened
7981 	 * the win and acked that data. We would
7982 	 * get into an ack war, the simplier
7983 	 * method then of just pretending we
7984 	 * did not send those segments something
7985 	 * won't work.
7986 	 */
7987 	struct bbr_sendmap *rsm, *nrsm;
7988 	tcp_seq max_seq;
7989 	uint32_t maxseg;
7990 	int can_split = 0;
7991 	int fnd = 0;
7992 
7993 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
7994 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
7995 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
7996 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
7997 		/* Find the first seq past or at maxseq */
7998 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
7999 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8000 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8001 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8002 			fnd = 1;
8003 			break;
8004 		}
8005 	}
8006 	bbr->rc_has_collapsed = 0;
8007 	if (!fnd) {
8008 		/* Nothing to do strange */
8009 		return;
8010 	}
8011 	/*
8012 	 * Now can we split?
8013 	 *
8014 	 * We don't want to split if splitting
8015 	 * would generate too many small segments
8016 	 * less we let an attacker fragment our
8017 	 * send_map and leave us out of memory.
8018 	 */
8019 	if ((max_seq != rsm->r_start) &&
8020 	    (max_seq != rsm->r_end)){
8021 		/* can we split? */
8022 		int res1, res2;
8023 
8024 		res1 = max_seq - rsm->r_start;
8025 		res2 = rsm->r_end - max_seq;
8026 		if ((res1 >= (maxseg/8)) &&
8027 		    (res2 >= (maxseg/8))) {
8028 			/* No small pieces here */
8029 			can_split = 1;
8030 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8031 			/* We are under the limit */
8032 			can_split = 1;
8033 		}
8034 	}
8035 	/* Ok do we need to split this rsm? */
8036 	if (max_seq == rsm->r_start) {
8037 		/* It's this guy no split required */
8038 		nrsm = rsm;
8039 	} else if (max_seq == rsm->r_end) {
8040 		/* It's the next one no split required. */
8041 		nrsm = TAILQ_NEXT(rsm, r_next);
8042 		if (nrsm == NULL) {
8043 			/* Huh? */
8044 			return;
8045 		}
8046 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8047 		/* yep we need to split it */
8048 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8049 		if (nrsm == NULL) {
8050 			/* failed XXXrrs what can we do mark the whole? */
8051 			nrsm = rsm;
8052 			goto no_split;
8053 		}
8054 		/* Clone it */
8055 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8056 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8057 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8058 		if (rsm->r_in_tmap) {
8059 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8060 			nrsm->r_in_tmap = 1;
8061 		}
8062 	} else {
8063 		/*
8064 		 * Split not allowed just start here just
8065 		 * use this guy.
8066 		 */
8067 		nrsm = rsm;
8068 	}
8069 no_split:
8070 	BBR_STAT_INC(bbr_collapsed_win);
8071 	/* reuse fnd as a count */
8072 	fnd = 0;
8073 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8074 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8075 		fnd++;
8076 		bbr->rc_has_collapsed = 1;
8077 	}
8078 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8079 }
8080 
8081 static void
8082 bbr_un_collapse_window(struct tcp_bbr *bbr)
8083 {
8084 	struct bbr_sendmap *rsm;
8085 	int cleared = 0;
8086 
8087 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8088 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8089 			/* Clear the flag */
8090 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8091 			cleared++;
8092 		} else
8093 			break;
8094 	}
8095 	bbr_log_type_rwnd_collapse(bbr,
8096 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8097 	bbr->rc_has_collapsed = 0;
8098 }
8099 
8100 /*
8101  * Return value of 1, the TCB is unlocked and most
8102  * likely gone, return value of 0, the TCB is still
8103  * locked.
8104  */
8105 static int
8106 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8107     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8108     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8109 {
8110 	/*
8111 	 * Update window information. Don't look at window if no ACK: TAC's
8112 	 * send garbage on first SYN.
8113 	 */
8114 	uint16_t nsegs;
8115 	int32_t tfo_syn;
8116 	struct tcp_bbr *bbr;
8117 
8118 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8119 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8120 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8121 	if ((thflags & TH_ACK) &&
8122 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8123 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8124 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8125 		/* keep track of pure window updates */
8126 		if (tlen == 0 &&
8127 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8128 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8129 		tp->snd_wnd = tiwin;
8130 		tp->snd_wl1 = th->th_seq;
8131 		tp->snd_wl2 = th->th_ack;
8132 		if (tp->snd_wnd > tp->max_sndwnd)
8133 			tp->max_sndwnd = tp->snd_wnd;
8134 		bbr->r_wanted_output = 1;
8135 	} else if (thflags & TH_ACK) {
8136 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8137 			tp->snd_wnd = tiwin;
8138 			tp->snd_wl1 = th->th_seq;
8139 			tp->snd_wl2 = th->th_ack;
8140 		}
8141 	}
8142 	if (tp->snd_wnd < ctf_outstanding(tp))
8143 		/* The peer collapsed its window on us */
8144 		bbr_collapsed_window(bbr);
8145  	else if (bbr->rc_has_collapsed)
8146 		bbr_un_collapse_window(bbr);
8147 	/* Was persist timer active and now we have window space? */
8148 	if ((bbr->rc_in_persist != 0) &&
8149 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8150 				bbr_minseg(bbr)))) {
8151 		/*
8152 		 * Make the rate persist at end of persist mode if idle long
8153 		 * enough
8154 		 */
8155 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8156 
8157 		/* Make sure we output to start the timer */
8158 		bbr->r_wanted_output = 1;
8159 	}
8160 	/* Do we need to enter persist? */
8161 	if ((bbr->rc_in_persist == 0) &&
8162 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8163 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8164 	    (tp->snd_max == tp->snd_una) &&
8165 	    sbavail(&so->so_snd) &&
8166 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8167 		/* No send window.. we must enter persist */
8168 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8169 	}
8170 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8171 		m_freem(m);
8172 		return (0);
8173 	}
8174 	/*
8175 	 * We don't support urgent data but
8176 	 * drag along the up just to make sure
8177 	 * if there is a stack switch no one
8178 	 * is surprised.
8179 	 */
8180 	tp->rcv_up = tp->rcv_nxt;
8181 
8182 	/*
8183 	 * Process the segment text, merging it into the TCP sequencing
8184 	 * queue, and arranging for acknowledgment of receipt if necessary.
8185 	 * This process logically involves adjusting tp->rcv_wnd as data is
8186 	 * presented to the user (this happens in tcp_usrreq.c, case
8187 	 * PRU_RCVD).  If a FIN has already been received on this connection
8188 	 * then we just ignore the text.
8189 	 */
8190 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8191 		   IS_FASTOPEN(tp->t_flags));
8192 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8193 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8194 		tcp_seq save_start = th->th_seq;
8195 		tcp_seq save_rnxt  = tp->rcv_nxt;
8196 		int     save_tlen  = tlen;
8197 
8198 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8199 		/*
8200 		 * Insert segment which includes th into TCP reassembly
8201 		 * queue with control block tp.  Set thflags to whether
8202 		 * reassembly now includes a segment with FIN.  This handles
8203 		 * the common case inline (segment is the next to be
8204 		 * received on an established connection, and the queue is
8205 		 * empty), avoiding linkage into and removal from the queue
8206 		 * and repetition of various conversions. Set DELACK for
8207 		 * segments received in order, but ack immediately when
8208 		 * segments are out of order (so fast retransmit can work).
8209 		 */
8210 		if (th->th_seq == tp->rcv_nxt &&
8211 		    SEGQ_EMPTY(tp) &&
8212 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8213 		    tfo_syn)) {
8214 #ifdef NETFLIX_SB_LIMITS
8215 			u_int mcnt, appended;
8216 
8217 			if (so->so_rcv.sb_shlim) {
8218 				mcnt = m_memcnt(m);
8219 				appended = 0;
8220 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8221 				    CFO_NOSLEEP, NULL) == false) {
8222 					counter_u64_add(tcp_sb_shlim_fails, 1);
8223 					m_freem(m);
8224 					return (0);
8225 				}
8226 			}
8227 
8228 #endif
8229 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8230 				bbr->bbr_segs_rcvd += max(1, nsegs);
8231 				tp->t_flags |= TF_DELACK;
8232 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8233 			} else {
8234 				bbr->r_wanted_output = 1;
8235 				tp->t_flags |= TF_ACKNOW;
8236 			}
8237 			tp->rcv_nxt += tlen;
8238 			if (tlen &&
8239 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8240 			    (tp->t_fbyte_in == 0)) {
8241 				tp->t_fbyte_in = ticks;
8242 				if (tp->t_fbyte_in == 0)
8243 					tp->t_fbyte_in = 1;
8244 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8245 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8246 			}
8247 			thflags = tcp_get_flags(th) & TH_FIN;
8248 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8249 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8250 			SOCKBUF_LOCK(&so->so_rcv);
8251 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8252 				m_freem(m);
8253 			else
8254 #ifdef NETFLIX_SB_LIMITS
8255 				appended =
8256 #endif
8257 					sbappendstream_locked(&so->so_rcv, m, 0);
8258 			/* NB: sorwakeup_locked() does an implicit unlock. */
8259 			sorwakeup_locked(so);
8260 #ifdef NETFLIX_SB_LIMITS
8261 			if (so->so_rcv.sb_shlim && appended != mcnt)
8262 				counter_fo_release(so->so_rcv.sb_shlim,
8263 				    mcnt - appended);
8264 #endif
8265 
8266 		} else {
8267 			/*
8268 			 * XXX: Due to the header drop above "th" is
8269 			 * theoretically invalid by now.  Fortunately
8270 			 * m_adj() doesn't actually frees any mbufs when
8271 			 * trimming from the head.
8272 			 */
8273 			tcp_seq temp = save_start;
8274 
8275 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8276 			tp->t_flags |= TF_ACKNOW;
8277 			if (tp->t_flags & TF_WAKESOR) {
8278 				tp->t_flags &= ~TF_WAKESOR;
8279 				/* NB: sorwakeup_locked() does an implicit unlock. */
8280 				sorwakeup_locked(so);
8281 			}
8282 		}
8283 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8284 		    (save_tlen > 0) &&
8285 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8286 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8287 				/*
8288 				 * DSACK actually handled in the fastpath
8289 				 * above.
8290 				 */
8291 				tcp_update_sack_list(tp, save_start,
8292 				    save_start + save_tlen);
8293 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8294 				if ((tp->rcv_numsacks >= 1) &&
8295 				    (tp->sackblks[0].end == save_start)) {
8296 					/*
8297 					 * Partial overlap, recorded at todrop
8298 					 * above.
8299 					 */
8300 					tcp_update_sack_list(tp,
8301 					    tp->sackblks[0].start,
8302 					    tp->sackblks[0].end);
8303 				} else {
8304 					tcp_update_dsack_list(tp, save_start,
8305 					    save_start + save_tlen);
8306 				}
8307 			} else if (tlen >= save_tlen) {
8308 				/* Update of sackblks. */
8309 				tcp_update_dsack_list(tp, save_start,
8310 				    save_start + save_tlen);
8311 			} else if (tlen > 0) {
8312 				tcp_update_dsack_list(tp, save_start,
8313 				    save_start + tlen);
8314 			}
8315 		}
8316 	} else {
8317 		m_freem(m);
8318 		thflags &= ~TH_FIN;
8319 	}
8320 
8321 	/*
8322 	 * If FIN is received ACK the FIN and let the user know that the
8323 	 * connection is closing.
8324 	 */
8325 	if (thflags & TH_FIN) {
8326 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8327 			/* The socket upcall is handled by socantrcvmore. */
8328 			socantrcvmore(so);
8329 			/*
8330 			 * If connection is half-synchronized (ie NEEDSYN
8331 			 * flag on) then delay ACK, so it may be piggybacked
8332 			 * when SYN is sent. Otherwise, since we received a
8333 			 * FIN then no more input can be expected, send ACK
8334 			 * now.
8335 			 */
8336 			if (tp->t_flags & TF_NEEDSYN) {
8337 				tp->t_flags |= TF_DELACK;
8338 				bbr_timer_cancel(bbr,
8339 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8340 			} else {
8341 				tp->t_flags |= TF_ACKNOW;
8342 			}
8343 			tp->rcv_nxt++;
8344 		}
8345 		switch (tp->t_state) {
8346 			/*
8347 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8348 			 * CLOSE_WAIT state.
8349 			 */
8350 		case TCPS_SYN_RECEIVED:
8351 			tp->t_starttime = ticks;
8352 			/* FALLTHROUGH */
8353 		case TCPS_ESTABLISHED:
8354 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8355 			break;
8356 
8357 			/*
8358 			 * If still in FIN_WAIT_1 STATE FIN has not been
8359 			 * acked so enter the CLOSING state.
8360 			 */
8361 		case TCPS_FIN_WAIT_1:
8362 			tcp_state_change(tp, TCPS_CLOSING);
8363 			break;
8364 
8365 			/*
8366 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8367 			 * starting the time-wait timer, turning off the
8368 			 * other standard timers.
8369 			 */
8370 		case TCPS_FIN_WAIT_2:
8371 			bbr->rc_timer_first = 1;
8372 			bbr_timer_cancel(bbr,
8373 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8374 			tcp_twstart(tp);
8375 			return (1);
8376 		}
8377 	}
8378 	/*
8379 	 * Return any desired output.
8380 	 */
8381 	if ((tp->t_flags & TF_ACKNOW) ||
8382 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8383 		bbr->r_wanted_output = 1;
8384 	}
8385 	return (0);
8386 }
8387 
8388 /*
8389  * Here nothing is really faster, its just that we
8390  * have broken out the fast-data path also just like
8391  * the fast-ack. Return 1 if we processed the packet
8392  * return 0 if you need to take the "slow-path".
8393  */
8394 static int
8395 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8396     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8397     uint32_t tiwin, int32_t nxt_pkt)
8398 {
8399 	uint16_t nsegs;
8400 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8401 	struct tcp_bbr *bbr;
8402 #ifdef NETFLIX_SB_LIMITS
8403 	u_int mcnt, appended;
8404 #endif
8405 
8406 	/* On the hpts and we would have called output */
8407 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8408 
8409 	/*
8410 	 * If last ACK falls within this segment's sequence numbers, record
8411 	 * the timestamp. NOTE that the test is modified according to the
8412 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8413 	 */
8414 	if (bbr->r_ctl.rc_resend != NULL) {
8415 		return (0);
8416 	}
8417 	if (tiwin && tiwin != tp->snd_wnd) {
8418 		return (0);
8419 	}
8420 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8421 		return (0);
8422 	}
8423 	if (__predict_false((to->to_flags & TOF_TS) &&
8424 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8425 		return (0);
8426 	}
8427 	if (__predict_false((th->th_ack != tp->snd_una))) {
8428 		return (0);
8429 	}
8430 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8431 		return (0);
8432 	}
8433 	if ((to->to_flags & TOF_TS) != 0 &&
8434 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8435 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8436 		tp->ts_recent = to->to_tsval;
8437 	}
8438 	/*
8439 	 * This is a pure, in-sequence data packet with nothing on the
8440 	 * reassembly queue and we have enough buffer space to take it.
8441 	 */
8442 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8443 
8444 #ifdef NETFLIX_SB_LIMITS
8445 	if (so->so_rcv.sb_shlim) {
8446 		mcnt = m_memcnt(m);
8447 		appended = 0;
8448 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8449 		    CFO_NOSLEEP, NULL) == false) {
8450 			counter_u64_add(tcp_sb_shlim_fails, 1);
8451 			m_freem(m);
8452 			return (1);
8453 		}
8454 	}
8455 #endif
8456 	/* Clean receiver SACK report if present */
8457 	if (tp->rcv_numsacks)
8458 		tcp_clean_sackreport(tp);
8459 	KMOD_TCPSTAT_INC(tcps_preddat);
8460 	tp->rcv_nxt += tlen;
8461 	if (tlen &&
8462 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8463 	    (tp->t_fbyte_in == 0)) {
8464 		tp->t_fbyte_in = ticks;
8465 		if (tp->t_fbyte_in == 0)
8466 			tp->t_fbyte_in = 1;
8467 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8468 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8469 	}
8470 	/*
8471 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8472 	 */
8473 	tp->snd_wl1 = th->th_seq;
8474 	/*
8475 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8476 	 */
8477 	tp->rcv_up = tp->rcv_nxt;
8478 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8479 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8480 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8481 
8482 	/* Add data to socket buffer. */
8483 	SOCKBUF_LOCK(&so->so_rcv);
8484 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8485 		m_freem(m);
8486 	} else {
8487 		/*
8488 		 * Set new socket buffer size. Give up when limit is
8489 		 * reached.
8490 		 */
8491 		if (newsize)
8492 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8493 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8494 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8495 
8496 #ifdef NETFLIX_SB_LIMITS
8497 		appended =
8498 #endif
8499 			sbappendstream_locked(&so->so_rcv, m, 0);
8500 		ctf_calc_rwin(so, tp);
8501 	}
8502 	/* NB: sorwakeup_locked() does an implicit unlock. */
8503 	sorwakeup_locked(so);
8504 #ifdef NETFLIX_SB_LIMITS
8505 	if (so->so_rcv.sb_shlim && mcnt != appended)
8506 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8507 #endif
8508 	if (DELAY_ACK(tp, bbr, nsegs)) {
8509 		bbr->bbr_segs_rcvd += max(1, nsegs);
8510 		tp->t_flags |= TF_DELACK;
8511 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8512 	} else {
8513 		bbr->r_wanted_output = 1;
8514 		tp->t_flags |= TF_ACKNOW;
8515 	}
8516 	return (1);
8517 }
8518 
8519 /*
8520  * This subfunction is used to try to highly optimize the
8521  * fast path. We again allow window updates that are
8522  * in sequence to remain in the fast-path. We also add
8523  * in the __predict's to attempt to help the compiler.
8524  * Note that if we return a 0, then we can *not* process
8525  * it and the caller should push the packet into the
8526  * slow-path. If we return 1, then all is well and
8527  * the packet is fully processed.
8528  */
8529 static int
8530 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8531     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8532     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8533 {
8534 	int32_t acked;
8535 	uint16_t nsegs;
8536 	uint32_t sack_changed;
8537 	uint32_t prev_acked = 0;
8538 	struct tcp_bbr *bbr;
8539 
8540 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8541 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8542 		return (0);
8543 	}
8544 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8545 		/* Above what we have sent? */
8546 		return (0);
8547 	}
8548 	if (__predict_false(tiwin == 0)) {
8549 		/* zero window */
8550 		return (0);
8551 	}
8552 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8553 		/* We need a SYN or a FIN, unlikely.. */
8554 		return (0);
8555 	}
8556 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8557 		/* Timestamp is behind .. old ack with seq wrap? */
8558 		return (0);
8559 	}
8560 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8561 		/* Still recovering */
8562 		return (0);
8563 	}
8564 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8565 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8566 		/* We are retransmitting */
8567 		return (0);
8568 	}
8569 	if (__predict_false(bbr->rc_in_persist != 0)) {
8570 		/* In persist mode */
8571 		return (0);
8572 	}
8573 	if (bbr->r_ctl.rc_sacked) {
8574 		/* We have sack holes on our scoreboard */
8575 		return (0);
8576 	}
8577 	/* Ok if we reach here, we can process a fast-ack */
8578 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8579 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8580 	/*
8581 	 * We never detect loss in fast ack [we can't
8582 	 * have a sack and can't be in recovery so
8583 	 * we always pass 0 (nothing detected)].
8584 	 */
8585 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8586 	/* Did the window get updated? */
8587 	if (tiwin != tp->snd_wnd) {
8588 		tp->snd_wnd = tiwin;
8589 		tp->snd_wl1 = th->th_seq;
8590 		if (tp->snd_wnd > tp->max_sndwnd)
8591 			tp->max_sndwnd = tp->snd_wnd;
8592 	}
8593 	/* Do we need to exit persists? */
8594 	if ((bbr->rc_in_persist != 0) &&
8595 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8596 			       bbr_minseg(bbr)))) {
8597 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8598 		bbr->r_wanted_output = 1;
8599 	}
8600 	/* Do we need to enter persists? */
8601 	if ((bbr->rc_in_persist == 0) &&
8602 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8603 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8604 	    (tp->snd_max == tp->snd_una) &&
8605 	    sbavail(&so->so_snd) &&
8606 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8607 		/* No send window.. we must enter persist */
8608 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8609 	}
8610 	/*
8611 	 * If last ACK falls within this segment's sequence numbers, record
8612 	 * the timestamp. NOTE that the test is modified according to the
8613 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8614 	 */
8615 	if ((to->to_flags & TOF_TS) != 0 &&
8616 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8617 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8618 		tp->ts_recent = to->to_tsval;
8619 	}
8620 	/*
8621 	 * This is a pure ack for outstanding data.
8622 	 */
8623 	KMOD_TCPSTAT_INC(tcps_predack);
8624 
8625 	/*
8626 	 * "bad retransmit" recovery.
8627 	 */
8628 	if (tp->t_flags & TF_PREVVALID) {
8629 		tp->t_flags &= ~TF_PREVVALID;
8630 		if (tp->t_rxtshift == 1 &&
8631 		    (int)(ticks - tp->t_badrxtwin) < 0)
8632 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8633 	}
8634 	/*
8635 	 * Recalculate the transmit timer / rtt.
8636 	 *
8637 	 * Some boxes send broken timestamp replies during the SYN+ACK
8638 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8639 	 * and blow up the retransmit timer.
8640 	 */
8641 	acked = BYTES_THIS_ACK(tp, th);
8642 
8643 #ifdef TCP_HHOOK
8644 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8645 	hhook_run_tcp_est_in(tp, th, to);
8646 #endif
8647 
8648 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8649 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8650 	sbdrop(&so->so_snd, acked);
8651 
8652 	if (SEQ_GT(th->th_ack, tp->snd_una))
8653 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8654 	tp->snd_una = th->th_ack;
8655 	if (tp->snd_wnd < ctf_outstanding(tp))
8656 		/* The peer collapsed its window on us */
8657 		bbr_collapsed_window(bbr);
8658 	else if (bbr->rc_has_collapsed)
8659 		bbr_un_collapse_window(bbr);
8660 
8661 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8662 		tp->snd_recover = tp->snd_una;
8663 	}
8664 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8665 	/*
8666 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8667 	 */
8668 	tp->snd_wl2 = th->th_ack;
8669 	m_freem(m);
8670 	/*
8671 	 * If all outstanding data are acked, stop retransmit timer,
8672 	 * otherwise restart timer using current (possibly backed-off)
8673 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8674 	 * If data are ready to send, let tcp_output decide between more
8675 	 * output or persist.
8676 	 * Wake up the socket if we have room to write more.
8677 	 */
8678 	sowwakeup(so);
8679 	if (tp->snd_una == tp->snd_max) {
8680 		/* Nothing left outstanding */
8681 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8682 		if (sbavail(&so->so_snd) == 0)
8683 			bbr->rc_tp->t_acktime = 0;
8684 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8685 		if (bbr->rc_in_persist == 0) {
8686 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8687 		}
8688 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8689 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8690 		/*
8691 		 * We invalidate the last ack here since we
8692 		 * don't want to transfer forward the time
8693 		 * for our sum's calculations.
8694 		 */
8695 		bbr->r_wanted_output = 1;
8696 	}
8697 	if (sbavail(&so->so_snd)) {
8698 		bbr->r_wanted_output = 1;
8699 	}
8700 	return (1);
8701 }
8702 
8703 /*
8704  * Return value of 1, the TCB is unlocked and most
8705  * likely gone, return value of 0, the TCB is still
8706  * locked.
8707  */
8708 static int
8709 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8710     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8711     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8712 {
8713 	int32_t todrop;
8714 	int32_t ourfinisacked = 0;
8715 	struct tcp_bbr *bbr;
8716 	int32_t ret_val = 0;
8717 
8718 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8719 
8720 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8721 	ctf_calc_rwin(so, tp);
8722 	/*
8723 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8724 	 * SYN, drop the input. if seg contains a RST, then drop the
8725 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8726 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8727 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8728 	 * not support ECN so we will not say we are capable. if SYN has
8729 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8730 	 * segment to be acked (eventually) continue processing rest of
8731 	 * data/controls, beginning with URG
8732 	 */
8733 	if ((thflags & TH_ACK) &&
8734 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8735 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8736 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8737 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8738 		return (1);
8739 	}
8740 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8741 		TCP_PROBE5(connect__refused, NULL, tp,
8742 		    mtod(m, const char *), tp, th);
8743 		tp = tcp_drop(tp, ECONNREFUSED);
8744 		ctf_do_drop(m, tp);
8745 		return (1);
8746 	}
8747 	if (thflags & TH_RST) {
8748 		ctf_do_drop(m, tp);
8749 		return (1);
8750 	}
8751 	if (!(thflags & TH_SYN)) {
8752 		ctf_do_drop(m, tp);
8753 		return (1);
8754 	}
8755 	tp->irs = th->th_seq;
8756 	tcp_rcvseqinit(tp);
8757 	if (thflags & TH_ACK) {
8758 		int tfo_partial = 0;
8759 
8760 		KMOD_TCPSTAT_INC(tcps_connects);
8761 		soisconnected(so);
8762 #ifdef MAC
8763 		mac_socketpeer_set_from_mbuf(m, so);
8764 #endif
8765 		/* Do window scaling on this connection? */
8766 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8767 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8768 			tp->rcv_scale = tp->request_r_scale;
8769 		}
8770 		tp->rcv_adv += min(tp->rcv_wnd,
8771 		    TCP_MAXWIN << tp->rcv_scale);
8772 		/*
8773 		 * If not all the data that was sent in the TFO SYN
8774 		 * has been acked, resend the remainder right away.
8775 		 */
8776 		if (IS_FASTOPEN(tp->t_flags) &&
8777 		    (tp->snd_una != tp->snd_max)) {
8778 			tp->snd_nxt = th->th_ack;
8779 			tfo_partial = 1;
8780 		}
8781 		/*
8782 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8783 		 * will be turned on later.
8784 		 */
8785 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8786 			bbr->bbr_segs_rcvd += 1;
8787 			tp->t_flags |= TF_DELACK;
8788 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8789 		} else {
8790 			bbr->r_wanted_output = 1;
8791 			tp->t_flags |= TF_ACKNOW;
8792 		}
8793 		if (SEQ_GT(th->th_ack, tp->iss)) {
8794 			/*
8795 			 * The SYN is acked
8796 			 * handle it specially.
8797 			 */
8798 			bbr_log_syn(tp, to);
8799 		}
8800 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8801 			/*
8802 			 * We advance snd_una for the
8803 			 * fast open case. If th_ack is
8804 			 * acknowledging data beyond
8805 			 * snd_una we can't just call
8806 			 * ack-processing since the
8807 			 * data stream in our send-map
8808 			 * will start at snd_una + 1 (one
8809 			 * beyond the SYN). If its just
8810 			 * equal we don't need to do that
8811 			 * and there is no send_map.
8812 			 */
8813 			tp->snd_una++;
8814 		}
8815 		/*
8816 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8817 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8818 		 */
8819 		tp->t_starttime = ticks;
8820 		if (tp->t_flags & TF_NEEDFIN) {
8821 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8822 			tp->t_flags &= ~TF_NEEDFIN;
8823 			thflags &= ~TH_SYN;
8824 		} else {
8825 			tcp_state_change(tp, TCPS_ESTABLISHED);
8826 			TCP_PROBE5(connect__established, NULL, tp,
8827 			    mtod(m, const char *), tp, th);
8828 			cc_conn_init(tp);
8829 		}
8830 	} else {
8831 		/*
8832 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8833 		 * open.  If segment contains CC option and there is a
8834 		 * cached CC, apply TAO test. If it succeeds, connection is *
8835 		 * half-synchronized. Otherwise, do 3-way handshake:
8836 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8837 		 * there was no CC option, clear cached CC value.
8838 		 */
8839 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
8840 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8841 	}
8842 	/*
8843 	 * Advance th->th_seq to correspond to first data byte. If data,
8844 	 * trim to stay within window, dropping FIN if necessary.
8845 	 */
8846 	th->th_seq++;
8847 	if (tlen > tp->rcv_wnd) {
8848 		todrop = tlen - tp->rcv_wnd;
8849 		m_adj(m, -todrop);
8850 		tlen = tp->rcv_wnd;
8851 		thflags &= ~TH_FIN;
8852 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8853 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8854 	}
8855 	tp->snd_wl1 = th->th_seq - 1;
8856 	tp->rcv_up = th->th_seq;
8857 	/*
8858 	 * Client side of transaction: already sent SYN and data. If the
8859 	 * remote host used T/TCP to validate the SYN, our data will be
8860 	 * ACK'd; if so, enter normal data segment processing in the middle
8861 	 * of step 5, ack processing. Otherwise, goto step 6.
8862 	 */
8863 	if (thflags & TH_ACK) {
8864 		if ((to->to_flags & TOF_TS) != 0) {
8865 			uint32_t t, rtt;
8866 
8867 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8868 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8869 				rtt = t - to->to_tsecr;
8870 				if (rtt == 0) {
8871 					rtt = 1;
8872 				}
8873 				rtt *= MS_IN_USEC;
8874 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8875 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8876 						       rtt, bbr->r_ctl.rc_rcvtime);
8877 			}
8878 		}
8879 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8880 			return (ret_val);
8881 		/* We may have changed to FIN_WAIT_1 above */
8882 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8883 			/*
8884 			 * In FIN_WAIT_1 STATE in addition to the processing
8885 			 * for the ESTABLISHED state if our FIN is now
8886 			 * acknowledged then enter FIN_WAIT_2.
8887 			 */
8888 			if (ourfinisacked) {
8889 				/*
8890 				 * If we can't receive any more data, then
8891 				 * closing user can proceed. Starting the
8892 				 * timer is contrary to the specification,
8893 				 * but if we don't get a FIN we'll hang
8894 				 * forever.
8895 				 *
8896 				 * XXXjl: we should release the tp also, and
8897 				 * use a compressed state.
8898 				 */
8899 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8900 					soisdisconnected(so);
8901 					tcp_timer_activate(tp, TT_2MSL,
8902 					    (tcp_fast_finwait2_recycle ?
8903 					    tcp_finwait2_timeout :
8904 					    TP_MAXIDLE(tp)));
8905 				}
8906 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8907 			}
8908 		}
8909 	}
8910 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8911 	    tiwin, thflags, nxt_pkt));
8912 }
8913 
8914 /*
8915  * Return value of 1, the TCB is unlocked and most
8916  * likely gone, return value of 0, the TCB is still
8917  * locked.
8918  */
8919 static int
8920 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8921 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8922 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8923 {
8924 	int32_t ourfinisacked = 0;
8925 	int32_t ret_val;
8926 	struct tcp_bbr *bbr;
8927 
8928 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8929 
8930 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8931 	ctf_calc_rwin(so, tp);
8932 	if ((thflags & TH_RST) ||
8933 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
8934 		return (ctf_process_rst(m, th, so, tp));
8935 	if ((thflags & TH_ACK) &&
8936 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8937 	     SEQ_GT(th->th_ack, tp->snd_max))) {
8938 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8939 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8940 		return (1);
8941 	}
8942 	if (IS_FASTOPEN(tp->t_flags)) {
8943 		/*
8944 		 * When a TFO connection is in SYN_RECEIVED, the only valid
8945 		 * packets are the initial SYN, a retransmit/copy of the
8946 		 * initial SYN (possibly with a subset of the original
8947 		 * data), a valid ACK, a FIN, or a RST.
8948 		 */
8949 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
8950 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8951 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8952 			return (1);
8953 		} else if (thflags & TH_SYN) {
8954 			/* non-initial SYN is ignored */
8955 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
8956 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
8957 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
8958 				ctf_do_drop(m, NULL);
8959 				return (0);
8960 			}
8961 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
8962 			ctf_do_drop(m, NULL);
8963 			return (0);
8964 		}
8965 	}
8966 	/*
8967 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
8968 	 * it's less than ts_recent, drop it.
8969 	 */
8970 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
8971 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
8972 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
8973 			return (ret_val);
8974 	}
8975 	/*
8976 	 * In the SYN-RECEIVED state, validate that the packet belongs to
8977 	 * this connection before trimming the data to fit the receive
8978 	 * window.  Check the sequence number versus IRS since we know the
8979 	 * sequence numbers haven't wrapped.  This is a partial fix for the
8980 	 * "LAND" DoS attack.
8981 	 */
8982 	if (SEQ_LT(th->th_seq, tp->irs)) {
8983 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8984 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8985 		return (1);
8986 	}
8987 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
8988 		return (ret_val);
8989 	}
8990 	/*
8991 	 * If last ACK falls within this segment's sequence numbers, record
8992 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
8993 	 * from the latest proposal of the tcplw@cray.com list (Braden
8994 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
8995 	 * with our earlier PAWS tests, so this check should be solely
8996 	 * predicated on the sequence space of this segment. 3) That we
8997 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
8998 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
8999 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9000 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9001 	 * p.869. In such cases, we can still calculate the RTT correctly
9002 	 * when RCV.NXT == Last.ACK.Sent.
9003 	 */
9004 	if ((to->to_flags & TOF_TS) != 0 &&
9005 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9006 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9007 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9008 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9009 		tp->ts_recent = to->to_tsval;
9010 	}
9011 	tp->snd_wnd = tiwin;
9012 	/*
9013 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9014 	 * is on (half-synchronized state), then queue data for later
9015 	 * processing; else drop segment and return.
9016 	 */
9017 	if ((thflags & TH_ACK) == 0) {
9018 		if (IS_FASTOPEN(tp->t_flags)) {
9019 			cc_conn_init(tp);
9020 		}
9021 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9022 					 tiwin, thflags, nxt_pkt));
9023 	}
9024 	KMOD_TCPSTAT_INC(tcps_connects);
9025 	if (tp->t_flags & TF_SONOTCONN) {
9026 		tp->t_flags &= ~TF_SONOTCONN;
9027 		soisconnected(so);
9028 	}
9029 	/* Do window scaling? */
9030 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9031 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9032 		tp->rcv_scale = tp->request_r_scale;
9033 	}
9034 	/*
9035 	 * ok for the first time in lets see if we can use the ts to figure
9036 	 * out what the initial RTT was.
9037 	 */
9038 	if ((to->to_flags & TOF_TS) != 0) {
9039 		uint32_t t, rtt;
9040 
9041 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9042 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9043 			rtt = t - to->to_tsecr;
9044 			if (rtt == 0) {
9045 				rtt = 1;
9046 			}
9047 			rtt *= MS_IN_USEC;
9048 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9049 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9050 		}
9051 	}
9052 	/* Drop off any SYN in the send map (probably not there)  */
9053 	if (thflags & TH_ACK)
9054 		bbr_log_syn(tp, to);
9055 	if (IS_FASTOPEN(tp->t_flags) && tp->t_tfo_pending) {
9056 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9057 		tp->t_tfo_pending = NULL;
9058 	}
9059 	/*
9060 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9061 	 * FIN-WAIT-1
9062 	 */
9063 	tp->t_starttime = ticks;
9064 	if (tp->t_flags & TF_NEEDFIN) {
9065 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9066 		tp->t_flags &= ~TF_NEEDFIN;
9067 	} else {
9068 		tcp_state_change(tp, TCPS_ESTABLISHED);
9069 		TCP_PROBE5(accept__established, NULL, tp,
9070 			   mtod(m, const char *), tp, th);
9071 		/*
9072 		 * TFO connections call cc_conn_init() during SYN
9073 		 * processing.  Calling it again here for such connections
9074 		 * is not harmless as it would undo the snd_cwnd reduction
9075 		 * that occurs when a TFO SYN|ACK is retransmitted.
9076 		 */
9077 		if (!IS_FASTOPEN(tp->t_flags))
9078 			cc_conn_init(tp);
9079 	}
9080 	/*
9081 	 * Account for the ACK of our SYN prior to
9082 	 * regular ACK processing below, except for
9083 	 * simultaneous SYN, which is handled later.
9084 	 */
9085 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9086 		tp->snd_una++;
9087 	/*
9088 	 * If segment contains data or ACK, will call tcp_reass() later; if
9089 	 * not, do so now to pass queued data to user.
9090 	 */
9091 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9092 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9093 			(struct mbuf *)0);
9094 		if (tp->t_flags & TF_WAKESOR) {
9095 			tp->t_flags &= ~TF_WAKESOR;
9096 			/* NB: sorwakeup_locked() does an implicit unlock. */
9097 			sorwakeup_locked(so);
9098 		}
9099 	}
9100 	tp->snd_wl1 = th->th_seq - 1;
9101 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9102 		return (ret_val);
9103 	}
9104 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9105 		/* We could have went to FIN_WAIT_1 (or EST) above */
9106 		/*
9107 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9108 		 * ESTABLISHED state if our FIN is now acknowledged then
9109 		 * enter FIN_WAIT_2.
9110 		 */
9111 		if (ourfinisacked) {
9112 			/*
9113 			 * If we can't receive any more data, then closing
9114 			 * user can proceed. Starting the timer is contrary
9115 			 * to the specification, but if we don't get a FIN
9116 			 * we'll hang forever.
9117 			 *
9118 			 * XXXjl: we should release the tp also, and use a
9119 			 * compressed state.
9120 			 */
9121 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9122 				soisdisconnected(so);
9123 				tcp_timer_activate(tp, TT_2MSL,
9124 						   (tcp_fast_finwait2_recycle ?
9125 						    tcp_finwait2_timeout :
9126 						    TP_MAXIDLE(tp)));
9127 			}
9128 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9129 		}
9130 	}
9131 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9132 				 tiwin, thflags, nxt_pkt));
9133 }
9134 
9135 /*
9136  * Return value of 1, the TCB is unlocked and most
9137  * likely gone, return value of 0, the TCB is still
9138  * locked.
9139  */
9140 static int
9141 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9142     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9143     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9144 {
9145 	struct tcp_bbr *bbr;
9146 	int32_t ret_val;
9147 
9148 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9149 
9150 	/*
9151 	 * Header prediction: check for the two common cases of a
9152 	 * uni-directional data xfer.  If the packet has no control flags,
9153 	 * is in-sequence, the window didn't change and we're not
9154 	 * retransmitting, it's a candidate.  If the length is zero and the
9155 	 * ack moved forward, we're the sender side of the xfer.  Just free
9156 	 * the data acked & wake any higher level process that was blocked
9157 	 * waiting for space.  If the length is non-zero and the ack didn't
9158 	 * move, we're the receiver side.  If we're getting packets in-order
9159 	 * (the reassembly queue is empty), add the data toc The socket
9160 	 * buffer and note that we need a delayed ack. Make sure that the
9161 	 * hidden state-flags are also off. Since we check for
9162 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9163 	 */
9164 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9165 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9166 		/*
9167 		 * If we have delived under 4 segments increase the initial
9168 		 * window if raised by the peer. We use this to determine
9169 		 * dynamic and static rwnd's at the end of a connection.
9170 		 */
9171 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9172 	}
9173 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9174 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9175 	    __predict_true(SEGQ_EMPTY(tp)) &&
9176 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9177 		if (tlen == 0) {
9178 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9179 			    tiwin, nxt_pkt, iptos)) {
9180 				return (0);
9181 			}
9182 		} else {
9183 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9184 			    tiwin, nxt_pkt)) {
9185 				return (0);
9186 			}
9187 		}
9188 	}
9189 	ctf_calc_rwin(so, tp);
9190 
9191 	if ((thflags & TH_RST) ||
9192 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9193 		return (ctf_process_rst(m, th, so, tp));
9194 	/*
9195 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9196 	 * synchronized state.
9197 	 */
9198 	if (thflags & TH_SYN) {
9199 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9200 		return (ret_val);
9201 	}
9202 	/*
9203 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9204 	 * it's less than ts_recent, drop it.
9205 	 */
9206 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9207 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9208 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9209 			return (ret_val);
9210 	}
9211 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9212 		return (ret_val);
9213 	}
9214 	/*
9215 	 * If last ACK falls within this segment's sequence numbers, record
9216 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9217 	 * from the latest proposal of the tcplw@cray.com list (Braden
9218 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9219 	 * with our earlier PAWS tests, so this check should be solely
9220 	 * predicated on the sequence space of this segment. 3) That we
9221 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9222 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9223 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9224 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9225 	 * p.869. In such cases, we can still calculate the RTT correctly
9226 	 * when RCV.NXT == Last.ACK.Sent.
9227 	 */
9228 	if ((to->to_flags & TOF_TS) != 0 &&
9229 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9230 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9231 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9232 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9233 		tp->ts_recent = to->to_tsval;
9234 	}
9235 	/*
9236 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9237 	 * is on (half-synchronized state), then queue data for later
9238 	 * processing; else drop segment and return.
9239 	 */
9240 	if ((thflags & TH_ACK) == 0) {
9241 		if (tp->t_flags & TF_NEEDSYN) {
9242 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9243 			    tiwin, thflags, nxt_pkt));
9244 		} else if (tp->t_flags & TF_ACKNOW) {
9245 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9246 			bbr->r_wanted_output = 1;
9247 			return (ret_val);
9248 		} else {
9249 			ctf_do_drop(m, NULL);
9250 			return (0);
9251 		}
9252 	}
9253 	/*
9254 	 * Ack processing.
9255 	 */
9256 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9257 		return (ret_val);
9258 	}
9259 	if (sbavail(&so->so_snd)) {
9260 		if (ctf_progress_timeout_check(tp, true)) {
9261 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9262 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9263 			return (1);
9264 		}
9265 	}
9266 	/* State changes only happen in bbr_process_data() */
9267 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9268 	    tiwin, thflags, nxt_pkt));
9269 }
9270 
9271 /*
9272  * Return value of 1, the TCB is unlocked and most
9273  * likely gone, return value of 0, the TCB is still
9274  * locked.
9275  */
9276 static int
9277 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9278     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9279     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9280 {
9281 	struct tcp_bbr *bbr;
9282 	int32_t ret_val;
9283 
9284 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9285 
9286 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9287 	ctf_calc_rwin(so, tp);
9288 	if ((thflags & TH_RST) ||
9289 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9290 		return (ctf_process_rst(m, th, so, tp));
9291 	/*
9292 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9293 	 * synchronized state.
9294 	 */
9295 	if (thflags & TH_SYN) {
9296 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9297 		return (ret_val);
9298 	}
9299 	/*
9300 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9301 	 * it's less than ts_recent, drop it.
9302 	 */
9303 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9304 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9305 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9306 			return (ret_val);
9307 	}
9308 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9309 		return (ret_val);
9310 	}
9311 	/*
9312 	 * If last ACK falls within this segment's sequence numbers, record
9313 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9314 	 * from the latest proposal of the tcplw@cray.com list (Braden
9315 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9316 	 * with our earlier PAWS tests, so this check should be solely
9317 	 * predicated on the sequence space of this segment. 3) That we
9318 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9319 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9320 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9321 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9322 	 * p.869. In such cases, we can still calculate the RTT correctly
9323 	 * when RCV.NXT == Last.ACK.Sent.
9324 	 */
9325 	if ((to->to_flags & TOF_TS) != 0 &&
9326 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9327 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9328 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9329 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9330 		tp->ts_recent = to->to_tsval;
9331 	}
9332 	/*
9333 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9334 	 * is on (half-synchronized state), then queue data for later
9335 	 * processing; else drop segment and return.
9336 	 */
9337 	if ((thflags & TH_ACK) == 0) {
9338 		if (tp->t_flags & TF_NEEDSYN) {
9339 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9340 			    tiwin, thflags, nxt_pkt));
9341 		} else if (tp->t_flags & TF_ACKNOW) {
9342 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9343 			bbr->r_wanted_output = 1;
9344 			return (ret_val);
9345 		} else {
9346 			ctf_do_drop(m, NULL);
9347 			return (0);
9348 		}
9349 	}
9350 	/*
9351 	 * Ack processing.
9352 	 */
9353 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9354 		return (ret_val);
9355 	}
9356 	if (sbavail(&so->so_snd)) {
9357 		if (ctf_progress_timeout_check(tp, true)) {
9358 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9359 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9360 			return (1);
9361 		}
9362 	}
9363 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9364 	    tiwin, thflags, nxt_pkt));
9365 }
9366 
9367 static int
9368 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9369     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9370 {
9371 
9372 	if (bbr->rc_allow_data_af_clo == 0) {
9373 close_now:
9374 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9375 		/* tcp_close will kill the inp pre-log the Reset */
9376 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9377 		tp = tcp_close(tp);
9378 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9379 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9380 		return (1);
9381 	}
9382 	if (sbavail(&so->so_snd) == 0)
9383 		goto close_now;
9384 	/* Ok we allow data that is ignored and a followup reset */
9385 	tp->rcv_nxt = th->th_seq + *tlen;
9386 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9387 	bbr->r_wanted_output = 1;
9388 	*tlen = 0;
9389 	return (0);
9390 }
9391 
9392 /*
9393  * Return value of 1, the TCB is unlocked and most
9394  * likely gone, return value of 0, the TCB is still
9395  * locked.
9396  */
9397 static int
9398 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9399     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9400     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9401 {
9402 	int32_t ourfinisacked = 0;
9403 	int32_t ret_val;
9404 	struct tcp_bbr *bbr;
9405 
9406 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9407 
9408 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9409 	ctf_calc_rwin(so, tp);
9410 	if ((thflags & TH_RST) ||
9411 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9412 		return (ctf_process_rst(m, th, so, tp));
9413 	/*
9414 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9415 	 * synchronized state.
9416 	 */
9417 	if (thflags & TH_SYN) {
9418 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9419 		return (ret_val);
9420 	}
9421 	/*
9422 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9423 	 * it's less than ts_recent, drop it.
9424 	 */
9425 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9426 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9427 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9428 			return (ret_val);
9429 	}
9430 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9431 		return (ret_val);
9432 	}
9433 	/*
9434 	 * If new data are received on a connection after the user processes
9435 	 * are gone, then RST the other end.
9436 	 * We call a new function now so we might continue and setup
9437 	 * to reset at all data being ack'd.
9438 	 */
9439 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9440 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9441 		return (1);
9442 	/*
9443 	 * If last ACK falls within this segment's sequence numbers, record
9444 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9445 	 * from the latest proposal of the tcplw@cray.com list (Braden
9446 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9447 	 * with our earlier PAWS tests, so this check should be solely
9448 	 * predicated on the sequence space of this segment. 3) That we
9449 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9450 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9451 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9452 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9453 	 * p.869. In such cases, we can still calculate the RTT correctly
9454 	 * when RCV.NXT == Last.ACK.Sent.
9455 	 */
9456 	if ((to->to_flags & TOF_TS) != 0 &&
9457 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9458 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9459 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9460 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9461 		tp->ts_recent = to->to_tsval;
9462 	}
9463 	/*
9464 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9465 	 * is on (half-synchronized state), then queue data for later
9466 	 * processing; else drop segment and return.
9467 	 */
9468 	if ((thflags & TH_ACK) == 0) {
9469 		if (tp->t_flags & TF_NEEDSYN) {
9470 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9471 			    tiwin, thflags, nxt_pkt));
9472 		} else if (tp->t_flags & TF_ACKNOW) {
9473 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9474 			bbr->r_wanted_output = 1;
9475 			return (ret_val);
9476 		} else {
9477 			ctf_do_drop(m, NULL);
9478 			return (0);
9479 		}
9480 	}
9481 	/*
9482 	 * Ack processing.
9483 	 */
9484 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9485 		return (ret_val);
9486 	}
9487 	if (ourfinisacked) {
9488 		/*
9489 		 * If we can't receive any more data, then closing user can
9490 		 * proceed. Starting the timer is contrary to the
9491 		 * specification, but if we don't get a FIN we'll hang
9492 		 * forever.
9493 		 *
9494 		 * XXXjl: we should release the tp also, and use a
9495 		 * compressed state.
9496 		 */
9497 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9498 			soisdisconnected(so);
9499 			tcp_timer_activate(tp, TT_2MSL,
9500 			    (tcp_fast_finwait2_recycle ?
9501 			    tcp_finwait2_timeout :
9502 			    TP_MAXIDLE(tp)));
9503 		}
9504 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9505 	}
9506 	if (sbavail(&so->so_snd)) {
9507 		if (ctf_progress_timeout_check(tp, true)) {
9508 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9509 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9510 			return (1);
9511 		}
9512 	}
9513 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9514 	    tiwin, thflags, nxt_pkt));
9515 }
9516 
9517 /*
9518  * Return value of 1, the TCB is unlocked and most
9519  * likely gone, return value of 0, the TCB is still
9520  * locked.
9521  */
9522 static int
9523 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9524     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9525     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9526 {
9527 	int32_t ourfinisacked = 0;
9528 	int32_t ret_val;
9529 	struct tcp_bbr *bbr;
9530 
9531 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9532 
9533 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9534 	ctf_calc_rwin(so, tp);
9535 	if ((thflags & TH_RST) ||
9536 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9537 		return (ctf_process_rst(m, th, so, tp));
9538 	/*
9539 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9540 	 * synchronized state.
9541 	 */
9542 	if (thflags & TH_SYN) {
9543 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9544 		return (ret_val);
9545 	}
9546 	/*
9547 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9548 	 * it's less than ts_recent, drop it.
9549 	 */
9550 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9551 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9552 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9553 			return (ret_val);
9554 	}
9555 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9556 		return (ret_val);
9557 	}
9558 	/*
9559 	 * If new data are received on a connection after the user processes
9560 	 * are gone, then RST the other end.
9561 	 * We call a new function now so we might continue and setup
9562 	 * to reset at all data being ack'd.
9563 	 */
9564 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9565 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9566 		return (1);
9567 	/*
9568 	 * If last ACK falls within this segment's sequence numbers, record
9569 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9570 	 * from the latest proposal of the tcplw@cray.com list (Braden
9571 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9572 	 * with our earlier PAWS tests, so this check should be solely
9573 	 * predicated on the sequence space of this segment. 3) That we
9574 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9575 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9576 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9577 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9578 	 * p.869. In such cases, we can still calculate the RTT correctly
9579 	 * when RCV.NXT == Last.ACK.Sent.
9580 	 */
9581 	if ((to->to_flags & TOF_TS) != 0 &&
9582 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9583 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9584 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9585 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9586 		tp->ts_recent = to->to_tsval;
9587 	}
9588 	/*
9589 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9590 	 * is on (half-synchronized state), then queue data for later
9591 	 * processing; else drop segment and return.
9592 	 */
9593 	if ((thflags & TH_ACK) == 0) {
9594 		if (tp->t_flags & TF_NEEDSYN) {
9595 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9596 			    tiwin, thflags, nxt_pkt));
9597 		} else if (tp->t_flags & TF_ACKNOW) {
9598 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9599 			bbr->r_wanted_output = 1;
9600 			return (ret_val);
9601 		} else {
9602 			ctf_do_drop(m, NULL);
9603 			return (0);
9604 		}
9605 	}
9606 	/*
9607 	 * Ack processing.
9608 	 */
9609 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9610 		return (ret_val);
9611 	}
9612 	if (ourfinisacked) {
9613 		tcp_twstart(tp);
9614 		m_freem(m);
9615 		return (1);
9616 	}
9617 	if (sbavail(&so->so_snd)) {
9618 		if (ctf_progress_timeout_check(tp, true)) {
9619 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9620 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9621 			return (1);
9622 		}
9623 	}
9624 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9625 	    tiwin, thflags, nxt_pkt));
9626 }
9627 
9628 /*
9629  * Return value of 1, the TCB is unlocked and most
9630  * likely gone, return value of 0, the TCB is still
9631  * locked.
9632  */
9633 static int
9634 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9635     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9636     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9637 {
9638 	int32_t ourfinisacked = 0;
9639 	int32_t ret_val;
9640 	struct tcp_bbr *bbr;
9641 
9642 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9643 
9644 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9645 	ctf_calc_rwin(so, tp);
9646 	if ((thflags & TH_RST) ||
9647 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9648 		return (ctf_process_rst(m, th, so, tp));
9649 	/*
9650 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9651 	 * synchronized state.
9652 	 */
9653 	if (thflags & TH_SYN) {
9654 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9655 		return (ret_val);
9656 	}
9657 	/*
9658 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9659 	 * it's less than ts_recent, drop it.
9660 	 */
9661 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9662 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9663 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9664 			return (ret_val);
9665 	}
9666 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9667 		return (ret_val);
9668 	}
9669 	/*
9670 	 * If new data are received on a connection after the user processes
9671 	 * are gone, then RST the other end.
9672 	 * We call a new function now so we might continue and setup
9673 	 * to reset at all data being ack'd.
9674 	 */
9675 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9676 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9677 		return (1);
9678 	/*
9679 	 * If last ACK falls within this segment's sequence numbers, record
9680 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9681 	 * from the latest proposal of the tcplw@cray.com list (Braden
9682 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9683 	 * with our earlier PAWS tests, so this check should be solely
9684 	 * predicated on the sequence space of this segment. 3) That we
9685 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9686 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9687 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9688 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9689 	 * p.869. In such cases, we can still calculate the RTT correctly
9690 	 * when RCV.NXT == Last.ACK.Sent.
9691 	 */
9692 	if ((to->to_flags & TOF_TS) != 0 &&
9693 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9694 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9695 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9696 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9697 		tp->ts_recent = to->to_tsval;
9698 	}
9699 	/*
9700 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9701 	 * is on (half-synchronized state), then queue data for later
9702 	 * processing; else drop segment and return.
9703 	 */
9704 	if ((thflags & TH_ACK) == 0) {
9705 		if (tp->t_flags & TF_NEEDSYN) {
9706 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9707 			    tiwin, thflags, nxt_pkt));
9708 		} else if (tp->t_flags & TF_ACKNOW) {
9709 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9710 			bbr->r_wanted_output = 1;
9711 			return (ret_val);
9712 		} else {
9713 			ctf_do_drop(m, NULL);
9714 			return (0);
9715 		}
9716 	}
9717 	/*
9718 	 * case TCPS_LAST_ACK: Ack processing.
9719 	 */
9720 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9721 		return (ret_val);
9722 	}
9723 	if (ourfinisacked) {
9724 		tp = tcp_close(tp);
9725 		ctf_do_drop(m, tp);
9726 		return (1);
9727 	}
9728 	if (sbavail(&so->so_snd)) {
9729 		if (ctf_progress_timeout_check(tp, true)) {
9730 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9731 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9732 			return (1);
9733 		}
9734 	}
9735 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9736 	    tiwin, thflags, nxt_pkt));
9737 }
9738 
9739 /*
9740  * Return value of 1, the TCB is unlocked and most
9741  * likely gone, return value of 0, the TCB is still
9742  * locked.
9743  */
9744 static int
9745 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9746     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9747     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9748 {
9749 	int32_t ourfinisacked = 0;
9750 	int32_t ret_val;
9751 	struct tcp_bbr *bbr;
9752 
9753 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9754 
9755 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9756 	ctf_calc_rwin(so, tp);
9757 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9758 	if ((thflags & TH_RST) ||
9759 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9760 		return (ctf_process_rst(m, th, so, tp));
9761 
9762 	/*
9763 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9764 	 * synchronized state.
9765 	 */
9766 	if (thflags & TH_SYN) {
9767 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9768 		return (ret_val);
9769 	}
9770 	/*
9771 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9772 	 * it's less than ts_recent, drop it.
9773 	 */
9774 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9775 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9776 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9777 			return (ret_val);
9778 	}
9779 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9780 		return (ret_val);
9781 	}
9782 	/*
9783 	 * If new data are received on a connection after the user processes
9784 	 * are gone, then we may RST the other end depending on the outcome
9785 	 * of bbr_check_data_after_close.
9786 	 * We call a new function now so we might continue and setup
9787 	 * to reset at all data being ack'd.
9788 	 */
9789 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9790 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9791 		return (1);
9792 	/*
9793 	 * If last ACK falls within this segment's sequence numbers, record
9794 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9795 	 * from the latest proposal of the tcplw@cray.com list (Braden
9796 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9797 	 * with our earlier PAWS tests, so this check should be solely
9798 	 * predicated on the sequence space of this segment. 3) That we
9799 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9800 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9801 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9802 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9803 	 * p.869. In such cases, we can still calculate the RTT correctly
9804 	 * when RCV.NXT == Last.ACK.Sent.
9805 	 */
9806 	if ((to->to_flags & TOF_TS) != 0 &&
9807 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9808 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9809 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9810 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9811 		tp->ts_recent = to->to_tsval;
9812 	}
9813 	/*
9814 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9815 	 * is on (half-synchronized state), then queue data for later
9816 	 * processing; else drop segment and return.
9817 	 */
9818 	if ((thflags & TH_ACK) == 0) {
9819 		if (tp->t_flags & TF_NEEDSYN) {
9820 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9821 			    tiwin, thflags, nxt_pkt));
9822 		} else if (tp->t_flags & TF_ACKNOW) {
9823 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9824 			bbr->r_wanted_output = 1;
9825 			return (ret_val);
9826 		} else {
9827 			ctf_do_drop(m, NULL);
9828 			return (0);
9829 		}
9830 	}
9831 	/*
9832 	 * Ack processing.
9833 	 */
9834 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9835 		return (ret_val);
9836 	}
9837 	if (sbavail(&so->so_snd)) {
9838 		if (ctf_progress_timeout_check(tp, true)) {
9839 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9840 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9841 			return (1);
9842 		}
9843 	}
9844 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9845 	    tiwin, thflags, nxt_pkt));
9846 }
9847 
9848 static void
9849 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr)
9850 {
9851 	/*
9852 	 * Assure no timers are running.
9853 	 */
9854 	if (tcp_timer_active(tp, TT_PERSIST)) {
9855 		/* We enter in persists, set the flag appropriately */
9856 		bbr->rc_in_persist = 1;
9857 	}
9858 	if (tcp_in_hpts(bbr->rc_tp)) {
9859 		tcp_hpts_remove(bbr->rc_tp);
9860 	}
9861 }
9862 
9863 static void
9864 bbr_google_mode_on(struct tcp_bbr *bbr)
9865 {
9866 	bbr->rc_use_google = 1;
9867 	bbr->rc_no_pacing = 0;
9868 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9869 	bbr->r_use_policer = bbr_policer_detection_enabled;
9870 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9871 	bbr->bbr_use_rack_cheat = 0;
9872 	bbr->r_ctl.rc_incr_tmrs = 0;
9873 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9874 	bbr->r_ctl.rc_inc_ip_oh = 0;
9875 	bbr->r_ctl.rc_inc_enet_oh = 0;
9876 	reset_time(&bbr->r_ctl.rc_delrate,
9877 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9878 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9879 			 (11 * USECS_IN_SECOND));
9880 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9881 }
9882 
9883 static void
9884 bbr_google_mode_off(struct tcp_bbr *bbr)
9885 {
9886 	bbr->rc_use_google = 0;
9887 	bbr->r_ctl.bbr_google_discount = 0;
9888 	bbr->no_pacing_until = bbr_no_pacing_until;
9889 	bbr->r_use_policer = 0;
9890 	if (bbr->no_pacing_until)
9891 		bbr->rc_no_pacing = 1;
9892 	else
9893 		bbr->rc_no_pacing = 0;
9894 	if (bbr_use_rack_resend_cheat)
9895 		bbr->bbr_use_rack_cheat = 1;
9896 	else
9897 		bbr->bbr_use_rack_cheat = 0;
9898 	if (bbr_incr_timers)
9899 		bbr->r_ctl.rc_incr_tmrs = 1;
9900 	else
9901 		bbr->r_ctl.rc_incr_tmrs = 0;
9902 	if (bbr_include_tcp_oh)
9903 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9904 	else
9905 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9906 	if (bbr_include_ip_oh)
9907 		bbr->r_ctl.rc_inc_ip_oh = 1;
9908 	else
9909 		bbr->r_ctl.rc_inc_ip_oh = 0;
9910 	if (bbr_include_enet_oh)
9911 		bbr->r_ctl.rc_inc_enet_oh = 1;
9912 	else
9913 		bbr->r_ctl.rc_inc_enet_oh = 0;
9914 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9915 	reset_time(&bbr->r_ctl.rc_delrate,
9916 		   bbr_num_pktepo_for_del_limit);
9917 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9918 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9919 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9920 }
9921 /*
9922  * Return 0 on success, non-zero on failure
9923  * which indicates the error (usually no memory).
9924  */
9925 static int
9926 bbr_init(struct tcpcb *tp, void **ptr)
9927 {
9928 	struct inpcb *inp = tptoinpcb(tp);
9929 	struct tcp_bbr *bbr = NULL;
9930 	uint32_t cts;
9931 
9932 	tcp_hpts_init(tp);
9933 
9934 	*ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
9935 	if (*ptr == NULL) {
9936 		/*
9937 		 * We need to allocate memory but cant. The INP and INP_INFO
9938 		 * locks and they are recursive (happens during setup. So a
9939 		 * scheme to drop the locks fails :(
9940 		 *
9941 		 */
9942 		return (ENOMEM);
9943 	}
9944 	bbr = (struct tcp_bbr *)*ptr;
9945 	bbr->rtt_valid = 0;
9946 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
9947 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
9948 	/* Take off any undesired flags */
9949 	tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
9950 	tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
9951 	tp->t_flags2 &= ~TF2_MBUF_ACKCMP;
9952 	tp->t_flags2 &= ~TF2_MBUF_L_ACKS;
9953 
9954 	TAILQ_INIT(&bbr->r_ctl.rc_map);
9955 	TAILQ_INIT(&bbr->r_ctl.rc_free);
9956 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
9957 	bbr->rc_tp = tp;
9958 	bbr->rc_inp = inp;
9959 	cts = tcp_get_usecs(&bbr->rc_tv);
9960 	tp->t_acktime = 0;
9961 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
9962 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
9963 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
9964 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
9965 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
9966 	bbr->r_ctl.rc_min_to = bbr_min_to;
9967 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
9968 	bbr->r_ctl.bbr_lost_at_state = 0;
9969 	bbr->r_ctl.rc_lost_at_startup = 0;
9970 	bbr->rc_all_timers_stopped = 0;
9971 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
9972 	bbr->r_ctl.rc_pkt_epoch_del = 0;
9973 	bbr->r_ctl.rc_pkt_epoch = 0;
9974 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
9975 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
9976 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
9977 	bbr->r_ctl.rc_went_idle_time = cts;
9978 	bbr->rc_pacer_started = cts;
9979 	bbr->r_ctl.rc_pkt_epoch_time = cts;
9980 	bbr->r_ctl.rc_rcvtime = cts;
9981 	bbr->r_ctl.rc_bbr_state_time = cts;
9982 	bbr->r_ctl.rc_del_time = cts;
9983 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
9984 	bbr->r_ctl.last_in_probertt = cts;
9985 	bbr->skip_gain = 0;
9986 	bbr->gain_is_limited = 0;
9987 	bbr->no_pacing_until = bbr_no_pacing_until;
9988 	if (bbr->no_pacing_until)
9989 		bbr->rc_no_pacing = 1;
9990 	if (bbr_use_google_algo) {
9991 		bbr->rc_no_pacing = 0;
9992 		bbr->rc_use_google = 1;
9993 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9994 		bbr->r_use_policer = bbr_policer_detection_enabled;
9995 	} else {
9996 		bbr->rc_use_google = 0;
9997 		bbr->r_ctl.bbr_google_discount = 0;
9998 		bbr->r_use_policer = 0;
9999 	}
10000 	if (bbr_ts_limiting)
10001 		bbr->rc_use_ts_limit = 1;
10002 	else
10003 		bbr->rc_use_ts_limit = 0;
10004 	if (bbr_ts_can_raise)
10005 		bbr->ts_can_raise = 1;
10006 	else
10007 		bbr->ts_can_raise = 0;
10008 	if (V_tcp_delack_enabled == 1)
10009 		tp->t_delayed_ack = 2;
10010 	else if (V_tcp_delack_enabled == 0)
10011 		tp->t_delayed_ack = 0;
10012 	else if (V_tcp_delack_enabled < 100)
10013 		tp->t_delayed_ack = V_tcp_delack_enabled;
10014 	else
10015 		tp->t_delayed_ack = 2;
10016 	if (bbr->rc_use_google == 0)
10017 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10018 	else
10019 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10020 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10021 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10022 	bbr->rc_init_win = bbr_def_init_win;
10023 	if (tp->t_flags & TF_REQ_TSTMP)
10024 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10025 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10026 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10027 	bbr->r_init_rtt = 1;
10028 
10029 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10030 	if (bbr_allow_hdwr_pacing)
10031 		bbr->bbr_hdw_pace_ena = 1;
10032 	else
10033 		bbr->bbr_hdw_pace_ena = 0;
10034 	if (bbr_sends_full_iwnd)
10035 		bbr->bbr_init_win_cheat = 1;
10036 	else
10037 		bbr->bbr_init_win_cheat = 0;
10038 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10039 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10040 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10041 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10042 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10043 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10044 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10045 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10046 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10047 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10048 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10049 	bbr->r_ctl.rc_rtt_shrinks = cts;
10050 	if (bbr->rc_use_google) {
10051 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10052 				  FILTER_TYPE_MAX,
10053 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10054 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10055 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10056 	} else {
10057 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10058 				  FILTER_TYPE_MAX,
10059 				  bbr_num_pktepo_for_del_limit);
10060 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10061 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10062 	}
10063 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10064 	if (bbr_uses_idle_restart)
10065 		bbr->rc_use_idle_restart = 1;
10066 	else
10067 		bbr->rc_use_idle_restart = 0;
10068 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10069 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10070 	if (bbr_resends_use_tso)
10071 		bbr->rc_resends_use_tso = 1;
10072 	if (tp->snd_una != tp->snd_max) {
10073 		/* Create a send map for the current outstanding data */
10074 		struct bbr_sendmap *rsm;
10075 
10076 		rsm = bbr_alloc(bbr);
10077 		if (rsm == NULL) {
10078 			uma_zfree(bbr_pcb_zone, *ptr);
10079 			*ptr = NULL;
10080 			return (ENOMEM);
10081 		}
10082 		rsm->r_rtt_not_allowed = 1;
10083 		rsm->r_tim_lastsent[0] = cts;
10084 		rsm->r_rtr_cnt = 1;
10085 		rsm->r_rtr_bytes = 0;
10086 		rsm->r_start = tp->snd_una;
10087 		rsm->r_end = tp->snd_max;
10088 		rsm->r_dupack = 0;
10089 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10090 		rsm->r_ts_valid = 0;
10091 		rsm->r_del_ack_ts = tp->ts_recent;
10092 		rsm->r_del_time = cts;
10093 		if (bbr->r_ctl.r_app_limited_until)
10094 			rsm->r_app_limited = 1;
10095 		else
10096 			rsm->r_app_limited = 0;
10097 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10098 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10099 		rsm->r_in_tmap = 1;
10100 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10101 			rsm->r_bbr_state = bbr_state_val(bbr);
10102 		else
10103 			rsm->r_bbr_state = 8;
10104 	}
10105 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10106 		bbr->bbr_use_rack_cheat = 1;
10107 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10108 		bbr->r_ctl.rc_incr_tmrs = 1;
10109 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10110 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10111 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10112 		bbr->r_ctl.rc_inc_ip_oh = 1;
10113 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10114 		bbr->r_ctl.rc_inc_enet_oh = 1;
10115 
10116 	bbr_log_type_statechange(bbr, cts, __LINE__);
10117 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10118 	    (tp->t_srtt)) {
10119 		uint32_t rtt;
10120 
10121 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10122 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10123 	}
10124 	/* announce the settings and state */
10125 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10126 	tcp_bbr_tso_size_check(bbr, cts);
10127 	/*
10128 	 * Now call the generic function to start a timer. This will place
10129 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10130 	 * flags.
10131 	 */
10132 	bbr_stop_all_timers(tp, bbr);
10133 	/*
10134 	 * Validate the timers are not in usec, if they are convert.
10135 	 * BBR should in theory move to USEC and get rid of a
10136 	 * lot of the TICKS_2 calls.. but for now we stay
10137 	 * with tick timers.
10138 	 */
10139 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
10140 	TCPT_RANGESET(tp->t_rxtcur,
10141 	    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
10142 	    tp->t_rttmin, TCPTV_REXMTMAX);
10143 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10144 	return (0);
10145 }
10146 
10147 /*
10148  * Return 0 if we can accept the connection. Return
10149  * non-zero if we can't handle the connection. A EAGAIN
10150  * means you need to wait until the connection is up.
10151  * a EADDRNOTAVAIL means we can never handle the connection
10152  * (no SACK).
10153  */
10154 static int
10155 bbr_handoff_ok(struct tcpcb *tp)
10156 {
10157 	if ((tp->t_state == TCPS_CLOSED) ||
10158 	    (tp->t_state == TCPS_LISTEN)) {
10159 		/* Sure no problem though it may not stick */
10160 		return (0);
10161 	}
10162 	if ((tp->t_state == TCPS_SYN_SENT) ||
10163 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10164 		/*
10165 		 * We really don't know you have to get to ESTAB or beyond
10166 		 * to tell.
10167 		 */
10168 		return (EAGAIN);
10169 	}
10170 	if (tp->t_flags & TF_SENTFIN)
10171 		return (EINVAL);
10172 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10173 		return (0);
10174 	}
10175 	/*
10176 	 * If we reach here we don't do SACK on this connection so we can
10177 	 * never do rack.
10178 	 */
10179 	return (EINVAL);
10180 }
10181 
10182 static void
10183 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10184 {
10185 	if (tp->t_fb_ptr) {
10186 		uint32_t calc;
10187 		struct tcp_bbr *bbr;
10188 		struct bbr_sendmap *rsm;
10189 
10190 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10191 		if (bbr->r_ctl.crte)
10192 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10193 		bbr_log_flowend(bbr);
10194 		bbr->rc_tp = NULL;
10195 		if (bbr->bbr_hdrw_pacing)
10196 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10197 		else
10198 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10199 		if (bbr->r_ctl.crte != NULL) {
10200 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10201 			bbr->r_ctl.crte = NULL;
10202 		}
10203 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10204 		while (rsm) {
10205 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10206 			uma_zfree(bbr_zone, rsm);
10207 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10208 		}
10209 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10210 		while (rsm) {
10211 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10212 			uma_zfree(bbr_zone, rsm);
10213 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10214 		}
10215 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10216 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10217 			BBR_STAT_INC(bbr_dynamic_rwnd);
10218 		else
10219 			BBR_STAT_INC(bbr_static_rwnd);
10220 		bbr->r_ctl.rc_free_cnt = 0;
10221 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10222 		tp->t_fb_ptr = NULL;
10223 	}
10224 	/* Make sure snd_nxt is correctly set */
10225 	tp->snd_nxt = tp->snd_max;
10226 }
10227 
10228 static void
10229 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10230 {
10231 	switch (tp->t_state) {
10232 	case TCPS_SYN_SENT:
10233 		bbr->r_state = TCPS_SYN_SENT;
10234 		bbr->r_substate = bbr_do_syn_sent;
10235 		break;
10236 	case TCPS_SYN_RECEIVED:
10237 		bbr->r_state = TCPS_SYN_RECEIVED;
10238 		bbr->r_substate = bbr_do_syn_recv;
10239 		break;
10240 	case TCPS_ESTABLISHED:
10241 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10242 		bbr->r_state = TCPS_ESTABLISHED;
10243 		bbr->r_substate = bbr_do_established;
10244 		break;
10245 	case TCPS_CLOSE_WAIT:
10246 		bbr->r_state = TCPS_CLOSE_WAIT;
10247 		bbr->r_substate = bbr_do_close_wait;
10248 		break;
10249 	case TCPS_FIN_WAIT_1:
10250 		bbr->r_state = TCPS_FIN_WAIT_1;
10251 		bbr->r_substate = bbr_do_fin_wait_1;
10252 		break;
10253 	case TCPS_CLOSING:
10254 		bbr->r_state = TCPS_CLOSING;
10255 		bbr->r_substate = bbr_do_closing;
10256 		break;
10257 	case TCPS_LAST_ACK:
10258 		bbr->r_state = TCPS_LAST_ACK;
10259 		bbr->r_substate = bbr_do_lastack;
10260 		break;
10261 	case TCPS_FIN_WAIT_2:
10262 		bbr->r_state = TCPS_FIN_WAIT_2;
10263 		bbr->r_substate = bbr_do_fin_wait_2;
10264 		break;
10265 	case TCPS_LISTEN:
10266 	case TCPS_CLOSED:
10267 	case TCPS_TIME_WAIT:
10268 	default:
10269 		break;
10270 	};
10271 }
10272 
10273 static void
10274 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10275 {
10276 	/*
10277 	 * Now what state are we going into now? Is there adjustments
10278 	 * needed?
10279 	 */
10280 	int32_t old_state;
10281 
10282 	old_state = bbr_state_val(bbr);
10283 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10284 		/* Save the lowest srtt we saw in our end of the sub-state */
10285 		bbr->rc_hit_state_1 = 0;
10286 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10287 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10288 	}
10289 	bbr->rc_bbr_substate++;
10290 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10291 		/* Cycle back to first state-> gain */
10292 		bbr->rc_bbr_substate = 0;
10293 	}
10294 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10295 		/*
10296 		 * We enter the gain(5/4) cycle (possibly less if
10297 		 * shallow buffer detection is enabled)
10298 		 */
10299 		if (bbr->skip_gain) {
10300 			/*
10301 			 * Hardware pacing has set our rate to
10302 			 * the max and limited our b/w just
10303 			 * do level i.e. no gain.
10304 			 */
10305 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10306 		} else if (bbr->gain_is_limited &&
10307 			   bbr->bbr_hdrw_pacing &&
10308 			   bbr->r_ctl.crte) {
10309 			/*
10310 			 * We can't gain above the hardware pacing
10311 			 * rate which is less than our rate + the gain
10312 			 * calculate the gain needed to reach the hardware
10313 			 * pacing rate..
10314 			 */
10315 			uint64_t bw, rate, gain_calc;
10316 
10317 			bw = bbr_get_bw(bbr);
10318 			rate = bbr->r_ctl.crte->rate;
10319 			if ((rate > bw) &&
10320 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10321 				gain_calc = (rate * BBR_UNIT) / bw;
10322 				if (gain_calc < BBR_UNIT)
10323 					gain_calc = BBR_UNIT;
10324 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10325 			} else {
10326 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10327 			}
10328 		} else
10329 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10330 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10331 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10332 		} else
10333 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10334 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10335 		bbr->rc_hit_state_1 = 1;
10336 		bbr->r_ctl.rc_exta_time_gd = 0;
10337 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10338 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10339 		if (bbr_state_drain_2_tar) {
10340 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10341 		} else
10342 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10343 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10344 	} else {
10345 		/* All other cycles hit here 2-7 */
10346 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10347 			if (bbr_sub_drain_slam_cwnd &&
10348 			    (bbr->rc_use_google == 0) &&
10349 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10350 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10351 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10352 			}
10353 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10354 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10355 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10356 			else
10357 				bbr->r_ctl.rc_exta_time_gd = 0;
10358 			if (bbr->r_ctl.rc_exta_time_gd) {
10359 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10360 				/* Now chop up the time for each state (div by 7) */
10361 				bbr->r_ctl.rc_level_state_extra /= 7;
10362 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10363 					/* Add a randomization */
10364 					bbr_randomize_extra_state_time(bbr);
10365 				}
10366 			}
10367 		}
10368 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10369 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10370 	}
10371 	if (bbr->rc_use_google) {
10372 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10373 	}
10374 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10375 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10376 	if (dolog)
10377 		bbr_log_type_statechange(bbr, cts, line);
10378 
10379 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10380 		uint32_t time_in;
10381 
10382 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10383 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10384 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10385 		} else {
10386 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10387 		}
10388 	}
10389 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10390 	bbr_set_state_target(bbr, __LINE__);
10391 	if (bbr_sub_drain_slam_cwnd &&
10392 	    (bbr->rc_use_google == 0) &&
10393 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10394 		/* Slam down the cwnd */
10395 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10396 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10397 		if (bbr_sub_drain_app_limit) {
10398 			/* Go app limited if we are on a long drain */
10399 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10400 							  ctf_flight_size(bbr->rc_tp,
10401 							      (bbr->r_ctl.rc_sacked +
10402 							       bbr->r_ctl.rc_lost_bytes)));
10403 		}
10404 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10405 	}
10406 	if (bbr->rc_lt_use_bw) {
10407 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10408 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10409 	}
10410 	/* Google changes TSO size every cycle */
10411 	if (bbr->rc_use_google)
10412 		tcp_bbr_tso_size_check(bbr, cts);
10413 	bbr->r_ctl.gain_epoch = cts;
10414 	bbr->r_ctl.rc_bbr_state_time = cts;
10415 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10416 }
10417 
10418 static void
10419 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10420 {
10421 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10422 	    (google_allow_early_out == 1) &&
10423 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10424 		/* We have reached out target flight size possibly early */
10425 		goto change_state;
10426 	}
10427 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10428 		return;
10429 	}
10430 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10431 		/*
10432 		 * Must be a rttProp movement forward before
10433 		 * we can change states.
10434 		 */
10435 		return;
10436 	}
10437 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10438 		/*
10439 		 * The needed time has passed but for
10440 		 * the gain cycle extra rules apply:
10441 		 * 1) If we have seen loss, we exit
10442 		 * 2) If we have not reached the target
10443 		 *    we stay in GAIN (gain-to-target).
10444 		 */
10445 		if (google_consider_lost && losses)
10446 			goto change_state;
10447 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10448 			return;
10449 		}
10450 	}
10451 change_state:
10452 	/* For gain we must reach our target, all others last 1 rttProp */
10453 	bbr_substate_change(bbr, cts, __LINE__, 1);
10454 }
10455 
10456 static void
10457 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10458 {
10459 	uint32_t flight, bbr_cur_cycle_time;
10460 
10461 	if (bbr->rc_use_google) {
10462 		bbr_set_probebw_google_gains(bbr, cts, losses);
10463 		return;
10464 	}
10465 	if (cts == 0) {
10466 		/*
10467 		 * Never alow cts to be 0 we
10468 		 * do this so we can judge if
10469 		 * we have set a timestamp.
10470 		 */
10471 		cts = 1;
10472 	}
10473 	if (bbr_state_is_pkt_epoch)
10474 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10475 	else
10476 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10477 
10478 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10479 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10480 			flight = ctf_flight_size(bbr->rc_tp,
10481 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10482 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10483 				/* Keep it slam down */
10484 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10485 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10486 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10487 				}
10488 				if (bbr_sub_drain_app_limit) {
10489 					/* Go app limited if we are on a long drain */
10490 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10491 				}
10492 			}
10493 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10494 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10495 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10496 				/*
10497 				 * Still here after the same time as
10498 				 * the gain. We need to drain harder
10499 				 * for the next srtt. Reduce by a set amount
10500 				 * the gain drop is capped at DRAIN states
10501 				 * value (88).
10502 				 */
10503 				bbr->r_ctl.flightsize_at_drain = flight;
10504 				if (bbr_drain_drop_mul &&
10505 				    bbr_drain_drop_div &&
10506 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10507 					/* Use your specific drop value (def 4/5 = 20%) */
10508 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10509 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10510 				} else {
10511 					/* You get drop of 20% */
10512 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10513 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10514 				}
10515 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10516 					/* Reduce our gain again to the bottom  */
10517 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10518 				}
10519 				bbr_log_exit_gain(bbr, cts, 4);
10520 				/*
10521 				 * Extend out so we wait another
10522 				 * epoch before dropping again.
10523 				 */
10524 				bbr->r_ctl.gain_epoch = cts;
10525 			}
10526 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10527 				if (bbr_sub_drain_slam_cwnd &&
10528 				    (bbr->rc_use_google == 0) &&
10529 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10530 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10531 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10532 				}
10533 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10534 				bbr_log_exit_gain(bbr, cts, 3);
10535 			}
10536 		} else {
10537 			/* Its a gain  */
10538 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10539 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10540 				goto change_state;
10541 			}
10542 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10543 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10544 			     bbr->rc_tp->snd_wnd)) {
10545 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10546 				bbr_log_exit_gain(bbr, cts, 2);
10547 			}
10548 		}
10549 		/**
10550 		 * We fall through and return always one of two things has
10551 		 * occurred.
10552 		 * 1) We are still not at target
10553 		 *    <or>
10554 		 * 2) We reached the target and set rc_bbr_state_atflight
10555 		 *    which means we no longer hit this block
10556 		 *    next time we are called.
10557 		 */
10558 		return;
10559 	}
10560 change_state:
10561 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10562 		return;
10563 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10564 		/* Less than a full time-period has passed */
10565 		return;
10566 	}
10567 	if (bbr->r_ctl.rc_level_state_extra &&
10568 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10569 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10570 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10571 		/* Less than a full time-period + extra has passed */
10572 		return;
10573 	}
10574 	if (bbr_gain_gets_extra_too &&
10575 	    bbr->r_ctl.rc_level_state_extra &&
10576 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10577 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10578 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10579 		/* Less than a full time-period + extra has passed */
10580 		return;
10581 	}
10582 	bbr_substate_change(bbr, cts, __LINE__, 1);
10583 }
10584 
10585 static uint32_t
10586 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10587 {
10588 	uint32_t mss, tar;
10589 
10590 	if (bbr->rc_use_google) {
10591 		/* Google just uses the cwnd target */
10592 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10593 	} else {
10594 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10595 			  bbr->r_ctl.rc_pace_max_segs);
10596 		/* Get the base cwnd with gain rounded to a mss */
10597 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10598 						      gain), mss);
10599 		/* Make sure it is within our min */
10600 		if (tar < get_min_cwnd(bbr))
10601 			return (get_min_cwnd(bbr));
10602 	}
10603 	return (tar);
10604 }
10605 
10606 static void
10607 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10608 {
10609 	uint32_t tar, meth;
10610 
10611 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10612 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10613 		/* Special case using old probe-rtt method */
10614 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10615 		meth = 1;
10616 	} else {
10617 		/* Non-probe-rtt case and reduced probe-rtt  */
10618 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10619 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10620 			/* For gain cycle we use the hptsi gain */
10621 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10622 			meth = 2;
10623 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10624 			/*
10625 			 * If configured, or for google all other states
10626 			 * get BBR_UNIT.
10627 			 */
10628 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10629 			meth = 3;
10630 		} else {
10631 			/*
10632 			 * Or we set a target based on the pacing gain
10633 			 * for non-google mode and default (non-configured).
10634 			 * Note we don't set a target goal below drain (192).
10635 			 */
10636 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10637 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10638 				meth = 4;
10639 			} else {
10640 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10641 				meth = 5;
10642 			}
10643 		}
10644 	}
10645 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10646 	bbr->r_ctl.rc_target_at_state = tar;
10647 }
10648 
10649 static void
10650 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10651 {
10652 	/* Change to probe_rtt */
10653 	uint32_t time_in;
10654 
10655 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10656 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10657 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10658 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10659 					  + bbr->r_ctl.rc_delivered);
10660 	/* Setup so we force feed the filter */
10661 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10662 		bbr->rc_prtt_set_ts = 1;
10663 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10664 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10665 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10666 	}
10667 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10668 	bbr->r_ctl.rc_rtt_shrinks = cts;
10669 	bbr->r_ctl.last_in_probertt = cts;
10670 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10671 	bbr->r_ctl.rc_bbr_state_time = cts;
10672 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10673 	/* We need to force the filter to update */
10674 
10675 	if ((bbr_sub_drain_slam_cwnd) &&
10676 	    bbr->rc_hit_state_1 &&
10677 	    (bbr->rc_use_google == 0) &&
10678 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10679 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10680 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10681 	} else
10682 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10683 	/* Update the lost */
10684 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10685 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10686 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10687 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10688 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10689 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10690 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10691 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10692 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10693 	} else {
10694 		/*
10695 		 * We bring it down slowly by using a hptsi gain that is
10696 		 * probably 75%. This will slowly float down our outstanding
10697 		 * without tampering with the cwnd.
10698 		 */
10699 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10700 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10701 		bbr_set_state_target(bbr, __LINE__);
10702 		if (bbr_prtt_slam_cwnd &&
10703 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10704 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10705 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10706 		}
10707 	}
10708 	if (ctf_flight_size(bbr->rc_tp,
10709 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10710 	    bbr->r_ctl.rc_target_at_state) {
10711 		/* We are at target */
10712 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10713 	} else {
10714 		/* We need to come down to reach target before our time begins */
10715 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10716 	}
10717 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10718 	BBR_STAT_INC(bbr_enter_probertt);
10719 	bbr_log_exit_gain(bbr, cts, 0);
10720 	bbr_log_type_statechange(bbr, cts, line);
10721 }
10722 
10723 static void
10724 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10725 {
10726 	/*
10727 	 * Sanity check on probe-rtt intervals.
10728 	 * In crazy situations where we are competing
10729 	 * against new-reno flows with huge buffers
10730 	 * our rtt-prop interval could come to dominate
10731 	 * things if we can't get through a full set
10732 	 * of cycles, we need to adjust it.
10733 	 */
10734 	if (bbr_can_adjust_probertt &&
10735 	    (bbr->rc_use_google == 0)) {
10736 		uint16_t val = 0;
10737 		uint32_t cur_rttp, fval, newval, baseval;
10738 
10739 		/* Are we to small and go into probe-rtt to often? */
10740 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10741 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10742 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10743 		if (bbr_is_ratio == 0) {
10744 			if (fval > bbr_rtt_probe_limit)
10745 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10746 			else
10747 				newval = cur_rttp;
10748 		} else {
10749 			int mul;
10750 
10751 			mul = fval / bbr_rtt_probe_limit;
10752 			newval = cur_rttp * mul;
10753 		}
10754 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10755 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10756 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10757 			val = 1;
10758 		} else {
10759 			/*
10760 			 * No adjustments were made
10761 			 * do we need to shrink it?
10762 			 */
10763 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10764 				if (cur_rttp <= bbr_rtt_probe_limit) {
10765 					/*
10766 					 * Things have calmed down lets
10767 					 * shrink all the way to default
10768 					 */
10769 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10770 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10771 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10772 					cur_rttp = bbr_rtt_probe_limit;
10773 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10774 					val = 2;
10775 				} else {
10776 					/*
10777 					 * Well does some adjustment make sense?
10778 					 */
10779 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10780 						/* We can reduce interval time some */
10781 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10782 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10783 						val = 3;
10784 					}
10785 				}
10786 			}
10787 		}
10788 		if (val)
10789 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10790 	}
10791 }
10792 
10793 static void
10794 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10795 {
10796 	/* Exit probe-rtt */
10797 
10798 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10799 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10800 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10801 	}
10802 	bbr_log_exit_gain(bbr, cts, 1);
10803 	bbr->rc_hit_state_1 = 0;
10804 	bbr->r_ctl.rc_rtt_shrinks = cts;
10805 	bbr->r_ctl.last_in_probertt = cts;
10806 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10807 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10808 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10809 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10810 					  bbr->r_ctl.rc_delivered);
10811 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10812 		uint32_t time_in;
10813 
10814 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10815 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10816 	}
10817 	if (bbr->rc_filled_pipe) {
10818 		/* Switch to probe_bw */
10819 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10820 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10821 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10822 		bbr_substate_change(bbr, cts, __LINE__, 0);
10823 		bbr_log_type_statechange(bbr, cts, __LINE__);
10824 	} else {
10825 		/* Back to startup */
10826 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10827 		bbr->r_ctl.rc_bbr_state_time = cts;
10828 		/*
10829 		 * We don't want to give a complete free 3
10830 		 * measurements until we exit, so we use
10831 		 * the number of pe's we were in probe-rtt
10832 		 * to add to the startup_epoch. That way
10833 		 * we will still retain the old state.
10834 		 */
10835 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10836 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10837 		/* Make sure to use the lower pg when shifting back in */
10838 		if (bbr->r_ctl.rc_lost &&
10839 		    bbr_use_lower_gain_in_startup &&
10840 		    (bbr->rc_use_google == 0))
10841 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10842 		else
10843 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10844 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10845 		/* Probably not needed but set it anyway */
10846 		bbr_set_state_target(bbr, __LINE__);
10847 		bbr_log_type_statechange(bbr, cts, __LINE__);
10848 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10849 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10850 	}
10851 	bbr_check_probe_rtt_limits(bbr, cts);
10852 }
10853 
10854 static int32_t inline
10855 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10856 {
10857 	if ((bbr->rc_past_init_win == 1) &&
10858 	    (bbr->rc_in_persist == 0) &&
10859 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10860 		return (1);
10861 	}
10862 	if (bbr_can_force_probertt &&
10863 	    (bbr->rc_in_persist == 0) &&
10864 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10865 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10866 		return (1);
10867 	}
10868 	return (0);
10869 }
10870 
10871 static int32_t
10872 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10873 {
10874 	uint64_t btlbw, gain;
10875 	if (pkt_epoch == 0) {
10876 		/*
10877 		 * Need to be on a pkt-epoch to continue.
10878 		 */
10879 		return (0);
10880 	}
10881 	btlbw = bbr_get_full_bw(bbr);
10882 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10883 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10884 	if (btlbw >= gain) {
10885 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10886 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10887 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10888 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10889 	}
10890 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10891 		return (1);
10892 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10893 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10894 	return(0);
10895 }
10896 
10897 static int32_t inline
10898 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10899 {
10900 	/* Have we gained 25% in the last 3 packet based epoch's? */
10901 	uint64_t btlbw, gain;
10902 	int do_exit;
10903 	int delta, rtt_gain;
10904 
10905 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10906 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10907 		/*
10908 		 * This qualifies as a RTT_PROBE session since we drop the
10909 		 * data outstanding to nothing and waited more than
10910 		 * bbr_rtt_probe_time.
10911 		 */
10912 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10913 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10914 	}
10915 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10916 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10917 		return (0);
10918 	}
10919 	if (bbr->rc_use_google)
10920 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10921 
10922 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10923 	    (bbr_use_lower_gain_in_startup)) {
10924 		/* Drop to a lower gain 1.5 x since we saw loss */
10925 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10926 	}
10927 	if (pkt_epoch == 0) {
10928 		/*
10929 		 * Need to be on a pkt-epoch to continue.
10930 		 */
10931 		return (0);
10932 	}
10933 	if (bbr_rtt_gain_thresh) {
10934 		/*
10935 		 * Do we allow a flow to stay
10936 		 * in startup with no loss and no
10937 		 * gain in rtt over a set threshold?
10938 		 */
10939 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
10940 		    bbr->r_ctl.startup_last_srtt &&
10941 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
10942 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
10943 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
10944 		} else
10945 			rtt_gain = 0;
10946 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
10947 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
10948 			/* First time or new lower value */
10949 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
10950 
10951 		if ((bbr->r_ctl.rc_lost == 0) &&
10952 		    (rtt_gain < bbr_rtt_gain_thresh)) {
10953 			/*
10954 			 * No loss, and we are under
10955 			 * our gain threhold for
10956 			 * increasing RTT.
10957 			 */
10958 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10959 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
10960 			bbr_log_startup_event(bbr, cts, rtt_gain,
10961 					      delta, bbr->r_ctl.startup_last_srtt, 10);
10962 			return (0);
10963 		}
10964 	}
10965 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
10966 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
10967 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
10968 		/*
10969 		 * We only assess if we have a new measurement when
10970 		 * we have no loss and are not in recovery.
10971 		 * Drag up by one our last_startup epoch so we will hold
10972 		 * the number of non-gain we have already accumulated.
10973 		 */
10974 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10975 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
10976 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10977 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
10978 		return (0);
10979 	}
10980 	/* Case where we reduced the lost (bad retransmit) */
10981 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
10982 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10983 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
10984 	btlbw = bbr_get_full_bw(bbr);
10985 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
10986 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10987 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10988 	else
10989 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10990 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10991 	do_exit = 0;
10992 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
10993 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10994 	if (btlbw >= gain) {
10995 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10996 		/* Update the lost so we won't exit in next set of tests */
10997 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10998 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10999 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
11000 	}
11001 	if ((bbr->rc_loss_exit &&
11002 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
11003 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
11004 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
11005 		/*
11006 		 * If we had no gain,  we had loss and that loss was above
11007 		 * our threshould, the rwnd is not constrained, and we have
11008 		 * had at least 3 packet epochs exit. Note that this is
11009 		 * switched off by sysctl. Google does not do this by the
11010 		 * way.
11011 		 */
11012 		if ((ctf_flight_size(bbr->rc_tp,
11013 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11014 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11015 			do_exit = 1;
11016 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11017 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11018 		} else {
11019 			/* Just record an updated loss value */
11020 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11021 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11022 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11023 		}
11024 	} else
11025 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11026 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11027 	    do_exit) {
11028 		/* Return 1 to exit the startup state. */
11029 		return (1);
11030 	}
11031 	/* Stay in startup */
11032 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11033 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11034 	return (0);
11035 }
11036 
11037 static void
11038 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11039 {
11040 	/*
11041 	 * A tick occurred in the rtt epoch do we need to do anything?
11042 	 */
11043 #ifdef BBR_INVARIANTS
11044 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11045 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11046 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11047 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11048 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11049 		/* Debug code? */
11050 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11051 	}
11052 #endif
11053 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11054 		/* Do we exit the startup state? */
11055 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11056 			uint32_t time_in;
11057 
11058 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11059 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11060 			bbr->rc_filled_pipe = 1;
11061 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11062 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11063 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11064 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11065 			} else
11066 				time_in = 0;
11067 			if (bbr->rc_no_pacing)
11068 				bbr->rc_no_pacing = 0;
11069 			bbr->r_ctl.rc_bbr_state_time = cts;
11070 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11071 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11072 			bbr_set_state_target(bbr, __LINE__);
11073 			if ((bbr->rc_use_google == 0) &&
11074 			    bbr_slam_cwnd_in_main_drain) {
11075 				/* Here we don't have to worry about probe-rtt */
11076 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11077 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11078 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11079 			}
11080 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11081 			bbr_log_type_statechange(bbr, cts, __LINE__);
11082 			if (ctf_flight_size(bbr->rc_tp,
11083 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11084 			    bbr->r_ctl.rc_target_at_state) {
11085 				/*
11086 				 * Switch to probe_bw if we are already
11087 				 * there
11088 				 */
11089 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11090 				bbr_substate_change(bbr, cts, __LINE__, 0);
11091 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11092 				bbr_log_type_statechange(bbr, cts, __LINE__);
11093 			}
11094 		}
11095 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11096 		uint32_t inflight;
11097 		struct tcpcb *tp;
11098 
11099 		tp = bbr->rc_tp;
11100 		inflight = ctf_flight_size(tp,
11101 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11102 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11103 			/* We have reached a flight of the cwnd target */
11104 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11105 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11106 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11107 			bbr_set_state_target(bbr, __LINE__);
11108 			/*
11109 			 * Rig it so we don't do anything crazy and
11110 			 * start fresh with a new randomization.
11111 			 */
11112 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11113 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11114 			bbr_substate_change(bbr, cts, __LINE__, 1);
11115 		}
11116 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11117 		/* Has in-flight reached the bdp (or less)? */
11118 		uint32_t inflight;
11119 		struct tcpcb *tp;
11120 
11121 		tp = bbr->rc_tp;
11122 		inflight = ctf_flight_size(tp,
11123 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11124 		if ((bbr->rc_use_google == 0) &&
11125 		    bbr_slam_cwnd_in_main_drain &&
11126 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11127 			/*
11128 			 * Here we don't have to worry about probe-rtt
11129 			 * re-slam it, but keep it slammed down.
11130 			 */
11131 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11132 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11133 		}
11134 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11135 			/* We have drained */
11136 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11137 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11138 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11139 				uint32_t time_in;
11140 
11141 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11142 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11143 			}
11144 			if ((bbr->rc_use_google == 0) &&
11145 			    bbr_slam_cwnd_in_main_drain &&
11146 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11147 				/* Restore the cwnd */
11148 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11149 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11150 			}
11151 			/* Setup probe-rtt has being done now RRS-HERE */
11152 			bbr->r_ctl.rc_rtt_shrinks = cts;
11153 			bbr->r_ctl.last_in_probertt = cts;
11154 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11155 			/* Randomly pick a sub-state */
11156 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11157 			bbr_substate_change(bbr, cts, __LINE__, 0);
11158 			bbr_log_type_statechange(bbr, cts, __LINE__);
11159 		}
11160 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11161 		uint32_t flight;
11162 
11163 		flight = ctf_flight_size(bbr->rc_tp,
11164 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11165 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11166 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11167 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11168 			/*
11169 			 * We must keep cwnd at the desired MSS.
11170 			 */
11171 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11172 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11173 		} else if ((bbr_prtt_slam_cwnd) &&
11174 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11175 			/* Re-slam it */
11176 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11177 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11178 		}
11179 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11180 			/* Has outstanding reached our target? */
11181 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11182 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11183 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11184 				/* If time is exactly 0, be 1usec off */
11185 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11186 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11187 				if (bbr->rc_use_google == 0) {
11188 					/*
11189 					 * Restore any lowering that as occurred to
11190 					 * reach here
11191 					 */
11192 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11193 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11194 					else
11195 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11196 				}
11197 			}
11198 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11199 			    (bbr->rc_use_google == 0) &&
11200 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11201 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11202 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11203 				/*
11204 				 * We have doddled with our current hptsi
11205 				 * gain an srtt and have still not made it
11206 				 * to target, or we have increased our flight.
11207 				 * Lets reduce the gain by xx%
11208 				 * flooring the reduce at DRAIN (based on
11209 				 * mul/div)
11210 				 */
11211 				int red;
11212 
11213 				bbr->r_ctl.flightsize_at_drain = flight;
11214 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11215 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11216 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11217 					/* Reduce our gain again */
11218 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11219 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11220 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11221 					/* one more chance before we give up */
11222 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11223 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11224 				} else {
11225 					/* At the very bottom */
11226 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11227 				}
11228 			}
11229 		}
11230 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11231 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11232 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11233 			/* Time to exit probe RTT normally */
11234 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11235 		}
11236 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11237 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11238 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11239 			/*
11240 			 * This qualifies as a RTT_PROBE session since we
11241 			 * drop the data outstanding to nothing and waited
11242 			 * more than bbr_rtt_probe_time.
11243 			 */
11244 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11245 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11246 		}
11247 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11248 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11249 		} else {
11250 			bbr_set_probebw_gains(bbr, cts, losses);
11251 		}
11252 	}
11253 }
11254 
11255 static void
11256 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11257 {
11258 	int32_t epoch = 0;
11259 
11260 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11261 		bbr_set_epoch(bbr, cts, line);
11262 		/* At each epoch doe lt bw sampling */
11263 		epoch = 1;
11264 	}
11265 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11266 }
11267 
11268 static int
11269 bbr_do_segment_nounlock(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11270     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos, int32_t nxt_pkt,
11271     struct timeval *tv)
11272 {
11273 	struct inpcb *inp = tptoinpcb(tp);
11274 	struct socket *so = tptosocket(tp);
11275 	int32_t thflags, retval;
11276 	uint32_t cts, lcts;
11277 	uint32_t tiwin;
11278 	struct tcpopt to;
11279 	struct tcp_bbr *bbr;
11280 	struct bbr_sendmap *rsm;
11281 	struct timeval ltv;
11282 	int32_t did_out = 0;
11283 	uint16_t nsegs;
11284 	int32_t prev_state;
11285 	uint32_t lost;
11286 
11287 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11288 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11289 	/* add in our stats */
11290 	kern_prefetch(bbr, &prev_state);
11291 	prev_state = 0;
11292 	thflags = tcp_get_flags(th);
11293 	/*
11294 	 * If this is either a state-changing packet or current state isn't
11295 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11296 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11297 	 * caller may have unnecessarily acquired a write lock due to a
11298 	 * race.
11299 	 */
11300 	INP_WLOCK_ASSERT(tptoinpcb(tp));
11301 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11302 	    __func__));
11303 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11304 	    __func__));
11305 
11306 	tp->t_rcvtime = ticks;
11307 	/*
11308 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11309 	 * the scale is zero.
11310 	 */
11311 	tiwin = th->th_win << tp->snd_scale;
11312 #ifdef STATS
11313 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11314 #endif
11315 
11316 	if (m->m_flags & M_TSTMP) {
11317 		/* Prefer the hardware timestamp if present */
11318 		struct timespec ts;
11319 
11320 		mbuf_tstmp2timespec(m, &ts);
11321 		bbr->rc_tv.tv_sec = ts.tv_sec;
11322 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11323 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11324 	} else if (m->m_flags & M_TSTMP_LRO) {
11325 		/* Next the arrival timestamp */
11326 		struct timespec ts;
11327 
11328 		mbuf_tstmp2timespec(m, &ts);
11329 		bbr->rc_tv.tv_sec = ts.tv_sec;
11330 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11331 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11332 	} else {
11333 		/*
11334 		 * Ok just get the current time.
11335 		 */
11336 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11337 	}
11338 	/*
11339 	 * Parse options on any incoming segment.
11340 	 */
11341 	tcp_dooptions(&to, (u_char *)(th + 1),
11342 	    (th->th_off << 2) - sizeof(struct tcphdr),
11343 	    (thflags & TH_SYN) ? TO_SYN : 0);
11344 
11345 	/*
11346 	 * If timestamps were negotiated during SYN/ACK and a
11347 	 * segment without a timestamp is received, silently drop
11348 	 * the segment, unless it is a RST segment or missing timestamps are
11349 	 * tolerated.
11350 	 * See section 3.2 of RFC 7323.
11351 	 */
11352 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS) &&
11353 	    ((thflags & TH_RST) == 0) && (V_tcp_tolerate_missing_ts == 0)) {
11354 		retval = 0;
11355 		m_freem(m);
11356 		goto done_with_input;
11357 	}
11358 	/*
11359 	 * If echoed timestamp is later than the current time, fall back to
11360 	 * non RFC1323 RTT calculation.  Normalize timestamp if syncookies
11361 	 * were used when this connection was established.
11362 	 */
11363 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
11364 		to.to_tsecr -= tp->ts_offset;
11365 		if (TSTMP_GT(to.to_tsecr, tcp_tv_to_mssectick(&bbr->rc_tv)))
11366 			to.to_tsecr = 0;
11367 	}
11368 	/*
11369 	 * If its the first time in we need to take care of options and
11370 	 * verify we can do SACK for rack!
11371 	 */
11372 	if (bbr->r_state == 0) {
11373 		/*
11374 		 * Process options only when we get SYN/ACK back. The SYN
11375 		 * case for incoming connections is handled in tcp_syncache.
11376 		 * According to RFC1323 the window field in a SYN (i.e., a
11377 		 * <SYN> or <SYN,ACK>) segment itself is never scaled. XXX
11378 		 * this is traditional behavior, may need to be cleaned up.
11379 		 */
11380 		if (bbr->rc_inp == NULL) {
11381 			bbr->rc_inp = inp;
11382 		}
11383 		/*
11384 		 * We need to init rc_inp here since its not init'd when
11385 		 * bbr_init is called
11386 		 */
11387 		if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
11388 			if ((to.to_flags & TOF_SCALE) &&
11389 			    (tp->t_flags & TF_REQ_SCALE)) {
11390 				tp->t_flags |= TF_RCVD_SCALE;
11391 				tp->snd_scale = to.to_wscale;
11392 			} else
11393 				tp->t_flags &= ~TF_REQ_SCALE;
11394 			/*
11395 			 * Initial send window.  It will be updated with the
11396 			 * next incoming segment to the scaled value.
11397 			 */
11398 			tp->snd_wnd = th->th_win;
11399 			if ((to.to_flags & TOF_TS) &&
11400 			    (tp->t_flags & TF_REQ_TSTMP)) {
11401 				tp->t_flags |= TF_RCVD_TSTMP;
11402 				tp->ts_recent = to.to_tsval;
11403 				tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
11404 			} else
11405 			    tp->t_flags &= ~TF_REQ_TSTMP;
11406 			if (to.to_flags & TOF_MSS)
11407 				tcp_mss(tp, to.to_mss);
11408 			if ((tp->t_flags & TF_SACK_PERMIT) &&
11409 			    (to.to_flags & TOF_SACKPERM) == 0)
11410 				tp->t_flags &= ~TF_SACK_PERMIT;
11411 			if (IS_FASTOPEN(tp->t_flags)) {
11412 				if (to.to_flags & TOF_FASTOPEN) {
11413 					uint16_t mss;
11414 
11415 					if (to.to_flags & TOF_MSS)
11416 						mss = to.to_mss;
11417 					else
11418 						if ((inp->inp_vflag & INP_IPV6) != 0)
11419 							mss = TCP6_MSS;
11420 						else
11421 							mss = TCP_MSS;
11422 					tcp_fastopen_update_cache(tp, mss,
11423 					    to.to_tfo_len, to.to_tfo_cookie);
11424 				} else
11425 					tcp_fastopen_disable_path(tp);
11426 			}
11427 		}
11428 		/*
11429 		 * At this point we are at the initial call. Here we decide
11430 		 * if we are doing RACK or not. We do this by seeing if
11431 		 * TF_SACK_PERMIT is set, if not rack is *not* possible and
11432 		 * we switch to the default code.
11433 		 */
11434 		if ((tp->t_flags & TF_SACK_PERMIT) == 0) {
11435 			/* Bail */
11436 			tcp_switch_back_to_default(tp);
11437 			(*tp->t_fb->tfb_tcp_do_segment)(tp, m, th, drop_hdrlen,
11438 			    tlen, iptos);
11439 			return (1);
11440 		}
11441 		/* Set the flag */
11442 		bbr->r_is_v6 = (inp->inp_vflag & INP_IPV6) != 0;
11443 		tcp_set_hpts(tp);
11444 		sack_filter_clear(&bbr->r_ctl.bbr_sf, th->th_ack);
11445 	}
11446 	if (thflags & TH_ACK) {
11447 		/* Track ack types */
11448 		if (to.to_flags & TOF_SACK)
11449 			BBR_STAT_INC(bbr_acks_with_sacks);
11450 		else
11451 			BBR_STAT_INC(bbr_plain_acks);
11452 	}
11453 	/*
11454 	 * This is the one exception case where we set the rack state
11455 	 * always. All other times (timers etc) we must have a rack-state
11456 	 * set (so we assure we have done the checks above for SACK).
11457 	 */
11458 	if (thflags & TH_FIN)
11459 		tcp_log_end_status(tp, TCP_EI_STATUS_CLIENT_FIN);
11460 	if (bbr->r_state != tp->t_state)
11461 		bbr_set_state(tp, bbr, tiwin);
11462 
11463 	if (SEQ_GT(th->th_ack, tp->snd_una) && (rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map)) != NULL)
11464 		kern_prefetch(rsm, &prev_state);
11465 	prev_state = bbr->r_state;
11466 	bbr->rc_ack_was_delayed = 0;
11467 	lost = bbr->r_ctl.rc_lost;
11468 	bbr->rc_is_pkt_epoch_now = 0;
11469 	if (m->m_flags & (M_TSTMP|M_TSTMP_LRO)) {
11470 		/* Get the real time into lcts and figure the real delay */
11471 		lcts = tcp_get_usecs(&ltv);
11472 		if (TSTMP_GT(lcts, cts)) {
11473 			bbr->r_ctl.rc_ack_hdwr_delay = lcts - cts;
11474 			bbr->rc_ack_was_delayed = 1;
11475 			if (TSTMP_GT(bbr->r_ctl.rc_ack_hdwr_delay,
11476 				     bbr->r_ctl.highest_hdwr_delay))
11477 				bbr->r_ctl.highest_hdwr_delay = bbr->r_ctl.rc_ack_hdwr_delay;
11478 		} else {
11479 			bbr->r_ctl.rc_ack_hdwr_delay = 0;
11480 			bbr->rc_ack_was_delayed = 0;
11481 		}
11482 	} else {
11483 		bbr->r_ctl.rc_ack_hdwr_delay = 0;
11484 		bbr->rc_ack_was_delayed = 0;
11485 	}
11486 	bbr_log_ack_event(bbr, th, &to, tlen, nsegs, cts, nxt_pkt, m);
11487 	if ((thflags & TH_SYN) && (thflags & TH_FIN) && V_drop_synfin) {
11488 		retval = 0;
11489 		m_freem(m);
11490 		goto done_with_input;
11491 	}
11492 	/*
11493 	 * If a segment with the ACK-bit set arrives in the SYN-SENT state
11494 	 * check SEQ.ACK first as described on page 66 of RFC 793, section 3.9.
11495 	 */
11496 	if ((tp->t_state == TCPS_SYN_SENT) && (thflags & TH_ACK) &&
11497 	    (SEQ_LEQ(th->th_ack, tp->iss) || SEQ_GT(th->th_ack, tp->snd_max))) {
11498 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
11499 		ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
11500 		return (1);
11501 	}
11502 	if (tiwin > bbr->r_ctl.rc_high_rwnd)
11503 		bbr->r_ctl.rc_high_rwnd = tiwin;
11504 	bbr->r_ctl.rc_flight_at_input = ctf_flight_size(tp,
11505 					    (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11506 	bbr->rtt_valid = 0;
11507 	if (to.to_flags & TOF_TS) {
11508 		bbr->rc_ts_valid = 1;
11509 		bbr->r_ctl.last_inbound_ts = to.to_tsval;
11510 	} else {
11511 		bbr->rc_ts_valid = 0;
11512 		bbr->r_ctl.last_inbound_ts = 0;
11513 	}
11514 	retval = (*bbr->r_substate) (m, th, so,
11515 	    tp, &to, drop_hdrlen,
11516 	    tlen, tiwin, thflags, nxt_pkt, iptos);
11517 	if (nxt_pkt == 0)
11518 		BBR_STAT_INC(bbr_rlock_left_ret0);
11519 	else
11520 		BBR_STAT_INC(bbr_rlock_left_ret1);
11521 	if (retval == 0) {
11522 		/*
11523 		 * If retval is 1 the tcb is unlocked and most likely the tp
11524 		 * is gone.
11525 		 */
11526 		INP_WLOCK_ASSERT(inp);
11527 		tcp_bbr_xmit_timer_commit(bbr, tp, cts);
11528 		if (bbr->rc_is_pkt_epoch_now)
11529 			bbr_set_pktepoch(bbr, cts, __LINE__);
11530 		bbr_check_bbr_for_state(bbr, cts, __LINE__, (bbr->r_ctl.rc_lost - lost));
11531 		if (nxt_pkt == 0) {
11532 			if ((bbr->r_wanted_output != 0) ||
11533 			    (tp->t_flags & TF_ACKNOW)) {
11534 
11535 				bbr->rc_output_starts_timer = 0;
11536 				did_out = 1;
11537 				if (tcp_output(tp) < 0)
11538 					return (1);
11539 			} else
11540 				bbr_start_hpts_timer(bbr, tp, cts, 6, 0, 0);
11541 		}
11542 		if ((nxt_pkt == 0) &&
11543 		    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) == 0) &&
11544 		    (SEQ_GT(tp->snd_max, tp->snd_una) ||
11545 		     (tp->t_flags & TF_DELACK) ||
11546 		     ((V_tcp_always_keepalive || bbr->rc_inp->inp_socket->so_options & SO_KEEPALIVE) &&
11547 		      (tp->t_state <= TCPS_CLOSING)))) {
11548 			/*
11549 			 * We could not send (probably in the hpts but
11550 			 * stopped the timer)?
11551 			 */
11552 			if ((tp->snd_max == tp->snd_una) &&
11553 			    ((tp->t_flags & TF_DELACK) == 0) &&
11554 			    (tcp_in_hpts(tp)) &&
11555 			    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
11556 				/*
11557 				 * keep alive not needed if we are hptsi
11558 				 * output yet
11559 				 */
11560 				;
11561 			} else {
11562 				if (tcp_in_hpts(tp)) {
11563 					tcp_hpts_remove(tp);
11564 					if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11565 					    (TSTMP_GT(lcts, bbr->rc_pacer_started))) {
11566 						uint32_t del;
11567 
11568 						del = lcts - bbr->rc_pacer_started;
11569 						if (bbr->r_ctl.rc_last_delay_val > del) {
11570 							BBR_STAT_INC(bbr_force_timer_start);
11571 							bbr->r_ctl.rc_last_delay_val -= del;
11572 							bbr->rc_pacer_started = lcts;
11573 						} else {
11574 							/* We are late */
11575 							bbr->r_ctl.rc_last_delay_val = 0;
11576 							BBR_STAT_INC(bbr_force_output);
11577 							if (tcp_output(tp) < 0)
11578 								return (1);
11579 						}
11580 					}
11581 				}
11582 				bbr_start_hpts_timer(bbr, tp, cts, 8, bbr->r_ctl.rc_last_delay_val,
11583 				    0);
11584 			}
11585 		} else if ((bbr->rc_output_starts_timer == 0) && (nxt_pkt == 0)) {
11586 			/* Do we have the correct timer running? */
11587 			bbr_timer_audit(tp, bbr, lcts, &so->so_snd);
11588 		}
11589 		/* Clear the flag, it may have been cleared by output but we may not have  */
11590 		if ((nxt_pkt == 0) && (tp->t_flags2 & TF2_HPTS_CALLS))
11591 			tp->t_flags2 &= ~TF2_HPTS_CALLS;
11592 		/* Do we have a new state */
11593 		if (bbr->r_state != tp->t_state)
11594 			bbr_set_state(tp, bbr, tiwin);
11595 done_with_input:
11596 		bbr_log_doseg_done(bbr, cts, nxt_pkt, did_out);
11597 		if (did_out)
11598 			bbr->r_wanted_output = 0;
11599 	}
11600 	return (retval);
11601 }
11602 
11603 static void
11604 bbr_do_segment(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11605     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos)
11606 {
11607 	struct timeval tv;
11608 	int retval;
11609 
11610 	/* First lets see if we have old packets */
11611 	if (!STAILQ_EMPTY(&tp->t_inqueue)) {
11612 		if (ctf_do_queued_segments(tp, 1)) {
11613 			m_freem(m);
11614 			return;
11615 		}
11616 	}
11617 	if (m->m_flags & M_TSTMP_LRO) {
11618 		mbuf_tstmp2timeval(m, &tv);
11619 	} else {
11620 		/* Should not be should we kassert instead? */
11621 		tcp_get_usecs(&tv);
11622 	}
11623 	retval = bbr_do_segment_nounlock(tp, m, th, drop_hdrlen, tlen, iptos,
11624 	    0, &tv);
11625 	if (retval == 0) {
11626 		INP_WUNLOCK(tptoinpcb(tp));
11627 	}
11628 }
11629 
11630 /*
11631  * Return how much data can be sent without violating the
11632  * cwnd or rwnd.
11633  */
11634 
11635 static inline uint32_t
11636 bbr_what_can_we_send(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t sendwin,
11637     uint32_t avail, int32_t sb_offset, uint32_t cts)
11638 {
11639 	uint32_t len;
11640 
11641 	if (ctf_outstanding(tp) >= tp->snd_wnd) {
11642 		/* We never want to go over our peers rcv-window */
11643 		len = 0;
11644 	} else {
11645 		uint32_t flight;
11646 
11647 		flight = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11648 		if (flight >= sendwin) {
11649 			/*
11650 			 * We have in flight what we are allowed by cwnd (if
11651 			 * it was rwnd blocking it would have hit above out
11652 			 * >= tp->snd_wnd).
11653 			 */
11654 			return (0);
11655 		}
11656 		len = sendwin - flight;
11657 		if ((len + ctf_outstanding(tp)) > tp->snd_wnd) {
11658 			/* We would send too much (beyond the rwnd) */
11659 			len = tp->snd_wnd - ctf_outstanding(tp);
11660 		}
11661 		if ((len + sb_offset) > avail) {
11662 			/*
11663 			 * We don't have that much in the SB, how much is
11664 			 * there?
11665 			 */
11666 			len = avail - sb_offset;
11667 		}
11668 	}
11669 	return (len);
11670 }
11671 
11672 static inline void
11673 bbr_do_send_accounting(struct tcpcb *tp, struct tcp_bbr *bbr, struct bbr_sendmap *rsm, int32_t len, int32_t error)
11674 {
11675 	if (error) {
11676 		return;
11677 	}
11678 	if (rsm) {
11679 		if (rsm->r_flags & BBR_TLP) {
11680 			/*
11681 			 * TLP should not count in retran count, but in its
11682 			 * own bin
11683 			 */
11684 			KMOD_TCPSTAT_INC(tcps_tlpresends);
11685 			KMOD_TCPSTAT_ADD(tcps_tlpresend_bytes, len);
11686 		} else {
11687 			/* Retransmit */
11688 			tp->t_sndrexmitpack++;
11689 			KMOD_TCPSTAT_INC(tcps_sndrexmitpack);
11690 			KMOD_TCPSTAT_ADD(tcps_sndrexmitbyte, len);
11691 #ifdef STATS
11692 			stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RETXPB,
11693 			    len);
11694 #endif
11695 		}
11696 		/*
11697 		 * Logs in 0 - 8, 8 is all non probe_bw states 0-7 is
11698 		 * sub-state
11699 		 */
11700 		counter_u64_add(bbr_state_lost[rsm->r_bbr_state], len);
11701 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_BW) {
11702 			/* Non probe_bw log in 1, 2, or 4. */
11703 			counter_u64_add(bbr_state_resend[bbr->rc_bbr_state], len);
11704 		} else {
11705 			/*
11706 			 * Log our probe state 3, and log also 5-13 to show
11707 			 * us the recovery sub-state for the send. This
11708 			 * means that 3 == (5+6+7+8+9+10+11+12+13)
11709 			 */
11710 			counter_u64_add(bbr_state_resend[BBR_STATE_PROBE_BW], len);
11711 			counter_u64_add(bbr_state_resend[(bbr_state_val(bbr) + 5)], len);
11712 		}
11713 		/* Place in both 16's the totals of retransmitted */
11714 		counter_u64_add(bbr_state_lost[16], len);
11715 		counter_u64_add(bbr_state_resend[16], len);
11716 		/* Place in 17's the total sent */
11717 		counter_u64_add(bbr_state_resend[17], len);
11718 		counter_u64_add(bbr_state_lost[17], len);
11719 
11720 	} else {
11721 		/* New sends */
11722 		KMOD_TCPSTAT_INC(tcps_sndpack);
11723 		KMOD_TCPSTAT_ADD(tcps_sndbyte, len);
11724 		/* Place in 17's the total sent */
11725 		counter_u64_add(bbr_state_resend[17], len);
11726 		counter_u64_add(bbr_state_lost[17], len);
11727 #ifdef STATS
11728 		stats_voi_update_abs_u64(tp->t_stats, VOI_TCP_TXPB,
11729 		    len);
11730 #endif
11731 	}
11732 }
11733 
11734 static void
11735 bbr_cwnd_limiting(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t in_level)
11736 {
11737 	if (bbr->rc_filled_pipe && bbr_target_cwnd_mult_limit && (bbr->rc_use_google == 0)) {
11738 		/*
11739 		 * Limit the cwnd to not be above N x the target plus whats
11740 		 * is outstanding. The target is based on the current b/w
11741 		 * estimate.
11742 		 */
11743 		uint32_t target;
11744 
11745 		target = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), BBR_UNIT);
11746 		target += ctf_outstanding(tp);
11747 		target *= bbr_target_cwnd_mult_limit;
11748 		if (tp->snd_cwnd > target)
11749 			tp->snd_cwnd = target;
11750 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 10, 0, 0, __LINE__);
11751 	}
11752 }
11753 
11754 static int
11755 bbr_window_update_needed(struct tcpcb *tp, struct socket *so, uint32_t recwin, int32_t maxseg)
11756 {
11757 	/*
11758 	 * "adv" is the amount we could increase the window, taking into
11759 	 * account that we are limited by TCP_MAXWIN << tp->rcv_scale.
11760 	 */
11761 	int32_t adv;
11762 	int32_t oldwin;
11763 
11764 	adv = recwin;
11765 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
11766 		oldwin = (tp->rcv_adv - tp->rcv_nxt);
11767 		if (adv > oldwin)
11768 			adv -= oldwin;
11769 		else {
11770 			/* We can't increase the window */
11771 			adv = 0;
11772 		}
11773 	} else
11774 		oldwin = 0;
11775 
11776 	/*
11777 	 * If the new window size ends up being the same as or less
11778 	 * than the old size when it is scaled, then don't force
11779 	 * a window update.
11780 	 */
11781 	if (oldwin >> tp->rcv_scale >= (adv + oldwin) >> tp->rcv_scale)
11782 		return (0);
11783 
11784 	if (adv >= (2 * maxseg) &&
11785 	    (adv >= (so->so_rcv.sb_hiwat / 4) ||
11786 	    recwin <= (so->so_rcv.sb_hiwat / 8) ||
11787 	    so->so_rcv.sb_hiwat <= 8 * maxseg)) {
11788 		return (1);
11789 	}
11790 	if (2 * adv >= (int32_t) so->so_rcv.sb_hiwat)
11791 		return (1);
11792 	return (0);
11793 }
11794 
11795 /*
11796  * Return 0 on success and a errno on failure to send.
11797  * Note that a 0 return may not mean we sent anything
11798  * if the TCB was on the hpts. A non-zero return
11799  * does indicate the error we got from ip[6]_output.
11800  */
11801 static int
11802 bbr_output_wtime(struct tcpcb *tp, const struct timeval *tv)
11803 {
11804 	struct socket *so;
11805 	int32_t len;
11806 	uint32_t cts;
11807 	uint32_t recwin, sendwin;
11808 	int32_t sb_offset;
11809 	int32_t flags, abandon, error = 0;
11810 	struct tcp_log_buffer *lgb = NULL;
11811 	struct mbuf *m;
11812 	struct mbuf *mb;
11813 	uint32_t if_hw_tsomaxsegcount = 0;
11814 	uint32_t if_hw_tsomaxsegsize = 0;
11815 	uint32_t if_hw_tsomax = 0;
11816 	struct ip *ip = NULL;
11817 	struct tcp_bbr *bbr;
11818 	struct tcphdr *th;
11819 	struct udphdr *udp = NULL;
11820 	u_char opt[TCP_MAXOLEN];
11821 	unsigned ipoptlen, optlen, hdrlen;
11822 	unsigned ulen;
11823 	uint32_t bbr_seq;
11824 	uint32_t delay_calc=0;
11825 	uint8_t doing_tlp = 0;
11826 	uint8_t local_options;
11827 #ifdef BBR_INVARIANTS
11828 	uint8_t doing_retran_from = 0;
11829 	uint8_t picked_up_retran = 0;
11830 #endif
11831 	uint8_t wanted_cookie = 0;
11832 	uint8_t more_to_rxt=0;
11833 	int32_t prefetch_so_done = 0;
11834 	int32_t prefetch_rsm = 0;
11835 	uint32_t tot_len = 0;
11836 	uint32_t maxseg, pace_max_segs, p_maxseg;
11837 	int32_t csum_flags = 0;
11838  	int32_t hw_tls;
11839 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
11840 	unsigned ipsec_optlen = 0;
11841 
11842 #endif
11843 	volatile int32_t sack_rxmit;
11844 	struct bbr_sendmap *rsm = NULL;
11845 	int32_t tso, mtu;
11846 	struct tcpopt to;
11847 	int32_t slot = 0;
11848 	struct inpcb *inp;
11849 	struct sockbuf *sb;
11850 	bool hpts_calling;
11851 #ifdef INET6
11852 	struct ip6_hdr *ip6 = NULL;
11853 	int32_t isipv6;
11854 #endif
11855 	uint8_t app_limited = BBR_JR_SENT_DATA;
11856 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11857 	/* We take a cache hit here */
11858 	memcpy(&bbr->rc_tv, tv, sizeof(struct timeval));
11859 	cts = tcp_tv_to_usectick(&bbr->rc_tv);
11860 	inp = bbr->rc_inp;
11861 	hpts_calling = !!(tp->t_flags2 & TF2_HPTS_CALLS);
11862 	tp->t_flags2 &= ~TF2_HPTS_CALLS;
11863 	so = inp->inp_socket;
11864 	sb = &so->so_snd;
11865 	if (tp->t_nic_ktls_xmit)
11866  		hw_tls = 1;
11867  	else
11868  		hw_tls = 0;
11869 	kern_prefetch(sb, &maxseg);
11870 	maxseg = tp->t_maxseg - bbr->rc_last_options;
11871 	if (bbr_minseg(bbr) < maxseg) {
11872 		tcp_bbr_tso_size_check(bbr, cts);
11873 	}
11874 	/* Remove any flags that indicate we are pacing on the inp  */
11875 	pace_max_segs = bbr->r_ctl.rc_pace_max_segs;
11876 	p_maxseg = min(maxseg, pace_max_segs);
11877 	INP_WLOCK_ASSERT(inp);
11878 #ifdef TCP_OFFLOAD
11879 	if (tp->t_flags & TF_TOE)
11880 		return (tcp_offload_output(tp));
11881 #endif
11882 
11883 #ifdef INET6
11884 	if (bbr->r_state) {
11885 		/* Use the cache line loaded if possible */
11886 		isipv6 = bbr->r_is_v6;
11887 	} else {
11888 		isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
11889 	}
11890 #endif
11891 	if (((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) &&
11892 	    tcp_in_hpts(tp)) {
11893 		/*
11894 		 * We are on the hpts for some timer but not hptsi output.
11895 		 * Possibly remove from the hpts so we can send/recv etc.
11896 		 */
11897 		if ((tp->t_flags & TF_ACKNOW) == 0) {
11898 			/*
11899 			 * No immediate demand right now to send an ack, but
11900 			 * the user may have read, making room for new data
11901 			 * (a window update). If so we may want to cancel
11902 			 * whatever timer is running (KEEP/DEL-ACK?) and
11903 			 * continue to send out a window update. Or we may
11904 			 * have gotten more data into the socket buffer to
11905 			 * send.
11906 			 */
11907 			recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
11908 				      (long)TCP_MAXWIN << tp->rcv_scale);
11909 			if ((bbr_window_update_needed(tp, so, recwin, maxseg) == 0) &&
11910 			    ((tcp_outflags[tp->t_state] & TH_RST) == 0) &&
11911 			    ((sbavail(sb) + ((tcp_outflags[tp->t_state] & TH_FIN) ? 1 : 0)) <=
11912 			    (tp->snd_max - tp->snd_una))) {
11913 				/*
11914 				 * Nothing new to send and no window update
11915 				 * is needed to send. Lets just return and
11916 				 * let the timer-run off.
11917 				 */
11918 				return (0);
11919 			}
11920 		}
11921 		tcp_hpts_remove(tp);
11922 		bbr_timer_cancel(bbr, __LINE__, cts);
11923 	}
11924 	if (bbr->r_ctl.rc_last_delay_val) {
11925 		/* Calculate a rough delay for early escape to sending  */
11926 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11927 			delay_calc = cts - bbr->rc_pacer_started;
11928 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11929 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11930 		else
11931 			delay_calc = 0;
11932 	}
11933 	/* Mark that we have called bbr_output(). */
11934 	if ((bbr->r_timer_override) ||
11935 	    (tp->t_state < TCPS_ESTABLISHED)) {
11936 		/* Timeouts or early states are exempt */
11937 		if (tcp_in_hpts(tp))
11938 			tcp_hpts_remove(tp);
11939 	} else if (tcp_in_hpts(tp)) {
11940 		if ((bbr->r_ctl.rc_last_delay_val) &&
11941 		    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) &&
11942 		    delay_calc) {
11943 			/*
11944 			 * We were being paced for output and the delay has
11945 			 * already exceeded when we were supposed to be
11946 			 * called, lets go ahead and pull out of the hpts
11947 			 * and call output.
11948 			 */
11949 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_LATE], 1);
11950 			bbr->r_ctl.rc_last_delay_val = 0;
11951 			tcp_hpts_remove(tp);
11952 		} else if (tp->t_state == TCPS_CLOSED) {
11953 			bbr->r_ctl.rc_last_delay_val = 0;
11954 			tcp_hpts_remove(tp);
11955 		} else {
11956 			/*
11957 			 * On the hpts, you shall not pass! even if ACKNOW
11958 			 * is on, we will when the hpts fires, unless of
11959 			 * course we are overdue.
11960 			 */
11961 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_INPACE], 1);
11962 			return (0);
11963 		}
11964 	}
11965 	bbr->rc_cwnd_limited = 0;
11966 	if (bbr->r_ctl.rc_last_delay_val) {
11967 		/* recalculate the real delay and deal with over/under  */
11968 		if (SEQ_GT(cts, bbr->rc_pacer_started))
11969 			delay_calc = cts - bbr->rc_pacer_started;
11970 		else
11971 			delay_calc = 0;
11972 		if (delay_calc >= bbr->r_ctl.rc_last_delay_val)
11973 			/* Setup the delay which will be added in */
11974 			delay_calc -= bbr->r_ctl.rc_last_delay_val;
11975 		else {
11976 			/*
11977 			 * We are early setup to adjust
11978 			 * our slot time.
11979 			 */
11980 			uint64_t merged_val;
11981 
11982 			bbr->r_ctl.rc_agg_early += (bbr->r_ctl.rc_last_delay_val - delay_calc);
11983 			bbr->r_agg_early_set = 1;
11984 			if (bbr->r_ctl.rc_hptsi_agg_delay) {
11985 				if (bbr->r_ctl.rc_hptsi_agg_delay >= bbr->r_ctl.rc_agg_early) {
11986 					/* Nope our previous late cancels out the early */
11987 					bbr->r_ctl.rc_hptsi_agg_delay -= bbr->r_ctl.rc_agg_early;
11988 					bbr->r_agg_early_set = 0;
11989 					bbr->r_ctl.rc_agg_early = 0;
11990 				} else {
11991 					bbr->r_ctl.rc_agg_early -= bbr->r_ctl.rc_hptsi_agg_delay;
11992 					bbr->r_ctl.rc_hptsi_agg_delay = 0;
11993 				}
11994 			}
11995 			merged_val = bbr->rc_pacer_started;
11996 			merged_val <<= 32;
11997 			merged_val |= bbr->r_ctl.rc_last_delay_val;
11998 			bbr_log_pacing_delay_calc(bbr, hpts_calling,
11999 						 bbr->r_ctl.rc_agg_early, cts, delay_calc, merged_val,
12000 						 bbr->r_agg_early_set, 3);
12001 			bbr->r_ctl.rc_last_delay_val = 0;
12002 			BBR_STAT_INC(bbr_early);
12003 			delay_calc = 0;
12004 		}
12005 	} else {
12006 		/* We were not delayed due to hptsi */
12007 		if (bbr->r_agg_early_set)
12008 			bbr->r_ctl.rc_agg_early = 0;
12009 		bbr->r_agg_early_set = 0;
12010 		delay_calc = 0;
12011 	}
12012 	if (delay_calc) {
12013 		/*
12014 		 * We had a hptsi delay which means we are falling behind on
12015 		 * sending at the expected rate. Calculate an extra amount
12016 		 * of data we can send, if any, to put us back on track.
12017 		 */
12018 		if ((bbr->r_ctl.rc_hptsi_agg_delay + delay_calc) < bbr->r_ctl.rc_hptsi_agg_delay)
12019 			bbr->r_ctl.rc_hptsi_agg_delay = 0xffffffff;
12020 		else
12021 			bbr->r_ctl.rc_hptsi_agg_delay += delay_calc;
12022 	}
12023 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12024 	if ((tp->snd_una == tp->snd_max) &&
12025 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
12026 	    (sbavail(sb))) {
12027 		/*
12028 		 * Ok we have been idle with nothing outstanding
12029 		 * we possibly need to start fresh with either a new
12030 		 * suite of states or a fast-ramp up.
12031 		 */
12032 		bbr_restart_after_idle(bbr,
12033 				       cts, bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time));
12034 	}
12035 	/*
12036 	 * Now was there a hptsi delay where we are behind? We only count
12037 	 * being behind if: a) We are not in recovery. b) There was a delay.
12038 	 * <and> c) We had room to send something.
12039 	 *
12040 	 */
12041 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
12042 		int retval;
12043 
12044 		retval = bbr_process_timers(tp, bbr, cts, hpts_calling);
12045 		if (retval != 0) {
12046 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_ATIMER], 1);
12047 			/*
12048 			 * If timers want tcp_drop(), then pass error out,
12049 			 * otherwise suppress it.
12050 			 */
12051 			return (retval < 0 ? retval : 0);
12052 		}
12053 	}
12054 	bbr->rc_tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
12055 	if (hpts_calling &&
12056 	    (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)) {
12057 		bbr->r_ctl.rc_last_delay_val = 0;
12058 	}
12059 	bbr->r_timer_override = 0;
12060 	bbr->r_wanted_output = 0;
12061 	/*
12062 	 * For TFO connections in SYN_RECEIVED, only allow the initial
12063 	 * SYN|ACK and those sent by the retransmit timer.
12064 	 */
12065 	if (IS_FASTOPEN(tp->t_flags) &&
12066 	    ((tp->t_state == TCPS_SYN_RECEIVED) ||
12067 	     (tp->t_state == TCPS_SYN_SENT)) &&
12068 	    SEQ_GT(tp->snd_max, tp->snd_una) &&	/* initial SYN or SYN|ACK sent */
12069 	    (tp->t_rxtshift == 0)) {	/* not a retransmit */
12070 		len = 0;
12071 		goto just_return_nolock;
12072 	}
12073 	/*
12074 	 * Before sending anything check for a state update. For hpts
12075 	 * calling without input this is important. If its input calling
12076 	 * then this was already done.
12077 	 */
12078 	if (bbr->rc_use_google == 0)
12079 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12080 again:
12081 	/*
12082 	 * If we've recently taken a timeout, snd_max will be greater than
12083 	 * snd_max. BBR in general does not pay much attention to snd_nxt
12084 	 * for historic reasons the persist timer still uses it. This means
12085 	 * we have to look at it. All retransmissions that are not persits
12086 	 * use the rsm that needs to be sent so snd_nxt is ignored. At the
12087 	 * end of this routine we pull snd_nxt always up to snd_max.
12088 	 */
12089 	doing_tlp = 0;
12090 #ifdef BBR_INVARIANTS
12091 	doing_retran_from = picked_up_retran = 0;
12092 #endif
12093 	error = 0;
12094 	tso = 0;
12095 	slot = 0;
12096 	mtu = 0;
12097 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
12098 	sb_offset = tp->snd_max - tp->snd_una;
12099 	flags = tcp_outflags[tp->t_state];
12100 	sack_rxmit = 0;
12101 	len = 0;
12102 	rsm = NULL;
12103 	if (flags & TH_RST) {
12104 		SOCKBUF_LOCK(sb);
12105 		goto send;
12106 	}
12107 recheck_resend:
12108 	while (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
12109 		/* We need to always have one in reserve */
12110 		rsm = bbr_alloc(bbr);
12111 		if (rsm == NULL) {
12112 			error = ENOMEM;
12113 			/* Lie to get on the hpts */
12114 			tot_len = tp->t_maxseg;
12115 			if (hpts_calling)
12116 				/* Retry in a ms */
12117 				slot = 1001;
12118 			goto just_return_nolock;
12119 		}
12120 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
12121 		bbr->r_ctl.rc_free_cnt++;
12122 		rsm = NULL;
12123 	}
12124 	/* What do we send, a resend? */
12125 	if (bbr->r_ctl.rc_resend == NULL) {
12126 		/* Check for rack timeout */
12127 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
12128 		if (bbr->r_ctl.rc_resend) {
12129 #ifdef BBR_INVARIANTS
12130 			picked_up_retran = 1;
12131 #endif
12132 			bbr_cong_signal(tp, NULL, CC_NDUPACK, bbr->r_ctl.rc_resend);
12133 		}
12134 	}
12135 	if (bbr->r_ctl.rc_resend) {
12136 		rsm = bbr->r_ctl.rc_resend;
12137 #ifdef BBR_INVARIANTS
12138 		doing_retran_from = 1;
12139 #endif
12140 		/* Remove any TLP flags its a RACK or T-O */
12141 		rsm->r_flags &= ~BBR_TLP;
12142 		bbr->r_ctl.rc_resend = NULL;
12143 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
12144 #ifdef BBR_INVARIANTS
12145 			panic("Huh, tp:%p bbr:%p rsm:%p start:%u < snd_una:%u\n",
12146 			    tp, bbr, rsm, rsm->r_start, tp->snd_una);
12147 			goto recheck_resend;
12148 #else
12149 			/* TSNH */
12150 			rsm = NULL;
12151 			goto recheck_resend;
12152 #endif
12153 		}
12154 		if (rsm->r_flags & BBR_HAS_SYN) {
12155 			/* Only retransmit a SYN by itself */
12156 			len = 0;
12157 			if ((flags & TH_SYN) == 0) {
12158 				/* Huh something is wrong */
12159 				rsm->r_start++;
12160 				if (rsm->r_start == rsm->r_end) {
12161 					/* Clean it up, somehow we missed the ack? */
12162 					bbr_log_syn(tp, NULL);
12163 				} else {
12164 					/* TFO with data? */
12165 					rsm->r_flags &= ~BBR_HAS_SYN;
12166 					len = rsm->r_end - rsm->r_start;
12167 				}
12168 			} else {
12169 				/* Retransmitting SYN */
12170 				rsm = NULL;
12171 				SOCKBUF_LOCK(sb);
12172 				goto send;
12173 			}
12174 		} else
12175 			len = rsm->r_end - rsm->r_start;
12176 		if ((bbr->rc_resends_use_tso == 0) &&
12177 		    (len > maxseg)) {
12178 			len = maxseg;
12179 			more_to_rxt = 1;
12180 		}
12181 		sb_offset = rsm->r_start - tp->snd_una;
12182 		if (len > 0) {
12183 			sack_rxmit = 1;
12184 			KMOD_TCPSTAT_INC(tcps_sack_rexmits);
12185 			KMOD_TCPSTAT_ADD(tcps_sack_rexmit_bytes,
12186 			    min(len, maxseg));
12187 		} else {
12188 			/* I dont think this can happen */
12189 			rsm = NULL;
12190 			goto recheck_resend;
12191 		}
12192 		BBR_STAT_INC(bbr_resends_set);
12193 	} else if (bbr->r_ctl.rc_tlp_send) {
12194 		/*
12195 		 * Tail loss probe
12196 		 */
12197 		doing_tlp = 1;
12198 		rsm = bbr->r_ctl.rc_tlp_send;
12199 		bbr->r_ctl.rc_tlp_send = NULL;
12200 		sack_rxmit = 1;
12201 		len = rsm->r_end - rsm->r_start;
12202 		if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12203 			len = maxseg;
12204 
12205 		if (SEQ_GT(tp->snd_una, rsm->r_start)) {
12206 #ifdef BBR_INVARIANTS
12207 			panic("tp:%p bbc:%p snd_una:%u rsm:%p r_start:%u",
12208 			    tp, bbr, tp->snd_una, rsm, rsm->r_start);
12209 #else
12210 			/* TSNH */
12211 			rsm = NULL;
12212 			goto recheck_resend;
12213 #endif
12214 		}
12215 		sb_offset = rsm->r_start - tp->snd_una;
12216 		BBR_STAT_INC(bbr_tlp_set);
12217 	}
12218 	/*
12219 	 * Enforce a connection sendmap count limit if set
12220 	 * as long as we are not retransmiting.
12221 	 */
12222 	if ((rsm == NULL) &&
12223 	    (V_tcp_map_entries_limit > 0) &&
12224 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
12225 		BBR_STAT_INC(bbr_alloc_limited);
12226 		if (!bbr->alloc_limit_reported) {
12227 			bbr->alloc_limit_reported = 1;
12228 			BBR_STAT_INC(bbr_alloc_limited_conns);
12229 		}
12230 		goto just_return_nolock;
12231 	}
12232 #ifdef BBR_INVARIANTS
12233 	if (rsm && SEQ_LT(rsm->r_start, tp->snd_una)) {
12234 		panic("tp:%p bbr:%p rsm:%p sb_offset:%u len:%u",
12235 		    tp, bbr, rsm, sb_offset, len);
12236 	}
12237 #endif
12238 	/*
12239 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
12240 	 * state flags.
12241 	 */
12242 	if (tp->t_flags & TF_NEEDFIN && (rsm == NULL))
12243 		flags |= TH_FIN;
12244 	if (tp->t_flags & TF_NEEDSYN)
12245 		flags |= TH_SYN;
12246 
12247 	if (rsm && (rsm->r_flags & BBR_HAS_FIN)) {
12248 		/* we are retransmitting the fin */
12249 		len--;
12250 		if (len) {
12251 			/*
12252 			 * When retransmitting data do *not* include the
12253 			 * FIN. This could happen from a TLP probe if we
12254 			 * allowed data with a FIN.
12255 			 */
12256 			flags &= ~TH_FIN;
12257 		}
12258 	} else if (rsm) {
12259 		if (flags & TH_FIN)
12260 			flags &= ~TH_FIN;
12261 	}
12262 	if ((sack_rxmit == 0) && (prefetch_rsm == 0)) {
12263 		void *end_rsm;
12264 
12265 		end_rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
12266 		if (end_rsm)
12267 			kern_prefetch(end_rsm, &prefetch_rsm);
12268 		prefetch_rsm = 1;
12269 	}
12270 	SOCKBUF_LOCK(sb);
12271 	/*
12272 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
12273 	 * sb_offset will be > 0 even if so_snd.sb_cc is 0, resulting in a
12274 	 * negative length.  This can also occur when TCP opens up its
12275 	 * congestion window while receiving additional duplicate acks after
12276 	 * fast-retransmit because TCP will reset snd_nxt to snd_max after
12277 	 * the fast-retransmit.
12278 	 *
12279 	 * In the normal retransmit-FIN-only case, however, snd_nxt will be
12280 	 * set to snd_una, the sb_offset will be 0, and the length may wind
12281 	 * up 0.
12282 	 *
12283 	 * If sack_rxmit is true we are retransmitting from the scoreboard
12284 	 * in which case len is already set.
12285 	 */
12286 	if (sack_rxmit == 0) {
12287 		uint32_t avail;
12288 
12289 		avail = sbavail(sb);
12290 		if (SEQ_GT(tp->snd_max, tp->snd_una))
12291 			sb_offset = tp->snd_max - tp->snd_una;
12292 		else
12293 			sb_offset = 0;
12294 		if (bbr->rc_tlp_new_data) {
12295 			/* TLP is forcing out new data */
12296 			uint32_t tlplen;
12297 
12298 			doing_tlp = 1;
12299 			tlplen = maxseg;
12300 
12301 			if (tlplen > (uint32_t)(avail - sb_offset)) {
12302 				tlplen = (uint32_t)(avail - sb_offset);
12303 			}
12304 			if (tlplen > tp->snd_wnd) {
12305 				len = tp->snd_wnd;
12306 			} else {
12307 				len = tlplen;
12308 			}
12309 			bbr->rc_tlp_new_data = 0;
12310 		} else {
12311 			len = bbr_what_can_we_send(tp, bbr, sendwin, avail, sb_offset, cts);
12312 			if ((len < p_maxseg) &&
12313 			    (bbr->rc_in_persist == 0) &&
12314 			    (ctf_outstanding(tp) >= (2 * p_maxseg)) &&
12315 			    ((avail - sb_offset) >= p_maxseg)) {
12316 				/*
12317 				 * We are not completing whats in the socket
12318 				 * buffer (i.e. there is at least a segment
12319 				 * waiting to send) and we have 2 or more
12320 				 * segments outstanding. There is no sense
12321 				 * of sending a little piece. Lets defer and
12322 				 * and wait until we can send a whole
12323 				 * segment.
12324 				 */
12325 				len = 0;
12326 			}
12327 			if (bbr->rc_in_persist) {
12328 				/*
12329 				 * We are in persists, figure out if
12330 				 * a retransmit is available (maybe the previous
12331 				 * persists we sent) or if we have to send new
12332 				 * data.
12333 				 */
12334 				rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
12335 				if (rsm) {
12336 					len = rsm->r_end - rsm->r_start;
12337 					if (rsm->r_flags & BBR_HAS_FIN)
12338 						len--;
12339 					if ((bbr->rc_resends_use_tso == 0) && (len > maxseg))
12340 						len = maxseg;
12341 					if (len > 1)
12342 						BBR_STAT_INC(bbr_persist_reneg);
12343 					/*
12344 					 * XXXrrs we could force the len to
12345 					 * 1 byte here to cause the chunk to
12346 					 * split apart.. but that would then
12347 					 * mean we always retransmit it as
12348 					 * one byte even after the window
12349 					 * opens.
12350 					 */
12351 					sack_rxmit = 1;
12352 					sb_offset = rsm->r_start - tp->snd_una;
12353 				} else {
12354 					/*
12355 					 * First time through in persists or peer
12356 					 * acked our one byte. Though we do have
12357 					 * to have something in the sb.
12358 					 */
12359 					len = 1;
12360 					sb_offset = 0;
12361 					if (avail == 0)
12362 					    len = 0;
12363 				}
12364 			}
12365 		}
12366 	}
12367 	if (prefetch_so_done == 0) {
12368 		kern_prefetch(so, &prefetch_so_done);
12369 		prefetch_so_done = 1;
12370 	}
12371 	/*
12372 	 * Lop off SYN bit if it has already been sent.  However, if this is
12373 	 * SYN-SENT state and if segment contains data and if we don't know
12374 	 * that foreign host supports TAO, suppress sending segment.
12375 	 */
12376 	if ((flags & TH_SYN) && (rsm == NULL) &&
12377 	    SEQ_GT(tp->snd_max, tp->snd_una)) {
12378 		if (tp->t_state != TCPS_SYN_RECEIVED)
12379 			flags &= ~TH_SYN;
12380 		/*
12381 		 * When sending additional segments following a TFO SYN|ACK,
12382 		 * do not include the SYN bit.
12383 		 */
12384 		if (IS_FASTOPEN(tp->t_flags) &&
12385 		    (tp->t_state == TCPS_SYN_RECEIVED))
12386 			flags &= ~TH_SYN;
12387 		sb_offset--, len++;
12388 		if (sbavail(sb) == 0)
12389 			len = 0;
12390 	} else if ((flags & TH_SYN) && rsm) {
12391 		/*
12392 		 * Subtract one from the len for the SYN being
12393 		 * retransmitted.
12394 		 */
12395 		len--;
12396 	}
12397 	/*
12398 	 * Be careful not to send data and/or FIN on SYN segments. This
12399 	 * measure is needed to prevent interoperability problems with not
12400 	 * fully conformant TCP implementations.
12401 	 */
12402 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
12403 		len = 0;
12404 		flags &= ~TH_FIN;
12405 	}
12406 	/*
12407 	 * On TFO sockets, ensure no data is sent in the following cases:
12408 	 *
12409 	 *  - When retransmitting SYN|ACK on a passively-created socket
12410 	 *  - When retransmitting SYN on an actively created socket
12411 	 *  - When sending a zero-length cookie (cookie request) on an
12412 	 *    actively created socket
12413 	 *  - When the socket is in the CLOSED state (RST is being sent)
12414 	 */
12415 	if (IS_FASTOPEN(tp->t_flags) &&
12416 	    (((flags & TH_SYN) && (tp->t_rxtshift > 0)) ||
12417 	     ((tp->t_state == TCPS_SYN_SENT) &&
12418 	      (tp->t_tfo_client_cookie_len == 0)) ||
12419 	     (flags & TH_RST))) {
12420 		len = 0;
12421 		sack_rxmit = 0;
12422 		rsm = NULL;
12423 	}
12424 	/* Without fast-open there should never be data sent on a SYN */
12425 	if ((flags & TH_SYN) && (!IS_FASTOPEN(tp->t_flags)))
12426 		len = 0;
12427 	if (len <= 0) {
12428 		/*
12429 		 * If FIN has been sent but not acked, but we haven't been
12430 		 * called to retransmit, len will be < 0.  Otherwise, window
12431 		 * shrank after we sent into it.  If window shrank to 0,
12432 		 * cancel pending retransmit, pull snd_nxt back to (closed)
12433 		 * window, and set the persist timer if it isn't already
12434 		 * going.  If the window didn't close completely, just wait
12435 		 * for an ACK.
12436 		 *
12437 		 * We also do a general check here to ensure that we will
12438 		 * set the persist timer when we have data to send, but a
12439 		 * 0-byte window. This makes sure the persist timer is set
12440 		 * even if the packet hits one of the "goto send" lines
12441 		 * below.
12442 		 */
12443 		len = 0;
12444 		if ((tp->snd_wnd == 0) &&
12445 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12446 		    (tp->snd_una == tp->snd_max) &&
12447 		    (sb_offset < (int)sbavail(sb))) {
12448 			/*
12449 			 * Not enough room in the rwnd to send
12450 			 * a paced segment out.
12451 			 */
12452 			bbr_enter_persist(tp, bbr, cts, __LINE__);
12453 		}
12454 	} else if ((rsm == NULL) &&
12455 		   (doing_tlp == 0) &&
12456 		   (len < bbr->r_ctl.rc_pace_max_segs)) {
12457 		/*
12458 		 * We are not sending a full segment for
12459 		 * some reason. Should we not send anything (think
12460 		 * sws or persists)?
12461 		 */
12462 		if ((tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12463 		    (TCPS_HAVEESTABLISHED(tp->t_state)) &&
12464 		    (len < (int)(sbavail(sb) - sb_offset))) {
12465 			/*
12466 			 * Here the rwnd is less than
12467 			 * the pacing size, this is not a retransmit,
12468 			 * we are established and
12469 			 * the send is not the last in the socket buffer
12470 			 * lets not send, and possibly enter persists.
12471 			 */
12472 			len = 0;
12473 			if (tp->snd_max == tp->snd_una)
12474 				bbr_enter_persist(tp, bbr, cts, __LINE__);
12475 		} else if ((tp->snd_cwnd >= bbr->r_ctl.rc_pace_max_segs) &&
12476 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12477 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12478 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12479 			   (len < bbr_minseg(bbr))) {
12480 			/*
12481 			 * Here we are not retransmitting, and
12482 			 * the cwnd is not so small that we could
12483 			 * not send at least a min size (rxt timer
12484 			 * not having gone off), We have 2 segments or
12485 			 * more already in flight, its not the tail end
12486 			 * of the socket buffer  and the cwnd is blocking
12487 			 * us from sending out minimum pacing segment size.
12488 			 * Lets not send anything.
12489 			 */
12490 			bbr->rc_cwnd_limited = 1;
12491 			len = 0;
12492 		} else if (((tp->snd_wnd - ctf_outstanding(tp)) <
12493 			    min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
12494 			   (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12495 						 bbr->r_ctl.rc_lost_bytes)) > (2 * maxseg)) &&
12496 			   (len < (int)(sbavail(sb) - sb_offset)) &&
12497 			   (TCPS_HAVEESTABLISHED(tp->t_state))) {
12498 			/*
12499 			 * Here we have a send window but we have
12500 			 * filled it up and we can't send another pacing segment.
12501 			 * We also have in flight more than 2 segments
12502 			 * and we are not completing the sb i.e. we allow
12503 			 * the last bytes of the sb to go out even if
12504 			 * its not a full pacing segment.
12505 			 */
12506 			len = 0;
12507 		}
12508 	}
12509 	/* len will be >= 0 after this point. */
12510 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
12511 	tcp_sndbuf_autoscale(tp, so, sendwin);
12512 	/*
12513 	 *
12514 	 */
12515 	if (bbr->rc_in_persist &&
12516 	    len &&
12517 	    (rsm == NULL) &&
12518 	    (len < min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs))) {
12519 		/*
12520 		 * We are in persist, not doing a retransmit and don't have enough space
12521 		 * yet to send a full TSO. So is it at the end of the sb
12522 		 * if so we need to send else nuke to 0 and don't send.
12523 		 */
12524 		int sbleft;
12525 		if (sbavail(sb) > sb_offset)
12526 			sbleft = sbavail(sb) - sb_offset;
12527 		else
12528 			sbleft = 0;
12529 		if (sbleft >= min((bbr->r_ctl.rc_high_rwnd/2), bbr->r_ctl.rc_pace_max_segs)) {
12530 			/* not at end of sb lets not send */
12531 			len = 0;
12532 		}
12533 	}
12534 	/*
12535 	 * Decide if we can use TCP Segmentation Offloading (if supported by
12536 	 * hardware).
12537 	 *
12538 	 * TSO may only be used if we are in a pure bulk sending state.  The
12539 	 * presence of TCP-MD5, SACK retransmits, SACK advertizements and IP
12540 	 * options prevent using TSO.  With TSO the TCP header is the same
12541 	 * (except for the sequence number) for all generated packets.  This
12542 	 * makes it impossible to transmit any options which vary per
12543 	 * generated segment or packet.
12544 	 *
12545 	 * IPv4 handling has a clear separation of ip options and ip header
12546 	 * flags while IPv6 combines both in in6p_outputopts. ip6_optlen()
12547 	 * does the right thing below to provide length of just ip options
12548 	 * and thus checking for ipoptlen is enough to decide if ip options
12549 	 * are present.
12550 	 */
12551 #ifdef INET6
12552 	if (isipv6)
12553 		ipoptlen = ip6_optlen(inp);
12554 	else
12555 #endif
12556 	if (inp->inp_options)
12557 		ipoptlen = inp->inp_options->m_len -
12558 		    offsetof(struct ipoption, ipopt_list);
12559 	else
12560 		ipoptlen = 0;
12561 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12562 	/*
12563 	 * Pre-calculate here as we save another lookup into the darknesses
12564 	 * of IPsec that way and can actually decide if TSO is ok.
12565 	 */
12566 #ifdef INET6
12567 	if (isipv6 && IPSEC_ENABLED(ipv6))
12568 		ipsec_optlen = IPSEC_HDRSIZE(ipv6, inp);
12569 #ifdef INET
12570 	else
12571 #endif
12572 #endif				/* INET6 */
12573 #ifdef INET
12574 	if (IPSEC_ENABLED(ipv4))
12575 		ipsec_optlen = IPSEC_HDRSIZE(ipv4, inp);
12576 #endif				/* INET */
12577 #endif				/* IPSEC */
12578 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12579 	ipoptlen += ipsec_optlen;
12580 #endif
12581 	if ((tp->t_flags & TF_TSO) && V_tcp_do_tso &&
12582 	    (len > maxseg) &&
12583 	    (tp->t_port == 0) &&
12584 	    ((tp->t_flags & TF_SIGNATURE) == 0) &&
12585 	    tp->rcv_numsacks == 0 &&
12586 	    ipoptlen == 0)
12587 		tso = 1;
12588 
12589 	recwin = lmin(lmax(sbspace(&so->so_rcv), 0),
12590 	    (long)TCP_MAXWIN << tp->rcv_scale);
12591 	/*
12592 	 * Sender silly window avoidance.   We transmit under the following
12593 	 * conditions when len is non-zero:
12594 	 *
12595 	 * - We have a full segment (or more with TSO) - This is the last
12596 	 * buffer in a write()/send() and we are either idle or running
12597 	 * NODELAY - we've timed out (e.g. persist timer) - we have more
12598 	 * then 1/2 the maximum send window's worth of data (receiver may be
12599 	 * limited the window size) - we need to retransmit
12600 	 */
12601 	if (rsm)
12602 		goto send;
12603 	if (len) {
12604 		if (sack_rxmit)
12605 			goto send;
12606 		if (len >= p_maxseg)
12607 			goto send;
12608 		/*
12609 		 * NOTE! on localhost connections an 'ack' from the remote
12610 		 * end may occur synchronously with the output and cause us
12611 		 * to flush a buffer queued with moretocome.  XXX
12612 		 *
12613 		 */
12614 		if (((tp->t_flags & TF_MORETOCOME) == 0) &&	/* normal case */
12615 		    ((tp->t_flags & TF_NODELAY) ||
12616 		    ((uint32_t)len + (uint32_t)sb_offset) >= sbavail(&so->so_snd)) &&
12617 		    (tp->t_flags & TF_NOPUSH) == 0) {
12618 			goto send;
12619 		}
12620 		if ((tp->snd_una == tp->snd_max) && len) {	/* Nothing outstanding */
12621 			goto send;
12622 		}
12623 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0) {
12624 			goto send;
12625 		}
12626 	}
12627 	/*
12628 	 * Sending of standalone window updates.
12629 	 *
12630 	 * Window updates are important when we close our window due to a
12631 	 * full socket buffer and are opening it again after the application
12632 	 * reads data from it.  Once the window has opened again and the
12633 	 * remote end starts to send again the ACK clock takes over and
12634 	 * provides the most current window information.
12635 	 *
12636 	 * We must avoid the silly window syndrome whereas every read from
12637 	 * the receive buffer, no matter how small, causes a window update
12638 	 * to be sent.  We also should avoid sending a flurry of window
12639 	 * updates when the socket buffer had queued a lot of data and the
12640 	 * application is doing small reads.
12641 	 *
12642 	 * Prevent a flurry of pointless window updates by only sending an
12643 	 * update when we can increase the advertized window by more than
12644 	 * 1/4th of the socket buffer capacity.  When the buffer is getting
12645 	 * full or is very small be more aggressive and send an update
12646 	 * whenever we can increase by two mss sized segments. In all other
12647 	 * situations the ACK's to new incoming data will carry further
12648 	 * window increases.
12649 	 *
12650 	 * Don't send an independent window update if a delayed ACK is
12651 	 * pending (it will get piggy-backed on it) or the remote side
12652 	 * already has done a half-close and won't send more data.  Skip
12653 	 * this if the connection is in T/TCP half-open state.
12654 	 */
12655 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
12656 	    !(tp->t_flags & TF_DELACK) &&
12657 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
12658 		/* Check to see if we should do a window update */
12659 		if (bbr_window_update_needed(tp, so, recwin, maxseg))
12660 			goto send;
12661 	}
12662 	/*
12663 	 * Send if we owe the peer an ACK, RST, SYN.  ACKNOW
12664 	 * is also a catch-all for the retransmit timer timeout case.
12665 	 */
12666 	if (tp->t_flags & TF_ACKNOW) {
12667 		goto send;
12668 	}
12669 	if (flags & TH_RST) {
12670 		/* Always send a RST if one is due */
12671 		goto send;
12672 	}
12673 	if ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0) {
12674 		goto send;
12675 	}
12676 	/*
12677 	 * If our state indicates that FIN should be sent and we have not
12678 	 * yet done so, then we need to send.
12679 	 */
12680 	if (flags & TH_FIN &&
12681 	    ((tp->t_flags & TF_SENTFIN) == 0)) {
12682 		goto send;
12683 	}
12684 	/*
12685 	 * No reason to send a segment, just return.
12686 	 */
12687 just_return:
12688 	SOCKBUF_UNLOCK(sb);
12689 just_return_nolock:
12690 	if (tot_len)
12691 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
12692 	if (bbr->rc_no_pacing)
12693 		slot = 0;
12694 	if (tot_len == 0) {
12695 		if ((ctf_outstanding(tp) + min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) >=
12696 		    tp->snd_wnd) {
12697 			BBR_STAT_INC(bbr_rwnd_limited);
12698 			app_limited = BBR_JR_RWND_LIMITED;
12699 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12700 			if ((bbr->rc_in_persist == 0) &&
12701 			    TCPS_HAVEESTABLISHED(tp->t_state) &&
12702 			    (tp->snd_max == tp->snd_una) &&
12703 			    sbavail(&so->so_snd)) {
12704 				/* No send window.. we must enter persist */
12705 				bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
12706 			}
12707 		} else if (ctf_outstanding(tp) >= sbavail(sb)) {
12708 			BBR_STAT_INC(bbr_app_limited);
12709 			app_limited = BBR_JR_APP_LIMITED;
12710 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12711 		} else if ((ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12712 						 bbr->r_ctl.rc_lost_bytes)) + p_maxseg) >= tp->snd_cwnd) {
12713 			BBR_STAT_INC(bbr_cwnd_limited);
12714  			app_limited = BBR_JR_CWND_LIMITED;
12715 			bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12716 									bbr->r_ctl.rc_lost_bytes)));
12717 			bbr->rc_cwnd_limited = 1;
12718 		} else {
12719 			BBR_STAT_INC(bbr_app_limited);
12720 			app_limited = BBR_JR_APP_LIMITED;
12721 			bbr_cwnd_limiting(tp, bbr, ctf_outstanding(tp));
12722 		}
12723 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
12724 		bbr->r_agg_early_set = 0;
12725 		bbr->r_ctl.rc_agg_early = 0;
12726 		bbr->r_ctl.rc_last_delay_val = 0;
12727 	} else if (bbr->rc_use_google == 0)
12728 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
12729 	/* Are we app limited? */
12730 	if ((app_limited == BBR_JR_APP_LIMITED) ||
12731 	    (app_limited == BBR_JR_RWND_LIMITED)) {
12732 		/**
12733 		 * We are application limited.
12734 		 */
12735 		bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
12736 								       bbr->r_ctl.rc_lost_bytes)) + bbr->r_ctl.rc_delivered);
12737 	}
12738 	if (tot_len == 0)
12739 		counter_u64_add(bbr_out_size[TCP_MSS_ACCT_JUSTRET], 1);
12740 	/* Dont update the time if we did not send */
12741 	bbr->r_ctl.rc_last_delay_val = 0;
12742 	bbr->rc_output_starts_timer = 1;
12743 	bbr_start_hpts_timer(bbr, tp, cts, 9, slot, tot_len);
12744 	bbr_log_type_just_return(bbr, cts, tot_len, hpts_calling, app_limited, p_maxseg, len);
12745 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
12746 		/* Make sure snd_nxt is drug up */
12747 		tp->snd_nxt = tp->snd_max;
12748 	}
12749 	return (error);
12750 
12751 send:
12752 	if (doing_tlp == 0) {
12753 		/*
12754 		 * Data not a TLP, and its not the rxt firing. If it is the
12755 		 * rxt firing, we want to leave the tlp_in_progress flag on
12756 		 * so we don't send another TLP. It has to be a rack timer
12757 		 * or normal send (response to acked data) to clear the tlp
12758 		 * in progress flag.
12759 		 */
12760 		bbr->rc_tlp_in_progress = 0;
12761 		bbr->rc_tlp_rtx_out = 0;
12762 	} else {
12763 		/*
12764 		 * Its a TLP.
12765 		 */
12766 		bbr->rc_tlp_in_progress = 1;
12767 	}
12768 	bbr_timer_cancel(bbr, __LINE__, cts);
12769 	if (rsm == NULL) {
12770 		if (sbused(sb) > 0) {
12771 			/*
12772 			 * This is sub-optimal. We only send a stand alone
12773 			 * FIN on its own segment.
12774 			 */
12775 			if (flags & TH_FIN) {
12776 				flags &= ~TH_FIN;
12777 				if ((len == 0) && ((tp->t_flags & TF_ACKNOW) == 0)) {
12778 					/* Lets not send this */
12779 					slot = 0;
12780 					goto just_return;
12781 				}
12782 			}
12783 		}
12784 	} else {
12785 		/*
12786 		 * We do *not* send a FIN on a retransmit if it has data.
12787 		 * The if clause here where len > 1 should never come true.
12788 		 */
12789 		if ((len > 0) &&
12790 		    (((rsm->r_flags & BBR_HAS_FIN) == 0) &&
12791 		    (flags & TH_FIN))) {
12792 			flags &= ~TH_FIN;
12793 			len--;
12794 		}
12795 	}
12796 	SOCKBUF_LOCK_ASSERT(sb);
12797 	if (len > 0) {
12798 		if ((tp->snd_una == tp->snd_max) &&
12799 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
12800 			/*
12801 			 * This qualifies as a RTT_PROBE session since we
12802 			 * drop the data outstanding to nothing and waited
12803 			 * more than bbr_rtt_probe_time.
12804 			 */
12805 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
12806 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
12807 		}
12808 		if (len >= maxseg)
12809 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
12810 		else
12811 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
12812 	}
12813 	/*
12814 	 * Before ESTABLISHED, force sending of initial options unless TCP
12815 	 * set not to do any options. NOTE: we assume that the IP/TCP header
12816 	 * plus TCP options always fit in a single mbuf, leaving room for a
12817 	 * maximum link header, i.e. max_linkhdr + sizeof (struct tcpiphdr)
12818 	 * + optlen <= MCLBYTES
12819 	 */
12820 	optlen = 0;
12821 #ifdef INET6
12822 	if (isipv6)
12823 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
12824 	else
12825 #endif
12826 		hdrlen = sizeof(struct tcpiphdr);
12827 
12828 	/*
12829 	 * Compute options for segment. We only have to care about SYN and
12830 	 * established connection segments.  Options for SYN-ACK segments
12831 	 * are handled in TCP syncache.
12832 	 */
12833 	to.to_flags = 0;
12834 	local_options = 0;
12835 	if ((tp->t_flags & TF_NOOPT) == 0) {
12836 		/* Maximum segment size. */
12837 		if (flags & TH_SYN) {
12838 			to.to_mss = tcp_mssopt(&inp->inp_inc);
12839 			if (tp->t_port)
12840 				to.to_mss -= V_tcp_udp_tunneling_overhead;
12841 			to.to_flags |= TOF_MSS;
12842 			/*
12843 			 * On SYN or SYN|ACK transmits on TFO connections,
12844 			 * only include the TFO option if it is not a
12845 			 * retransmit, as the presence of the TFO option may
12846 			 * have caused the original SYN or SYN|ACK to have
12847 			 * been dropped by a middlebox.
12848 			 */
12849 			if (IS_FASTOPEN(tp->t_flags) &&
12850 			    (tp->t_rxtshift == 0)) {
12851 				if (tp->t_state == TCPS_SYN_RECEIVED) {
12852 					to.to_tfo_len = TCP_FASTOPEN_COOKIE_LEN;
12853 					to.to_tfo_cookie =
12854 					    (u_int8_t *)&tp->t_tfo_cookie.server;
12855 					to.to_flags |= TOF_FASTOPEN;
12856 					wanted_cookie = 1;
12857 				} else if (tp->t_state == TCPS_SYN_SENT) {
12858 					to.to_tfo_len =
12859 					    tp->t_tfo_client_cookie_len;
12860 					to.to_tfo_cookie =
12861 					    tp->t_tfo_cookie.client;
12862 					to.to_flags |= TOF_FASTOPEN;
12863 					wanted_cookie = 1;
12864 				}
12865 			}
12866 		}
12867 		/* Window scaling. */
12868 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
12869 			to.to_wscale = tp->request_r_scale;
12870 			to.to_flags |= TOF_SCALE;
12871 		}
12872 		/* Timestamps. */
12873 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
12874 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
12875 			to.to_tsval = 	tcp_tv_to_mssectick(&bbr->rc_tv) + tp->ts_offset;
12876 			to.to_tsecr = tp->ts_recent;
12877 			to.to_flags |= TOF_TS;
12878 			local_options += TCPOLEN_TIMESTAMP + 2;
12879 		}
12880 		/* Set receive buffer autosizing timestamp. */
12881 		if (tp->rfbuf_ts == 0 &&
12882 		    (so->so_rcv.sb_flags & SB_AUTOSIZE))
12883 			tp->rfbuf_ts = 	tcp_tv_to_mssectick(&bbr->rc_tv);
12884 		/* Selective ACK's. */
12885 		if (flags & TH_SYN)
12886 			to.to_flags |= TOF_SACKPERM;
12887 		else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
12888 		    tp->rcv_numsacks > 0) {
12889 			to.to_flags |= TOF_SACK;
12890 			to.to_nsacks = tp->rcv_numsacks;
12891 			to.to_sacks = (u_char *)tp->sackblks;
12892 		}
12893 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
12894 		/* TCP-MD5 (RFC2385). */
12895 		if (tp->t_flags & TF_SIGNATURE)
12896 			to.to_flags |= TOF_SIGNATURE;
12897 #endif				/* TCP_SIGNATURE */
12898 
12899 		/* Processing the options. */
12900 		hdrlen += (optlen = tcp_addoptions(&to, opt));
12901 		/*
12902 		 * If we wanted a TFO option to be added, but it was unable
12903 		 * to fit, ensure no data is sent.
12904 		 */
12905 		if (IS_FASTOPEN(tp->t_flags) && wanted_cookie &&
12906 		    !(to.to_flags & TOF_FASTOPEN))
12907 			len = 0;
12908 	}
12909 	if (tp->t_port) {
12910 		if (V_tcp_udp_tunneling_port == 0) {
12911 			/* The port was removed?? */
12912 			SOCKBUF_UNLOCK(&so->so_snd);
12913 			return (EHOSTUNREACH);
12914 		}
12915 		hdrlen += sizeof(struct udphdr);
12916 	}
12917 #ifdef INET6
12918 	if (isipv6)
12919 		ipoptlen = ip6_optlen(inp);
12920 	else
12921 #endif
12922 	if (inp->inp_options)
12923 		ipoptlen = inp->inp_options->m_len -
12924 		    offsetof(struct ipoption, ipopt_list);
12925 	else
12926 		ipoptlen = 0;
12927 	ipoptlen = 0;
12928 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
12929 	ipoptlen += ipsec_optlen;
12930 #endif
12931 	if (bbr->rc_last_options != local_options) {
12932 		/*
12933 		 * Cache the options length this generally does not change
12934 		 * on a connection. We use this to calculate TSO.
12935 		 */
12936 		bbr->rc_last_options = local_options;
12937 	}
12938 	maxseg = tp->t_maxseg - (ipoptlen + optlen);
12939 	p_maxseg = min(maxseg, pace_max_segs);
12940 	/*
12941 	 * Adjust data length if insertion of options will bump the packet
12942 	 * length beyond the t_maxseg length. Clear the FIN bit because we
12943 	 * cut off the tail of the segment.
12944 	 */
12945 	if (len > maxseg) {
12946 		if (len != 0 && (flags & TH_FIN)) {
12947 			flags &= ~TH_FIN;
12948 		}
12949 		if (tso) {
12950 			uint32_t moff;
12951 			int32_t max_len;
12952 
12953 			/* extract TSO information */
12954 			if_hw_tsomax = tp->t_tsomax;
12955 			if_hw_tsomaxsegcount = tp->t_tsomaxsegcount;
12956 			if_hw_tsomaxsegsize = tp->t_tsomaxsegsize;
12957 			KASSERT(ipoptlen == 0,
12958 			    ("%s: TSO can't do IP options", __func__));
12959 
12960 			/*
12961 			 * Check if we should limit by maximum payload
12962 			 * length:
12963 			 */
12964 			if (if_hw_tsomax != 0) {
12965 				/* compute maximum TSO length */
12966 				max_len = (if_hw_tsomax - hdrlen -
12967 				    max_linkhdr);
12968 				if (max_len <= 0) {
12969 					len = 0;
12970 				} else if (len > max_len) {
12971 					len = max_len;
12972 				}
12973 			}
12974 			/*
12975 			 * Prevent the last segment from being fractional
12976 			 * unless the send sockbuf can be emptied:
12977 			 */
12978 			if ((sb_offset + len) < sbavail(sb)) {
12979 				moff = len % (uint32_t)maxseg;
12980 				if (moff != 0) {
12981 					len -= moff;
12982 				}
12983 			}
12984 			/*
12985 			 * In case there are too many small fragments don't
12986 			 * use TSO:
12987 			 */
12988 			if (len <= maxseg) {
12989 				len = maxseg;
12990 				tso = 0;
12991 			}
12992 		} else {
12993 			/* Not doing TSO */
12994 			if (optlen + ipoptlen >= tp->t_maxseg) {
12995 				/*
12996 				 * Since we don't have enough space to put
12997 				 * the IP header chain and the TCP header in
12998 				 * one packet as required by RFC 7112, don't
12999 				 * send it. Also ensure that at least one
13000 				 * byte of the payload can be put into the
13001 				 * TCP segment.
13002 				 */
13003 				SOCKBUF_UNLOCK(&so->so_snd);
13004 				error = EMSGSIZE;
13005 				sack_rxmit = 0;
13006 				goto out;
13007 			}
13008 			len = maxseg;
13009 		}
13010 	} else {
13011 		/* Not doing TSO */
13012 		if_hw_tsomaxsegcount = 0;
13013 		tso = 0;
13014 	}
13015 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
13016 	    ("%s: len > IP_MAXPACKET", __func__));
13017 #ifdef DIAGNOSTIC
13018 #ifdef INET6
13019 	if (max_linkhdr + hdrlen > MCLBYTES)
13020 #else
13021 	if (max_linkhdr + hdrlen > MHLEN)
13022 #endif
13023 		panic("tcphdr too big");
13024 #endif
13025 	/*
13026 	 * This KASSERT is here to catch edge cases at a well defined place.
13027 	 * Before, those had triggered (random) panic conditions further
13028 	 * down.
13029 	 */
13030 #ifdef BBR_INVARIANTS
13031 	if (sack_rxmit) {
13032 		if (SEQ_LT(rsm->r_start, tp->snd_una)) {
13033 			panic("RSM:%p TP:%p bbr:%p start:%u is < snd_una:%u",
13034 			    rsm, tp, bbr, rsm->r_start, tp->snd_una);
13035 		}
13036 	}
13037 #endif
13038 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
13039 	if ((len == 0) &&
13040 	    (flags & TH_FIN) &&
13041 	    (sbused(sb))) {
13042 		/*
13043 		 * We have outstanding data, don't send a fin by itself!.
13044 		 */
13045 		slot = 0;
13046 		goto just_return;
13047 	}
13048 	/*
13049 	 * Grab a header mbuf, attaching a copy of data to be transmitted,
13050 	 * and initialize the header from the template for sends on this
13051 	 * connection.
13052 	 */
13053 	if (len) {
13054 		uint32_t moff;
13055 
13056 		/*
13057 		 * We place a limit on sending with hptsi.
13058 		 */
13059 		if ((rsm == NULL) && len > pace_max_segs)
13060 			len = pace_max_segs;
13061 		if (len <= maxseg)
13062 			tso = 0;
13063 #ifdef INET6
13064 		if (MHLEN < hdrlen + max_linkhdr)
13065 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
13066 		else
13067 #endif
13068 			m = m_gethdr(M_NOWAIT, MT_DATA);
13069 
13070 		if (m == NULL) {
13071 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13072 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13073 			SOCKBUF_UNLOCK(sb);
13074 			error = ENOBUFS;
13075 			sack_rxmit = 0;
13076 			goto out;
13077 		}
13078 		m->m_data += max_linkhdr;
13079 		m->m_len = hdrlen;
13080 		/*
13081 		 * Start the m_copy functions from the closest mbuf to the
13082 		 * sb_offset in the socket buffer chain.
13083 		 */
13084 		if ((sb_offset > sbavail(sb)) || ((len + sb_offset) > sbavail(sb))) {
13085 #ifdef BBR_INVARIANTS
13086 			if ((len + sb_offset) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0)))
13087 				panic("tp:%p bbr:%p len:%u sb_offset:%u sbavail:%u rsm:%p %u:%u:%u",
13088 				    tp, bbr, len, sb_offset, sbavail(sb), rsm,
13089 				    doing_retran_from,
13090 				    picked_up_retran,
13091 				    doing_tlp);
13092 
13093 #endif
13094 			/*
13095 			 * In this messed up situation we have two choices,
13096 			 * a) pretend the send worked, and just start timers
13097 			 * and what not (not good since that may lead us
13098 			 * back here a lot). <or> b) Send the lowest segment
13099 			 * in the map. <or> c) Drop the connection. Lets do
13100 			 * <b> which if it continues to happen will lead to
13101 			 * <c> via timeouts.
13102 			 */
13103 			BBR_STAT_INC(bbr_offset_recovery);
13104 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
13105 			sb_offset = 0;
13106 			if (rsm == NULL) {
13107 				sack_rxmit = 0;
13108 				len = sbavail(sb);
13109 			} else {
13110 				sack_rxmit = 1;
13111 				if (rsm->r_start != tp->snd_una) {
13112 					/*
13113 					 * Things are really messed up, <c>
13114 					 * is the only thing to do.
13115 					 */
13116 					BBR_STAT_INC(bbr_offset_drop);
13117 					SOCKBUF_UNLOCK(sb);
13118 					(void)m_free(m);
13119 					return (-EFAULT); /* tcp_drop() */
13120 				}
13121 				len = rsm->r_end - rsm->r_start;
13122 			}
13123 			if (len > sbavail(sb))
13124 				len = sbavail(sb);
13125 			if (len > maxseg)
13126 				len = maxseg;
13127 		}
13128 		mb = sbsndptr_noadv(sb, sb_offset, &moff);
13129 		if (len <= MHLEN - hdrlen - max_linkhdr && !hw_tls) {
13130 			m_copydata(mb, moff, (int)len,
13131 			    mtod(m, caddr_t)+hdrlen);
13132 			if (rsm == NULL)
13133 				sbsndptr_adv(sb, mb, len);
13134 			m->m_len += len;
13135 		} else {
13136 			struct sockbuf *msb;
13137 
13138 			if (rsm)
13139 				msb = NULL;
13140 			else
13141 				msb = sb;
13142 #ifdef BBR_INVARIANTS
13143 			if ((len + moff) > (sbavail(sb) + ((flags & (TH_FIN | TH_SYN)) ? 1 : 0))) {
13144 				if (rsm) {
13145 					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 ",
13146 					    tp, bbr, len, moff,
13147 					    sbavail(sb), rsm,
13148 					    tp->snd_una, rsm->r_flags, rsm->r_start,
13149 					    doing_retran_from,
13150 					    picked_up_retran,
13151 					    doing_tlp, sack_rxmit);
13152 				} else {
13153 					panic("tp:%p bbr:%p len:%u moff:%u sbavail:%u sb_offset:%u snd_una:%u",
13154 					    tp, bbr, len, moff, sbavail(sb), sb_offset, tp->snd_una);
13155 				}
13156 			}
13157 #endif
13158 			m->m_next = tcp_m_copym(
13159 				mb, moff, &len,
13160 				if_hw_tsomaxsegcount,
13161 				if_hw_tsomaxsegsize, msb,
13162 				((rsm == NULL) ? hw_tls : 0)
13163 #ifdef NETFLIX_COPY_ARGS
13164 				, NULL, NULL
13165 #endif
13166 				);
13167 			if (len <= maxseg) {
13168 				/*
13169 				 * Must have ran out of mbufs for the copy
13170 				 * shorten it to no longer need tso. Lets
13171 				 * not put on sendalot since we are low on
13172 				 * mbufs.
13173 				 */
13174 				tso = 0;
13175 			}
13176 			if (m->m_next == NULL) {
13177 				SOCKBUF_UNLOCK(sb);
13178 				(void)m_free(m);
13179 				error = ENOBUFS;
13180 				sack_rxmit = 0;
13181 				goto out;
13182 			}
13183 		}
13184 #ifdef BBR_INVARIANTS
13185 		if (tso && len < maxseg) {
13186 			panic("tp:%p tso on, but len:%d < maxseg:%d",
13187 			    tp, len, maxseg);
13188 		}
13189 		if (tso && if_hw_tsomaxsegcount) {
13190 			int32_t seg_cnt = 0;
13191 			struct mbuf *foo;
13192 
13193 			foo = m;
13194 			while (foo) {
13195 				seg_cnt++;
13196 				foo = foo->m_next;
13197 			}
13198 			if (seg_cnt > if_hw_tsomaxsegcount) {
13199 				panic("seg_cnt:%d > max:%d", seg_cnt, if_hw_tsomaxsegcount);
13200 			}
13201 		}
13202 #endif
13203 		/*
13204 		 * If we're sending everything we've got, set PUSH. (This
13205 		 * will keep happy those implementations which only give
13206 		 * data to the user when a buffer fills or a PUSH comes in.)
13207 		 */
13208 		if (sb_offset + len == sbused(sb) &&
13209 		    sbused(sb) &&
13210 		    !(flags & TH_SYN)) {
13211 			flags |= TH_PUSH;
13212 		}
13213 		SOCKBUF_UNLOCK(sb);
13214 	} else {
13215 		SOCKBUF_UNLOCK(sb);
13216 		if (tp->t_flags & TF_ACKNOW)
13217 			KMOD_TCPSTAT_INC(tcps_sndacks);
13218 		else if (flags & (TH_SYN | TH_FIN | TH_RST))
13219 			KMOD_TCPSTAT_INC(tcps_sndctrl);
13220 		else
13221 			KMOD_TCPSTAT_INC(tcps_sndwinup);
13222 
13223 		m = m_gethdr(M_NOWAIT, MT_DATA);
13224 		if (m == NULL) {
13225 			BBR_STAT_INC(bbr_failed_mbuf_aloc);
13226 			bbr_log_enobuf_jmp(bbr, len, cts, __LINE__, len, 0, 0);
13227 			error = ENOBUFS;
13228 			/* Fudge the send time since we could not send */
13229 			sack_rxmit = 0;
13230 			goto out;
13231 		}
13232 #ifdef INET6
13233 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
13234 		    MHLEN >= hdrlen) {
13235 			M_ALIGN(m, hdrlen);
13236 		} else
13237 #endif
13238 			m->m_data += max_linkhdr;
13239 		m->m_len = hdrlen;
13240 	}
13241 	SOCKBUF_UNLOCK_ASSERT(sb);
13242 	m->m_pkthdr.rcvif = (struct ifnet *)0;
13243 #ifdef MAC
13244 	mac_inpcb_create_mbuf(inp, m);
13245 #endif
13246 #ifdef INET6
13247 	if (isipv6) {
13248 		ip6 = mtod(m, struct ip6_hdr *);
13249 		if (tp->t_port) {
13250 			udp = (struct udphdr *)((caddr_t)ip6 + sizeof(struct ip6_hdr));
13251 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13252 			udp->uh_dport = tp->t_port;
13253 			ulen = hdrlen + len - sizeof(struct ip6_hdr);
13254 			udp->uh_ulen = htons(ulen);
13255 			th = (struct tcphdr *)(udp + 1);
13256 		} else {
13257 			th = (struct tcphdr *)(ip6 + 1);
13258 		}
13259 		tcpip_fillheaders(inp, tp->t_port, ip6, th);
13260 	} else
13261 #endif				/* INET6 */
13262 	{
13263 		ip = mtod(m, struct ip *);
13264 		if (tp->t_port) {
13265 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
13266 			udp->uh_sport = htons(V_tcp_udp_tunneling_port);
13267 			udp->uh_dport = tp->t_port;
13268 			ulen = hdrlen + len - sizeof(struct ip);
13269 			udp->uh_ulen = htons(ulen);
13270 			th = (struct tcphdr *)(udp + 1);
13271 		} else {
13272 			th = (struct tcphdr *)(ip + 1);
13273 		}
13274 		tcpip_fillheaders(inp, tp->t_port, ip, th);
13275 	}
13276 	/*
13277 	 * If we are doing retransmissions, then snd_nxt will not reflect
13278 	 * the first unsent octet.  For ACK only packets, we do not want the
13279 	 * sequence number of the retransmitted packet, we want the sequence
13280 	 * number of the next unsent octet.  So, if there is no data (and no
13281 	 * SYN or FIN), use snd_max instead of snd_nxt when filling in
13282 	 * ti_seq.  But if we are in persist state, snd_max might reflect
13283 	 * one byte beyond the right edge of the window, so use snd_nxt in
13284 	 * that case, since we know we aren't doing a retransmission.
13285 	 * (retransmit and persist are mutually exclusive...)
13286 	 */
13287 	if (sack_rxmit == 0) {
13288 		if (len && ((flags & (TH_FIN | TH_SYN | TH_RST)) == 0)) {
13289 			/* New data (including new persists) */
13290 			th->th_seq = htonl(tp->snd_max);
13291 			bbr_seq = tp->snd_max;
13292 		} else if (flags & TH_SYN) {
13293 			/* Syn's always send from iss */
13294 			th->th_seq = htonl(tp->iss);
13295 			bbr_seq = tp->iss;
13296 		} else if (flags & TH_FIN) {
13297 			if (flags & TH_FIN && tp->t_flags & TF_SENTFIN) {
13298 				/*
13299 				 * If we sent the fin already its 1 minus
13300 				 * snd_max
13301 				 */
13302 				th->th_seq = (htonl(tp->snd_max - 1));
13303 				bbr_seq = (tp->snd_max - 1);
13304 			} else {
13305 				/* First time FIN use snd_max */
13306 				th->th_seq = htonl(tp->snd_max);
13307 				bbr_seq = tp->snd_max;
13308 			}
13309 		} else {
13310 			/*
13311 			 * len == 0 and not persist we use snd_max, sending
13312 			 * an ack unless we have sent the fin then its 1
13313 			 * minus.
13314 			 */
13315 			/*
13316 			 * XXXRRS Question if we are in persists and we have
13317 			 * nothing outstanding to send and we have not sent
13318 			 * a FIN, we will send an ACK. In such a case it
13319 			 * might be better to send (tp->snd_una - 1) which
13320 			 * would force the peer to ack.
13321 			 */
13322 			if (tp->t_flags & TF_SENTFIN) {
13323 				th->th_seq = htonl(tp->snd_max - 1);
13324 				bbr_seq = (tp->snd_max - 1);
13325 			} else {
13326 				th->th_seq = htonl(tp->snd_max);
13327 				bbr_seq = tp->snd_max;
13328 			}
13329 		}
13330 	} else {
13331 		/* All retransmits use the rsm to guide the send */
13332 		th->th_seq = htonl(rsm->r_start);
13333 		bbr_seq = rsm->r_start;
13334 	}
13335 	th->th_ack = htonl(tp->rcv_nxt);
13336 	if (optlen) {
13337 		bcopy(opt, th + 1, optlen);
13338 		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
13339 	}
13340 	tcp_set_flags(th, flags);
13341 	/*
13342 	 * Calculate receive window.  Don't shrink window, but avoid silly
13343 	 * window syndrome.
13344 	 */
13345 	if ((flags & TH_RST) || ((recwin < (so->so_rcv.sb_hiwat / 4) &&
13346 				  recwin < maxseg)))
13347 		recwin = 0;
13348 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
13349 	    recwin < (tp->rcv_adv - tp->rcv_nxt))
13350 		recwin = (tp->rcv_adv - tp->rcv_nxt);
13351 	if (recwin > TCP_MAXWIN << tp->rcv_scale)
13352 		recwin = TCP_MAXWIN << tp->rcv_scale;
13353 
13354 	/*
13355 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN> or
13356 	 * <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK> case is
13357 	 * handled in syncache.
13358 	 */
13359 	if (flags & TH_SYN)
13360 		th->th_win = htons((u_short)
13361 		    (min(sbspace(&so->so_rcv), TCP_MAXWIN)));
13362 	else {
13363 		/* Avoid shrinking window with window scaling. */
13364 		recwin = roundup2(recwin, 1 << tp->rcv_scale);
13365 		th->th_win = htons((u_short)(recwin >> tp->rcv_scale));
13366 	}
13367 	/*
13368 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised a 0
13369 	 * window.  This may cause the remote transmitter to stall.  This
13370 	 * flag tells soreceive() to disable delayed acknowledgements when
13371 	 * draining the buffer.  This can occur if the receiver is
13372 	 * attempting to read more data than can be buffered prior to
13373 	 * transmitting on the connection.
13374 	 */
13375 	if (th->th_win == 0) {
13376 		tp->t_sndzerowin++;
13377 		tp->t_flags |= TF_RXWIN0SENT;
13378 	} else
13379 		tp->t_flags &= ~TF_RXWIN0SENT;
13380 	/*
13381 	 * We don't support urgent data, but drag along
13382 	 * the pointer in case of a stack switch.
13383 	 */
13384 	tp->snd_up = tp->snd_una;
13385 	/*
13386 	 * Put TCP length in extended header, and then checksum extended
13387 	 * header and data.
13388 	 */
13389 	m->m_pkthdr.len = hdrlen + len;	/* in6_cksum() need this */
13390 
13391 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
13392 	if (to.to_flags & TOF_SIGNATURE) {
13393 		/*
13394 		 * Calculate MD5 signature and put it into the place
13395 		 * determined before. NOTE: since TCP options buffer doesn't
13396 		 * point into mbuf's data, calculate offset and use it.
13397 		 */
13398 		if (!TCPMD5_ENABLED() || TCPMD5_OUTPUT(m, th,
13399 		    (u_char *)(th + 1) + (to.to_signature - opt)) != 0) {
13400 			/*
13401 			 * Do not send segment if the calculation of MD5
13402 			 * digest has failed.
13403 			 */
13404 			goto out;
13405 		}
13406 	}
13407 #endif
13408 
13409 #ifdef INET6
13410 	if (isipv6) {
13411 		/*
13412 		 * ip6_plen is not need to be filled now, and will be filled
13413 		 * in ip6_output.
13414 		 */
13415 		if (tp->t_port) {
13416 			m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
13417 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13418 			udp->uh_sum = in6_cksum_pseudo(ip6, ulen, IPPROTO_UDP, 0);
13419 			th->th_sum = htons(0);
13420 			UDPSTAT_INC(udps_opackets);
13421 		} else {
13422 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
13423 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13424 			th->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr) +
13425 			    optlen + len, IPPROTO_TCP, 0);
13426 		}
13427 	}
13428 #endif
13429 #if defined(INET6) && defined(INET)
13430 	else
13431 #endif
13432 #ifdef INET
13433 	{
13434 		if (tp->t_port) {
13435 			m->m_pkthdr.csum_flags = CSUM_UDP;
13436 			m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
13437 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr,
13438 			    ip->ip_dst.s_addr, htons(ulen + IPPROTO_UDP));
13439 			th->th_sum = htons(0);
13440 			UDPSTAT_INC(udps_opackets);
13441 		} else {
13442 			csum_flags = m->m_pkthdr.csum_flags = CSUM_TCP;
13443 			m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
13444 			th->th_sum = in_pseudo(ip->ip_src.s_addr,
13445 			    ip->ip_dst.s_addr, htons(sizeof(struct tcphdr) +
13446 			    IPPROTO_TCP + len + optlen));
13447 		}
13448 		/* IP version must be set here for ipv4/ipv6 checking later */
13449 		KASSERT(ip->ip_v == IPVERSION,
13450 		    ("%s: IP version incorrect: %d", __func__, ip->ip_v));
13451 	}
13452 #endif
13453 
13454 	/*
13455 	 * Enable TSO and specify the size of the segments. The TCP pseudo
13456 	 * header checksum is always provided. XXX: Fixme: This is currently
13457 	 * not the case for IPv6.
13458 	 */
13459 	if (tso) {
13460 		KASSERT(len > maxseg,
13461 		    ("%s: len:%d <= tso_segsz:%d", __func__, len, maxseg));
13462 		m->m_pkthdr.csum_flags |= CSUM_TSO;
13463 		csum_flags |= CSUM_TSO;
13464 		m->m_pkthdr.tso_segsz = maxseg;
13465 	}
13466 	KASSERT(len + hdrlen == m_length(m, NULL),
13467 	    ("%s: mbuf chain different than expected: %d + %u != %u",
13468 	    __func__, len, hdrlen, m_length(m, NULL)));
13469 
13470 #ifdef TCP_HHOOK
13471 	/* Run HHOOK_TC_ESTABLISHED_OUT helper hooks. */
13472 	hhook_run_tcp_est_out(tp, th, &to, len, tso);
13473 #endif
13474 
13475 	/* Log to the black box */
13476 	if (tcp_bblogging_on(tp)) {
13477 		union tcp_log_stackspecific log;
13478 
13479 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
13480 		/* Record info on type of transmission */
13481 		log.u_bbr.flex1 = bbr->r_ctl.rc_hptsi_agg_delay;
13482 		log.u_bbr.flex2 = (bbr->r_recovery_bw << 3);
13483 		log.u_bbr.flex3 = maxseg;
13484 		log.u_bbr.flex4 = delay_calc;
13485 		log.u_bbr.flex5 = bbr->rc_past_init_win;
13486 		log.u_bbr.flex5 <<= 1;
13487 		log.u_bbr.flex5 |= bbr->rc_no_pacing;
13488 		log.u_bbr.flex5 <<= 29;
13489 		log.u_bbr.flex5 |= tp->t_maxseg;
13490 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_max_segs;
13491 		log.u_bbr.flex7 = (bbr->rc_bbr_state << 8) | bbr_state_val(bbr);
13492 		/* lets poke in the low and the high here for debugging */
13493 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
13494 		if (rsm || sack_rxmit) {
13495 			if (doing_tlp)
13496 				log.u_bbr.flex8 = 2;
13497 			else
13498 				log.u_bbr.flex8 = 1;
13499 		} else {
13500 			log.u_bbr.flex8 = 0;
13501 		}
13502 		lgb = tcp_log_event(tp, th, &so->so_rcv, &so->so_snd, TCP_LOG_OUT, ERRNO_UNK,
13503 		    len, &log, false, NULL, NULL, 0, tv);
13504 	} else {
13505 		lgb = NULL;
13506 	}
13507 	/*
13508 	 * Fill in IP length and desired time to live and send to IP level.
13509 	 * There should be a better way to handle ttl and tos; we could keep
13510 	 * them in the template, but need a way to checksum without them.
13511 	 */
13512 	/*
13513 	 * m->m_pkthdr.len should have been set before cksum calcuration,
13514 	 * because in6_cksum() need it.
13515 	 */
13516 #ifdef INET6
13517 	if (isipv6) {
13518 		/*
13519 		 * we separately set hoplimit for every segment, since the
13520 		 * user might want to change the value via setsockopt. Also,
13521 		 * desired default hop limit might be changed via Neighbor
13522 		 * Discovery.
13523 		 */
13524 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
13525 
13526 		/*
13527 		 * Set the packet size here for the benefit of DTrace
13528 		 * probes. ip6_output() will set it properly; it's supposed
13529 		 * to include the option header lengths as well.
13530 		 */
13531 		ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(*ip6));
13532 
13533 		if (V_path_mtu_discovery && maxseg > V_tcp_minmss)
13534 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13535 		else
13536 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13537 
13538 		if (tp->t_state == TCPS_SYN_SENT)
13539 			TCP_PROBE5(connect__request, NULL, tp, ip6, tp, th);
13540 
13541 		TCP_PROBE5(send, NULL, tp, ip6, tp, th);
13542 		/* TODO: IPv6 IP6TOS_ECT bit on */
13543 		error = ip6_output(m, inp->in6p_outputopts,
13544 		    &inp->inp_route6,
13545 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0),
13546 		    NULL, NULL, inp);
13547 
13548 		if (error == EMSGSIZE && inp->inp_route6.ro_nh != NULL)
13549 			mtu = inp->inp_route6.ro_nh->nh_mtu;
13550 	}
13551 #endif				/* INET6 */
13552 #if defined(INET) && defined(INET6)
13553 	else
13554 #endif
13555 #ifdef INET
13556 	{
13557 		ip->ip_len = htons(m->m_pkthdr.len);
13558 #ifdef INET6
13559 		if (isipv6)
13560 			ip->ip_ttl = in6_selecthlim(inp, NULL);
13561 #endif				/* INET6 */
13562 		/*
13563 		 * If we do path MTU discovery, then we set DF on every
13564 		 * packet. This might not be the best thing to do according
13565 		 * to RFC3390 Section 2. However the tcp hostcache migitates
13566 		 * the problem so it affects only the first tcp connection
13567 		 * with a host.
13568 		 *
13569 		 * NB: Don't set DF on small MTU/MSS to have a safe
13570 		 * fallback.
13571 		 */
13572 		if (V_path_mtu_discovery && tp->t_maxseg > V_tcp_minmss) {
13573 			tp->t_flags2 |= TF2_PLPMTU_PMTUD;
13574 			if (tp->t_port == 0 || len < V_tcp_minmss) {
13575 				ip->ip_off |= htons(IP_DF);
13576 			}
13577 		} else {
13578 			tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
13579 		}
13580 
13581 		if (tp->t_state == TCPS_SYN_SENT)
13582 			TCP_PROBE5(connect__request, NULL, tp, ip, tp, th);
13583 
13584 		TCP_PROBE5(send, NULL, tp, ip, tp, th);
13585 
13586 		error = ip_output(m, inp->inp_options, &inp->inp_route,
13587 		    ((rsm || sack_rxmit) ? IP_NO_SND_TAG_RL : 0), 0,
13588 		    inp);
13589 		if (error == EMSGSIZE && inp->inp_route.ro_nh != NULL)
13590 			mtu = inp->inp_route.ro_nh->nh_mtu;
13591 	}
13592 #endif				/* INET */
13593 out:
13594 
13595 	if (lgb) {
13596 		lgb->tlb_errno = error;
13597 		lgb = NULL;
13598 	}
13599 	/*
13600 	 * In transmit state, time the transmission and arrange for the
13601 	 * retransmit.  In persist state, just set snd_max.
13602 	 */
13603 	if (error == 0) {
13604 		tcp_account_for_send(tp, len, (rsm != NULL), doing_tlp, hw_tls);
13605 		if (TCPS_HAVEESTABLISHED(tp->t_state) &&
13606 		    (tp->t_flags & TF_SACK_PERMIT) &&
13607 		    tp->rcv_numsacks > 0)
13608 			tcp_clean_dsack_blocks(tp);
13609 		/* We sent an ack clear the bbr_segs_rcvd count */
13610 		bbr->output_error_seen = 0;
13611 		bbr->oerror_cnt = 0;
13612 		bbr->bbr_segs_rcvd = 0;
13613 		if (len == 0)
13614 			counter_u64_add(bbr_out_size[TCP_MSS_ACCT_SNDACK], 1);
13615 		/* Do accounting for new sends */
13616 		if ((len > 0) && (rsm == NULL)) {
13617 			int idx;
13618 			if (tp->snd_una == tp->snd_max) {
13619 				/*
13620 				 * Special case to match google, when
13621 				 * nothing is in flight the delivered
13622 				 * time does get updated to the current
13623 				 * time (see tcp_rate_bsd.c).
13624 				 */
13625 				bbr->r_ctl.rc_del_time = cts;
13626 			}
13627 			if (len >= maxseg) {
13628 				idx = (len / maxseg) + 3;
13629 				if (idx >= TCP_MSS_ACCT_ATIMER)
13630 					counter_u64_add(bbr_out_size[(TCP_MSS_ACCT_ATIMER - 1)], 1);
13631 				else
13632 					counter_u64_add(bbr_out_size[idx], 1);
13633 			} else {
13634 				/* smaller than a MSS */
13635 				idx = len / (bbr_hptsi_bytes_min - bbr->rc_last_options);
13636 				if (idx >= TCP_MSS_SMALL_MAX_SIZE_DIV)
13637 					idx = (TCP_MSS_SMALL_MAX_SIZE_DIV - 1);
13638 				counter_u64_add(bbr_out_size[(idx + TCP_MSS_SMALL_SIZE_OFF)], 1);
13639 			}
13640 		}
13641 	}
13642 	abandon = 0;
13643 	/*
13644 	 * We must do the send accounting before we log the output,
13645 	 * otherwise the state of the rsm could change and we account to the
13646 	 * wrong bucket.
13647 	 */
13648 	if (len > 0) {
13649 		bbr_do_send_accounting(tp, bbr, rsm, len, error);
13650 		if (error == 0) {
13651 			if (tp->snd_una == tp->snd_max)
13652 				bbr->r_ctl.rc_tlp_rxt_last_time = cts;
13653 		}
13654 	}
13655 	bbr_log_output(bbr, tp, &to, len, bbr_seq, (uint8_t) flags, error,
13656 	    cts, mb, &abandon, rsm, 0, sb);
13657 	if (abandon) {
13658 		/*
13659 		 * If bbr_log_output destroys the TCB or sees a TH_RST being
13660 		 * sent we should hit this condition.
13661 		 */
13662 		return (0);
13663 	}
13664 	if (bbr->rc_in_persist == 0) {
13665 		/*
13666 		 * Advance snd_nxt over sequence space of this segment.
13667 		 */
13668 		if (error)
13669 			/* We don't log or do anything with errors */
13670 			goto skip_upd;
13671 
13672 		if (tp->snd_una == tp->snd_max &&
13673 		    (len || (flags & (TH_SYN | TH_FIN)))) {
13674 			/*
13675 			 * Update the time we just added data since none was
13676 			 * outstanding.
13677 			 */
13678 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13679 			bbr->rc_tp->t_acktime  = ticks;
13680 		}
13681 		if (flags & (TH_SYN | TH_FIN) && (rsm == NULL)) {
13682 			if (flags & TH_SYN) {
13683 				/*
13684 				 * Smack the snd_max to iss + 1
13685 				 * if its a FO we will add len below.
13686 				 */
13687 				tp->snd_max = tp->iss + 1;
13688 			}
13689 			if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13690 				tp->snd_max++;
13691 				tp->t_flags |= TF_SENTFIN;
13692 			}
13693 		}
13694 		if (sack_rxmit == 0)
13695 			tp->snd_max += len;
13696 skip_upd:
13697 		if ((error == 0) && len)
13698 			tot_len += len;
13699 	} else {
13700 		/* Persists case */
13701 		int32_t xlen = len;
13702 
13703 		if (error)
13704 			goto nomore;
13705 
13706 		if (flags & TH_SYN)
13707 			++xlen;
13708 		if ((flags & TH_FIN) && ((tp->t_flags & TF_SENTFIN) == 0)) {
13709 			++xlen;
13710 			tp->t_flags |= TF_SENTFIN;
13711 		}
13712 		if (xlen && (tp->snd_una == tp->snd_max)) {
13713 			/*
13714 			 * Update the time we just added data since none was
13715 			 * outstanding.
13716 			 */
13717 			bbr_log_progress_event(bbr, tp, ticks, PROGRESS_START, __LINE__);
13718 			bbr->rc_tp->t_acktime = ticks;
13719 		}
13720 		if (sack_rxmit == 0)
13721 			tp->snd_max += xlen;
13722 		tot_len += (len + optlen + ipoptlen);
13723 	}
13724 nomore:
13725 	if (error) {
13726 		/*
13727 		 * Failures do not advance the seq counter above. For the
13728 		 * case of ENOBUFS we will fall out and become ack-clocked.
13729 		 * capping the cwnd at the current flight.
13730 		 * Everything else will just have to retransmit with the timer
13731 		 * (no pacer).
13732 		 */
13733 		SOCKBUF_UNLOCK_ASSERT(sb);
13734 		BBR_STAT_INC(bbr_saw_oerr);
13735 		/* Clear all delay/early tracks */
13736 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
13737 		bbr->r_ctl.rc_agg_early = 0;
13738 		bbr->r_agg_early_set = 0;
13739 		bbr->output_error_seen = 1;
13740 		if (bbr->oerror_cnt < 0xf)
13741 			bbr->oerror_cnt++;
13742 		if (bbr_max_net_error_cnt && (bbr->oerror_cnt >= bbr_max_net_error_cnt)) {
13743 			/* drop the session */
13744 			return (-ENETDOWN);
13745 		}
13746 		switch (error) {
13747 		case ENOBUFS:
13748 			/*
13749 			 * Make this guy have to get ack's to send
13750 			 * more but lets make sure we don't
13751 			 * slam him below a T-O (1MSS).
13752 			 */
13753 			if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
13754 				tp->snd_cwnd = ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13755 								    bbr->r_ctl.rc_lost_bytes)) - maxseg;
13756 				if (tp->snd_cwnd < maxseg)
13757 					tp->snd_cwnd = maxseg;
13758 			}
13759 			slot = (bbr_error_base_paceout + 1) << bbr->oerror_cnt;
13760 			BBR_STAT_INC(bbr_saw_enobuf);
13761 			if (bbr->bbr_hdrw_pacing)
13762 				counter_u64_add(bbr_hdwr_pacing_enobuf, 1);
13763 			else
13764 				counter_u64_add(bbr_nohdwr_pacing_enobuf, 1);
13765 			/*
13766 			 * Here even in the enobuf's case we want to do our
13767 			 * state update. The reason being we may have been
13768 			 * called by the input function. If so we have had
13769 			 * things change.
13770 			 */
13771 			error = 0;
13772 			goto enobufs;
13773 		case EMSGSIZE:
13774 			/*
13775 			 * For some reason the interface we used initially
13776 			 * to send segments changed to another or lowered
13777 			 * its MTU. If TSO was active we either got an
13778 			 * interface without TSO capabilits or TSO was
13779 			 * turned off. If we obtained mtu from ip_output()
13780 			 * then update it and try again.
13781 			 */
13782 			/* Turn on tracing (or try to) */
13783 			{
13784 				int old_maxseg;
13785 
13786 				old_maxseg = tp->t_maxseg;
13787 				BBR_STAT_INC(bbr_saw_emsgsiz);
13788 				bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, csum_flags, tso, cts);
13789 				if (mtu != 0)
13790 					tcp_mss_update(tp, -1, mtu, NULL, NULL);
13791 				if (old_maxseg <= tp->t_maxseg) {
13792 					/* Huh it did not shrink? */
13793 					tp->t_maxseg = old_maxseg - 40;
13794 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13795 				}
13796 				/*
13797 				 * Nuke all other things that can interfere
13798 				 * with slot
13799 				 */
13800 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13801 					slot = bbr_get_pacing_delay(bbr,
13802 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13803 					    (tot_len + len), cts, 0);
13804 					if (slot < bbr_error_base_paceout)
13805 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13806 				} else
13807 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13808 				bbr->rc_output_starts_timer = 1;
13809 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13810 				    tot_len);
13811 				return (error);
13812 			}
13813 		case EPERM:
13814 		case EACCES:
13815 			tp->t_softerror = error;
13816 			/* FALLTHROUGH */
13817 		case EHOSTDOWN:
13818 		case EHOSTUNREACH:
13819 		case ENETDOWN:
13820 		case ENETUNREACH:
13821 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13822 				tp->t_softerror = error;
13823 			}
13824 			/* FALLTHROUGH */
13825 		default:
13826 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13827 			bbr->rc_output_starts_timer = 1;
13828 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13829 			return (error);
13830 		}
13831 #ifdef STATS
13832 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13833 		    len &&
13834 		    (rsm == NULL) &&
13835 	    (bbr->rc_in_persist == 0)) {
13836 		tp->gput_seq = bbr_seq;
13837 		tp->gput_ack = bbr_seq +
13838 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13839 		tp->gput_ts = cts;
13840 		tp->t_flags |= TF_GPUTINPROG;
13841 #endif
13842 	}
13843 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13844 	if ((bbr->bbr_hdw_pace_ena) &&
13845 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13846 	    (bbr->rc_past_init_win) &&
13847 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13848 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13849 	    (inp->inp_route.ro_nh &&
13850 	     inp->inp_route.ro_nh->nh_ifp)) {
13851 		/*
13852 		 * We are past the initial window and
13853 		 * have at least one measurement so we
13854 		 * could use hardware pacing if its available.
13855 		 * We have an interface and we have not attempted
13856 		 * to setup hardware pacing, lets try to now.
13857 		 */
13858 		uint64_t rate_wanted;
13859 		int err = 0;
13860 
13861 		rate_wanted = bbr_get_hardware_rate(bbr);
13862 		bbr->bbr_attempt_hdwr_pace = 1;
13863 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13864 						      inp->inp_route.ro_nh->nh_ifp,
13865 						      rate_wanted,
13866 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
13867 						      &err, NULL);
13868 		if (bbr->r_ctl.crte) {
13869 			bbr_type_log_hdwr_pacing(bbr,
13870 						 bbr->r_ctl.crte->ptbl->rs_ifp,
13871 						 rate_wanted,
13872 						 bbr->r_ctl.crte->rate,
13873 						 __LINE__, cts, err);
13874 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
13875 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
13876 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
13877 			bbr->bbr_hdrw_pacing = 1;
13878 			/* Now what is our gain status? */
13879 			if (bbr->r_ctl.crte->rate < rate_wanted) {
13880 				/* We have a problem */
13881 				bbr_setup_less_of_rate(bbr, cts,
13882 						       bbr->r_ctl.crte->rate, rate_wanted);
13883 			} else {
13884 				/* We are good */
13885 				bbr->gain_is_limited = 0;
13886 				bbr->skip_gain = 0;
13887 			}
13888 			tcp_bbr_tso_size_check(bbr, cts);
13889 		} else {
13890 			bbr_type_log_hdwr_pacing(bbr,
13891 						 inp->inp_route.ro_nh->nh_ifp,
13892 						 rate_wanted,
13893 						 0,
13894 						 __LINE__, cts, err);
13895 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
13896 		}
13897 	}
13898 	if (bbr->bbr_hdrw_pacing) {
13899 		/*
13900 		 * Worry about cases where the route
13901 		 * changes or something happened that we
13902 		 * lost our hardware pacing possibly during
13903 		 * the last ip_output call.
13904 		 */
13905 		if (inp->inp_snd_tag == NULL) {
13906 			/* A change during ip output disabled hw pacing? */
13907 			bbr->bbr_hdrw_pacing = 0;
13908 		} else if ((inp->inp_route.ro_nh == NULL) ||
13909 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
13910 			/*
13911 			 * We had an interface or route change,
13912 			 * detach from the current hdwr pacing
13913 			 * and setup to re-attempt next go
13914 			 * round.
13915 			 */
13916 			bbr->bbr_hdrw_pacing = 0;
13917 			bbr->bbr_attempt_hdwr_pace = 0;
13918 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
13919 			tcp_bbr_tso_size_check(bbr, cts);
13920 		}
13921 	}
13922 	/*
13923 	 * Data sent (as far as we can tell). If this advertises a larger
13924 	 * window than any other segment, then remember the size of the
13925 	 * advertised window. Any pending ACK has now been sent.
13926 	 */
13927 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
13928 		tp->rcv_adv = tp->rcv_nxt + recwin;
13929 
13930 	tp->last_ack_sent = tp->rcv_nxt;
13931 	if ((error == 0) &&
13932 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
13933 	    (doing_tlp == 0) &&
13934 	    (tso == 0) &&
13935 	    (len > 0) &&
13936 	    ((flags & TH_RST) == 0) &&
13937 	    ((flags & TH_SYN) == 0) &&
13938 	    (IN_RECOVERY(tp->t_flags) == 0) &&
13939 	    (bbr->rc_in_persist == 0) &&
13940 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
13941 		/*
13942 		 * For non-tso we need to goto again until we have sent out
13943 		 * enough data to match what we are hptsi out every hptsi
13944 		 * interval.
13945 		 */
13946 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13947 			/* Make sure snd_nxt is drug up */
13948 			tp->snd_nxt = tp->snd_max;
13949 		}
13950 		if (rsm != NULL) {
13951 			rsm = NULL;
13952 			goto skip_again;
13953 		}
13954 		rsm = NULL;
13955 		sack_rxmit = 0;
13956 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13957 		goto again;
13958 	}
13959 skip_again:
13960 	if ((error == 0) && (flags & TH_FIN))
13961 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
13962 	if ((error == 0) && (flags & TH_RST))
13963 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13964 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
13965 		/*
13966 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
13967 		 * what we have sent so far
13968 		 */
13969 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
13970 		if (bbr->rc_no_pacing)
13971 			slot = 0;
13972 	}
13973 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13974 enobufs:
13975 	if (bbr->rc_use_google == 0)
13976 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
13977 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13978 							bbr->r_ctl.rc_lost_bytes)));
13979 	bbr->rc_output_starts_timer = 1;
13980 	if (bbr->bbr_use_rack_cheat &&
13981 	    (more_to_rxt ||
13982 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
13983 		/* Rack cheats and shotguns out all rxt's 1ms apart */
13984 		if (slot > 1000)
13985 			slot = 1000;
13986 	}
13987 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
13988 		/*
13989 		 * We don't change the tso size until some number of sends
13990 		 * to give the hardware commands time to get down
13991 		 * to the interface.
13992 		 */
13993 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
13994 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
13995 			bbr->hw_pacing_set = 1;
13996 			tcp_bbr_tso_size_check(bbr, cts);
13997 		}
13998 	}
13999 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14000 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14001 		/* Make sure snd_nxt is drug up */
14002 		tp->snd_nxt = tp->snd_max;
14003 	}
14004 	return (error);
14005 
14006 }
14007 
14008 /*
14009  * See bbr_output_wtime() for return values.
14010  */
14011 static int
14012 bbr_output(struct tcpcb *tp)
14013 {
14014 	int32_t ret;
14015 	struct timeval tv;
14016 
14017 	NET_EPOCH_ASSERT();
14018 
14019 	INP_WLOCK_ASSERT(tptoinpcb(tp));
14020 	(void)tcp_get_usecs(&tv);
14021 	ret = bbr_output_wtime(tp, &tv);
14022 	return (ret);
14023 }
14024 
14025 static void
14026 bbr_mtu_chg(struct tcpcb *tp)
14027 {
14028 	struct tcp_bbr *bbr;
14029 	struct bbr_sendmap *rsm, *frsm = NULL;
14030 	uint32_t maxseg;
14031 
14032 	/*
14033 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14034 	 * over the current size as SACK_PASS so a retransmit will occur.
14035 	 */
14036 
14037 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14038 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14039 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14040 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14041 		/* Don't mess with ones acked (by sack?) */
14042 		if (rsm->r_flags & BBR_ACKED)
14043 			continue;
14044 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14045 			/*
14046 			 * We mark sack-passed on all the previous large
14047 			 * sends we did. This will force them to retransmit.
14048 			 */
14049 			rsm->r_flags |= BBR_SACK_PASSED;
14050 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14051 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14052 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14053 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14054 				rsm->r_flags |= BBR_MARKED_LOST;
14055 			}
14056 			if (frsm == NULL)
14057 				frsm = rsm;
14058 		}
14059 	}
14060 	if (frsm) {
14061 		bbr->r_ctl.rc_resend = frsm;
14062 	}
14063 }
14064 
14065 static int
14066 bbr_pru_options(struct tcpcb *tp, int flags)
14067 {
14068 	if (flags & PRUS_OOB)
14069 		return (EOPNOTSUPP);
14070 	return (0);
14071 }
14072 
14073 static void
14074 bbr_switch_failed(struct tcpcb *tp)
14075 {
14076 	/*
14077 	 * If a switch fails we only need to
14078 	 * make sure mbuf_queuing is still in place.
14079 	 * We also need to make sure we are still in
14080 	 * ticks granularity (though we should probably
14081 	 * change bbr to go to USECs).
14082 	 *
14083 	 * For timers we need to see if we are still in the
14084 	 * pacer (if our flags are up) if so we are good, if
14085 	 * not we need to get back into the pacer.
14086 	 */
14087 	struct timeval tv;
14088 	uint32_t cts;
14089 	uint32_t toval;
14090 	struct tcp_bbr *bbr;
14091 	struct hpts_diag diag;
14092 
14093 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
14094 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
14095 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
14096 	if (tp->t_in_hpts > IHPTS_NONE) {
14097 		return;
14098 	}
14099 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14100 	cts = tcp_get_usecs(&tv);
14101 	if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
14102 		if (TSTMP_GT(bbr->rc_pacer_started, cts)) {
14103 			toval = bbr->rc_pacer_started - cts;
14104 		} else {
14105 			/* one slot please */
14106 			toval = HPTS_TICKS_PER_SLOT;
14107 		}
14108 	} else if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
14109 		if (TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
14110 			toval = bbr->r_ctl.rc_timer_exp - cts;
14111 		} else {
14112 			/* one slot please */
14113 			toval = HPTS_TICKS_PER_SLOT;
14114 		}
14115 	} else
14116 		toval = HPTS_TICKS_PER_SLOT;
14117 	(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(toval),
14118 				   __LINE__, &diag);
14119 	bbr_log_hpts_diag(bbr, cts, &diag);
14120 }
14121 
14122 struct tcp_function_block __tcp_bbr = {
14123 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14124 	.tfb_tcp_output = bbr_output,
14125 	.tfb_do_queued_segments = ctf_do_queued_segments,
14126 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14127 	.tfb_tcp_do_segment = bbr_do_segment,
14128 	.tfb_tcp_ctloutput = bbr_ctloutput,
14129 	.tfb_tcp_fb_init = bbr_init,
14130 	.tfb_tcp_fb_fini = bbr_fini,
14131 	.tfb_tcp_timer_stop_all = bbr_stopall,
14132 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14133 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14134 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14135 	.tfb_pru_options = bbr_pru_options,
14136 	.tfb_switch_failed = bbr_switch_failed,
14137 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14138 };
14139 
14140 /*
14141  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14142  * socket option arguments.  When it re-acquires the lock after the copy, it
14143  * has to revalidate that the connection is still valid for the socket
14144  * option.
14145  */
14146 static int
14147 bbr_set_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14148 {
14149 	struct epoch_tracker et;
14150 	struct inpcb *inp = tptoinpcb(tp);
14151 	struct tcp_bbr *bbr;
14152 	int32_t error = 0, optval;
14153 
14154 	switch (sopt->sopt_level) {
14155 	case IPPROTO_IPV6:
14156 	case IPPROTO_IP:
14157 		return (tcp_default_ctloutput(tp, sopt));
14158 	}
14159 
14160 	switch (sopt->sopt_name) {
14161 	case TCP_RACK_PACE_MAX_SEG:
14162 	case TCP_RACK_MIN_TO:
14163 	case TCP_RACK_REORD_THRESH:
14164 	case TCP_RACK_REORD_FADE:
14165 	case TCP_RACK_TLP_THRESH:
14166 	case TCP_RACK_PKT_DELAY:
14167 	case TCP_BBR_ALGORITHM:
14168 	case TCP_BBR_TSLIMITS:
14169 	case TCP_BBR_IWINTSO:
14170 	case TCP_BBR_RECFORCE:
14171 	case TCP_BBR_STARTUP_PG:
14172 	case TCP_BBR_DRAIN_PG:
14173 	case TCP_BBR_RWND_IS_APP:
14174 	case TCP_BBR_PROBE_RTT_INT:
14175 	case TCP_BBR_PROBE_RTT_GAIN:
14176 	case TCP_BBR_PROBE_RTT_LEN:
14177 	case TCP_BBR_STARTUP_LOSS_EXIT:
14178 	case TCP_BBR_USEDEL_RATE:
14179 	case TCP_BBR_MIN_RTO:
14180 	case TCP_BBR_MAX_RTO:
14181 	case TCP_BBR_PACE_PER_SEC:
14182 	case TCP_DELACK:
14183 	case TCP_BBR_PACE_DEL_TAR:
14184 	case TCP_BBR_SEND_IWND_IN_TSO:
14185 	case TCP_BBR_EXTRA_STATE:
14186 	case TCP_BBR_UTTER_MAX_TSO:
14187 	case TCP_BBR_MIN_TOPACEOUT:
14188 	case TCP_BBR_FLOOR_MIN_TSO:
14189 	case TCP_BBR_TSTMP_RAISES:
14190 	case TCP_BBR_POLICER_DETECT:
14191 	case TCP_BBR_USE_RACK_CHEAT:
14192 	case TCP_DATA_AFTER_CLOSE:
14193 	case TCP_BBR_HDWR_PACE:
14194 	case TCP_BBR_PACE_SEG_MAX:
14195 	case TCP_BBR_PACE_SEG_MIN:
14196 	case TCP_BBR_PACE_CROSS:
14197 	case TCP_BBR_PACE_OH:
14198 	case TCP_BBR_TMR_PACE_OH:
14199 	case TCP_BBR_RACK_RTT_USE:
14200 	case TCP_BBR_RETRAN_WTSO:
14201 		break;
14202 	default:
14203 		return (tcp_default_ctloutput(tp, sopt));
14204 		break;
14205 	}
14206 	INP_WUNLOCK(inp);
14207 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14208 	if (error)
14209 		return (error);
14210 	INP_WLOCK(inp);
14211 	if (inp->inp_flags & INP_DROPPED) {
14212 		INP_WUNLOCK(inp);
14213 		return (ECONNRESET);
14214 	}
14215 	if (tp->t_fb != &__tcp_bbr) {
14216 		INP_WUNLOCK(inp);
14217 		return (ENOPROTOOPT);
14218 	}
14219 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14220 	switch (sopt->sopt_name) {
14221 	case TCP_BBR_PACE_PER_SEC:
14222 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14223 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14224 		break;
14225 	case TCP_BBR_PACE_DEL_TAR:
14226 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14227 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14228 		break;
14229 	case TCP_BBR_PACE_SEG_MAX:
14230 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14231 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14232 		break;
14233 	case TCP_BBR_PACE_SEG_MIN:
14234 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14235 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14236 		break;
14237 	case TCP_BBR_PACE_CROSS:
14238 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14239 		bbr->r_ctl.bbr_cross_over = optval;
14240 		break;
14241 	case TCP_BBR_ALGORITHM:
14242 		BBR_OPTS_INC(tcp_bbr_algorithm);
14243 		if (optval && (bbr->rc_use_google == 0)) {
14244 			/* Turn on the google mode */
14245 			bbr_google_mode_on(bbr);
14246 			if ((optval > 3) && (optval < 500)) {
14247 				/*
14248 				 * Must be at least greater than .3%
14249 				 * and must be less than 50.0%.
14250 				 */
14251 				bbr->r_ctl.bbr_google_discount = optval;
14252 			}
14253 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14254 			/* Turn off the google mode */
14255 			bbr_google_mode_off(bbr);
14256 		}
14257 		break;
14258 	case TCP_BBR_TSLIMITS:
14259 		BBR_OPTS_INC(tcp_bbr_tslimits);
14260 		if (optval == 1)
14261 			bbr->rc_use_ts_limit = 1;
14262 		else if (optval == 0)
14263 			bbr->rc_use_ts_limit = 0;
14264 		else
14265 			error = EINVAL;
14266 		break;
14267 
14268 	case TCP_BBR_IWINTSO:
14269 		BBR_OPTS_INC(tcp_bbr_iwintso);
14270 		if ((optval >= 0) && (optval < 128)) {
14271 			uint32_t twin;
14272 
14273 			bbr->rc_init_win = optval;
14274 			twin = bbr_initial_cwnd(bbr, tp);
14275 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14276 				tp->snd_cwnd = twin;
14277 			else
14278 				error = EBUSY;
14279 		} else
14280 			error = EINVAL;
14281 		break;
14282 	case TCP_BBR_STARTUP_PG:
14283 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14284 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14285 			bbr->r_ctl.rc_startup_pg = optval;
14286 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14287 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14288 			}
14289 		} else
14290 			error = EINVAL;
14291 		break;
14292 	case TCP_BBR_DRAIN_PG:
14293 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14294 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14295 			bbr->r_ctl.rc_drain_pg = optval;
14296 		else
14297 			error = EINVAL;
14298 		break;
14299 	case TCP_BBR_PROBE_RTT_LEN:
14300 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14301 		if (optval <= 1)
14302 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14303 		else
14304 			error = EINVAL;
14305 		break;
14306 	case TCP_BBR_PROBE_RTT_GAIN:
14307 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14308 		if (optval <= BBR_UNIT)
14309 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14310 		else
14311 			error = EINVAL;
14312 		break;
14313 	case TCP_BBR_PROBE_RTT_INT:
14314 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14315 		if (optval > 1000)
14316 			bbr->r_ctl.rc_probertt_int = optval;
14317 		else
14318 			error = EINVAL;
14319 		break;
14320 	case TCP_BBR_MIN_TOPACEOUT:
14321 		BBR_OPTS_INC(tcp_bbr_topaceout);
14322 		if (optval == 0) {
14323 			bbr->no_pacing_until = 0;
14324 			bbr->rc_no_pacing = 0;
14325 		} else if (optval <= 0x00ff) {
14326 			bbr->no_pacing_until = optval;
14327 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14328 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14329 				/* Turn on no pacing */
14330 				bbr->rc_no_pacing = 1;
14331 			}
14332 		} else
14333 			error = EINVAL;
14334 		break;
14335 	case TCP_BBR_STARTUP_LOSS_EXIT:
14336 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14337 		bbr->rc_loss_exit = optval;
14338 		break;
14339 	case TCP_BBR_USEDEL_RATE:
14340 		error = EINVAL;
14341 		break;
14342 	case TCP_BBR_MIN_RTO:
14343 		BBR_OPTS_INC(tcp_bbr_min_rto);
14344 		bbr->r_ctl.rc_min_rto_ms = optval;
14345 		break;
14346 	case TCP_BBR_MAX_RTO:
14347 		BBR_OPTS_INC(tcp_bbr_max_rto);
14348 		bbr->rc_max_rto_sec = optval;
14349 		break;
14350 	case TCP_RACK_MIN_TO:
14351 		/* Minimum time between rack t-o's in ms */
14352 		BBR_OPTS_INC(tcp_rack_min_to);
14353 		bbr->r_ctl.rc_min_to = optval;
14354 		break;
14355 	case TCP_RACK_REORD_THRESH:
14356 		/* RACK reorder threshold (shift amount) */
14357 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14358 		if ((optval > 0) && (optval < 31))
14359 			bbr->r_ctl.rc_reorder_shift = optval;
14360 		else
14361 			error = EINVAL;
14362 		break;
14363 	case TCP_RACK_REORD_FADE:
14364 		/* Does reordering fade after ms time */
14365 		BBR_OPTS_INC(tcp_rack_reord_fade);
14366 		bbr->r_ctl.rc_reorder_fade = optval;
14367 		break;
14368 	case TCP_RACK_TLP_THRESH:
14369 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14370 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14371 		if (optval)
14372 			bbr->rc_tlp_threshold = optval;
14373 		else
14374 			error = EINVAL;
14375 		break;
14376 	case TCP_BBR_USE_RACK_CHEAT:
14377 		BBR_OPTS_INC(tcp_use_rackcheat);
14378 		if (bbr->rc_use_google) {
14379 			error = EINVAL;
14380 			break;
14381 		}
14382 		BBR_OPTS_INC(tcp_rack_cheat);
14383 		if (optval)
14384 			bbr->bbr_use_rack_cheat = 1;
14385 		else
14386 			bbr->bbr_use_rack_cheat = 0;
14387 		break;
14388 	case TCP_BBR_FLOOR_MIN_TSO:
14389 		BBR_OPTS_INC(tcp_utter_max_tso);
14390 		if ((optval >= 0) && (optval < 40))
14391 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14392 		else
14393 			error = EINVAL;
14394 		break;
14395 	case TCP_BBR_UTTER_MAX_TSO:
14396 		BBR_OPTS_INC(tcp_utter_max_tso);
14397 		if ((optval >= 0) && (optval < 0xffff))
14398 			bbr->r_ctl.bbr_utter_max = optval;
14399 		else
14400 			error = EINVAL;
14401 		break;
14402 
14403 	case TCP_BBR_EXTRA_STATE:
14404 		BBR_OPTS_INC(tcp_extra_state);
14405 		if (optval)
14406 			bbr->rc_use_idle_restart = 1;
14407 		else
14408 			bbr->rc_use_idle_restart = 0;
14409 		break;
14410 	case TCP_BBR_SEND_IWND_IN_TSO:
14411 		BBR_OPTS_INC(tcp_iwnd_tso);
14412 		if (optval) {
14413 			bbr->bbr_init_win_cheat = 1;
14414 			if (bbr->rc_past_init_win == 0) {
14415 				uint32_t cts;
14416 				cts = tcp_get_usecs(&bbr->rc_tv);
14417 				tcp_bbr_tso_size_check(bbr, cts);
14418 			}
14419 		} else
14420 			bbr->bbr_init_win_cheat = 0;
14421 		break;
14422 	case TCP_BBR_HDWR_PACE:
14423 		BBR_OPTS_INC(tcp_hdwr_pacing);
14424 		if (optval){
14425 			bbr->bbr_hdw_pace_ena = 1;
14426 			bbr->bbr_attempt_hdwr_pace = 0;
14427 		} else {
14428 			bbr->bbr_hdw_pace_ena = 0;
14429 #ifdef RATELIMIT
14430 			if (bbr->r_ctl.crte != NULL) {
14431 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14432 				bbr->r_ctl.crte = NULL;
14433 			}
14434 #endif
14435 		}
14436 		break;
14437 
14438 	case TCP_DELACK:
14439 		BBR_OPTS_INC(tcp_delack);
14440 		if (optval < 100) {
14441 			if (optval == 0) /* off */
14442 				tp->t_delayed_ack = 0;
14443 			else if (optval == 1) /* on which is 2 */
14444 				tp->t_delayed_ack = 2;
14445 			else /* higher than 2 and less than 100 */
14446 				tp->t_delayed_ack = optval;
14447 			if (tp->t_flags & TF_DELACK) {
14448 				tp->t_flags &= ~TF_DELACK;
14449 				tp->t_flags |= TF_ACKNOW;
14450 				NET_EPOCH_ENTER(et);
14451 				bbr_output(tp);
14452 				NET_EPOCH_EXIT(et);
14453 			}
14454 		} else
14455 			error = EINVAL;
14456 		break;
14457 	case TCP_RACK_PKT_DELAY:
14458 		/* RACK added ms i.e. rack-rtt + reord + N */
14459 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14460 		bbr->r_ctl.rc_pkt_delay = optval;
14461 		break;
14462 
14463 	case TCP_BBR_RETRAN_WTSO:
14464 		BBR_OPTS_INC(tcp_retran_wtso);
14465 		if (optval)
14466 			bbr->rc_resends_use_tso = 1;
14467 		else
14468 			bbr->rc_resends_use_tso = 0;
14469 		break;
14470 	case TCP_DATA_AFTER_CLOSE:
14471 		BBR_OPTS_INC(tcp_data_ac);
14472 		if (optval)
14473 			bbr->rc_allow_data_af_clo = 1;
14474 		else
14475 			bbr->rc_allow_data_af_clo = 0;
14476 		break;
14477 	case TCP_BBR_POLICER_DETECT:
14478 		BBR_OPTS_INC(tcp_policer_det);
14479 		if (bbr->rc_use_google == 0)
14480 			error = EINVAL;
14481 		else if (optval)
14482 			bbr->r_use_policer = 1;
14483 		else
14484 			bbr->r_use_policer = 0;
14485 		break;
14486 
14487 	case TCP_BBR_TSTMP_RAISES:
14488 		BBR_OPTS_INC(tcp_ts_raises);
14489 		if (optval)
14490 			bbr->ts_can_raise = 1;
14491 		else
14492 			bbr->ts_can_raise = 0;
14493 		break;
14494 	case TCP_BBR_TMR_PACE_OH:
14495 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14496 		if (bbr->rc_use_google) {
14497 			error = EINVAL;
14498 		} else {
14499 			if (optval)
14500 				bbr->r_ctl.rc_incr_tmrs = 1;
14501 			else
14502 				bbr->r_ctl.rc_incr_tmrs = 0;
14503 		}
14504 		break;
14505 	case TCP_BBR_PACE_OH:
14506 		BBR_OPTS_INC(tcp_pacing_oh);
14507 		if (bbr->rc_use_google) {
14508 			error = EINVAL;
14509 		} else {
14510 			if (optval > (BBR_INCL_TCP_OH|
14511 				      BBR_INCL_IP_OH|
14512 				      BBR_INCL_ENET_OH)) {
14513 				error = EINVAL;
14514 				break;
14515 			}
14516 			if (optval & BBR_INCL_TCP_OH)
14517 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14518 			else
14519 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14520 			if (optval & BBR_INCL_IP_OH)
14521 				bbr->r_ctl.rc_inc_ip_oh = 1;
14522 			else
14523 				bbr->r_ctl.rc_inc_ip_oh = 0;
14524 			if (optval & BBR_INCL_ENET_OH)
14525 				bbr->r_ctl.rc_inc_enet_oh = 1;
14526 			else
14527 				bbr->r_ctl.rc_inc_enet_oh = 0;
14528 		}
14529 		break;
14530 	default:
14531 		return (tcp_default_ctloutput(tp, sopt));
14532 		break;
14533 	}
14534 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14535 	INP_WUNLOCK(inp);
14536 	return (error);
14537 }
14538 
14539 /*
14540  * return 0 on success, error-num on failure
14541  */
14542 static int
14543 bbr_get_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14544 {
14545 	struct inpcb *inp = tptoinpcb(tp);
14546 	struct tcp_bbr *bbr;
14547 	int32_t error, optval;
14548 
14549 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14550 	if (bbr == NULL) {
14551 		INP_WUNLOCK(inp);
14552 		return (EINVAL);
14553 	}
14554 	/*
14555 	 * Because all our options are either boolean or an int, we can just
14556 	 * pull everything into optval and then unlock and copy. If we ever
14557 	 * add a option that is not a int, then this will have quite an
14558 	 * impact to this routine.
14559 	 */
14560 	switch (sopt->sopt_name) {
14561 	case TCP_BBR_PACE_PER_SEC:
14562 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14563 		break;
14564 	case TCP_BBR_PACE_DEL_TAR:
14565 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14566 		break;
14567 	case TCP_BBR_PACE_SEG_MAX:
14568 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14569 		break;
14570 	case TCP_BBR_MIN_TOPACEOUT:
14571 		optval = bbr->no_pacing_until;
14572 		break;
14573 	case TCP_BBR_PACE_SEG_MIN:
14574 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14575 		break;
14576 	case TCP_BBR_PACE_CROSS:
14577 		optval = bbr->r_ctl.bbr_cross_over;
14578 		break;
14579 	case TCP_BBR_ALGORITHM:
14580 		optval = bbr->rc_use_google;
14581 		break;
14582 	case TCP_BBR_TSLIMITS:
14583 		optval = bbr->rc_use_ts_limit;
14584 		break;
14585 	case TCP_BBR_IWINTSO:
14586 		optval = bbr->rc_init_win;
14587 		break;
14588 	case TCP_BBR_STARTUP_PG:
14589 		optval = bbr->r_ctl.rc_startup_pg;
14590 		break;
14591 	case TCP_BBR_DRAIN_PG:
14592 		optval = bbr->r_ctl.rc_drain_pg;
14593 		break;
14594 	case TCP_BBR_PROBE_RTT_INT:
14595 		optval = bbr->r_ctl.rc_probertt_int;
14596 		break;
14597 	case TCP_BBR_PROBE_RTT_LEN:
14598 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14599 		break;
14600 	case TCP_BBR_PROBE_RTT_GAIN:
14601 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14602 		break;
14603 	case TCP_BBR_STARTUP_LOSS_EXIT:
14604 		optval = bbr->rc_loss_exit;
14605 		break;
14606 	case TCP_BBR_USEDEL_RATE:
14607 		error = EINVAL;
14608 		break;
14609 	case TCP_BBR_MIN_RTO:
14610 		optval = bbr->r_ctl.rc_min_rto_ms;
14611 		break;
14612 	case TCP_BBR_MAX_RTO:
14613 		optval = bbr->rc_max_rto_sec;
14614 		break;
14615 	case TCP_RACK_PACE_MAX_SEG:
14616 		/* Max segments in a pace */
14617 		optval = bbr->r_ctl.rc_pace_max_segs;
14618 		break;
14619 	case TCP_RACK_MIN_TO:
14620 		/* Minimum time between rack t-o's in ms */
14621 		optval = bbr->r_ctl.rc_min_to;
14622 		break;
14623 	case TCP_RACK_REORD_THRESH:
14624 		/* RACK reorder threshold (shift amount) */
14625 		optval = bbr->r_ctl.rc_reorder_shift;
14626 		break;
14627 	case TCP_RACK_REORD_FADE:
14628 		/* Does reordering fade after ms time */
14629 		optval = bbr->r_ctl.rc_reorder_fade;
14630 		break;
14631 	case TCP_BBR_USE_RACK_CHEAT:
14632 		/* Do we use the rack cheat for rxt */
14633 		optval = bbr->bbr_use_rack_cheat;
14634 		break;
14635 	case TCP_BBR_FLOOR_MIN_TSO:
14636 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14637 		break;
14638 	case TCP_BBR_UTTER_MAX_TSO:
14639 		optval = bbr->r_ctl.bbr_utter_max;
14640 		break;
14641 	case TCP_BBR_SEND_IWND_IN_TSO:
14642 		/* Do we send TSO size segments initially */
14643 		optval = bbr->bbr_init_win_cheat;
14644 		break;
14645 	case TCP_BBR_EXTRA_STATE:
14646 		optval = bbr->rc_use_idle_restart;
14647 		break;
14648 	case TCP_RACK_TLP_THRESH:
14649 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14650 		optval = bbr->rc_tlp_threshold;
14651 		break;
14652 	case TCP_RACK_PKT_DELAY:
14653 		/* RACK added ms i.e. rack-rtt + reord + N */
14654 		optval = bbr->r_ctl.rc_pkt_delay;
14655 		break;
14656 	case TCP_BBR_RETRAN_WTSO:
14657 		optval = bbr->rc_resends_use_tso;
14658 		break;
14659 	case TCP_DATA_AFTER_CLOSE:
14660 		optval = bbr->rc_allow_data_af_clo;
14661 		break;
14662 	case TCP_DELACK:
14663 		optval = tp->t_delayed_ack;
14664 		break;
14665 	case TCP_BBR_HDWR_PACE:
14666 		optval = bbr->bbr_hdw_pace_ena;
14667 		break;
14668 	case TCP_BBR_POLICER_DETECT:
14669 		optval = bbr->r_use_policer;
14670 		break;
14671 	case TCP_BBR_TSTMP_RAISES:
14672 		optval = bbr->ts_can_raise;
14673 		break;
14674 	case TCP_BBR_TMR_PACE_OH:
14675 		optval = bbr->r_ctl.rc_incr_tmrs;
14676 		break;
14677 	case TCP_BBR_PACE_OH:
14678 		optval = 0;
14679 		if (bbr->r_ctl.rc_inc_tcp_oh)
14680 			optval |= BBR_INCL_TCP_OH;
14681 		if (bbr->r_ctl.rc_inc_ip_oh)
14682 			optval |= BBR_INCL_IP_OH;
14683 		if (bbr->r_ctl.rc_inc_enet_oh)
14684 			optval |= BBR_INCL_ENET_OH;
14685 		break;
14686 	default:
14687 		return (tcp_default_ctloutput(tp, sopt));
14688 		break;
14689 	}
14690 	INP_WUNLOCK(inp);
14691 	error = sooptcopyout(sopt, &optval, sizeof optval);
14692 	return (error);
14693 }
14694 
14695 /*
14696  * return 0 on success, error-num on failure
14697  */
14698 static int
14699 bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt)
14700 {
14701 	if (sopt->sopt_dir == SOPT_SET) {
14702 		return (bbr_set_sockopt(tp, sopt));
14703 	} else if (sopt->sopt_dir == SOPT_GET) {
14704 		return (bbr_get_sockopt(tp, sopt));
14705 	} else {
14706 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14707 	}
14708 }
14709 
14710 static const char *bbr_stack_names[] = {
14711 	__XSTRING(STACKNAME),
14712 #ifdef STACKALIAS
14713 	__XSTRING(STACKALIAS),
14714 #endif
14715 };
14716 
14717 static bool bbr_mod_inited = false;
14718 
14719 static int
14720 tcp_addbbr(module_t mod, int32_t type, void *data)
14721 {
14722 	int32_t err = 0;
14723 	int num_stacks;
14724 
14725 	switch (type) {
14726 	case MOD_LOAD:
14727 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14728 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14729 		    sizeof(struct bbr_sendmap),
14730 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14731 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14732 		    sizeof(struct tcp_bbr),
14733 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14734 		sysctl_ctx_init(&bbr_sysctl_ctx);
14735 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14736 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14737 		    OID_AUTO,
14738 #ifdef STACKALIAS
14739 		    __XSTRING(STACKALIAS),
14740 #else
14741 		    __XSTRING(STACKNAME),
14742 #endif
14743 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14744 		    "");
14745 		if (bbr_sysctl_root == NULL) {
14746 			printf("Failed to add sysctl node\n");
14747 			err = EFAULT;
14748 			goto free_uma;
14749 		}
14750 		bbr_init_sysctls();
14751 		num_stacks = nitems(bbr_stack_names);
14752 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14753 		    bbr_stack_names, &num_stacks);
14754 		if (err) {
14755 			printf("Failed to register %s stack name for "
14756 			    "%s module\n", bbr_stack_names[num_stacks],
14757 			    __XSTRING(MODNAME));
14758 			sysctl_ctx_free(&bbr_sysctl_ctx);
14759 	free_uma:
14760 			uma_zdestroy(bbr_zone);
14761 			uma_zdestroy(bbr_pcb_zone);
14762 			bbr_counter_destroy();
14763 			printf("Failed to register " __XSTRING(MODNAME)
14764 			    " module err:%d\n", err);
14765 			return (err);
14766 		}
14767 		tcp_lro_reg_mbufq();
14768 		bbr_mod_inited = true;
14769 		printf(__XSTRING(MODNAME) " is now available\n");
14770 		break;
14771 	case MOD_QUIESCE:
14772 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14773 		break;
14774 	case MOD_UNLOAD:
14775 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14776 		if (err == EBUSY)
14777 			break;
14778 		if (bbr_mod_inited) {
14779 			uma_zdestroy(bbr_zone);
14780 			uma_zdestroy(bbr_pcb_zone);
14781 			sysctl_ctx_free(&bbr_sysctl_ctx);
14782 			bbr_counter_destroy();
14783 			printf(__XSTRING(MODNAME)
14784 			    " is now no longer available\n");
14785 			bbr_mod_inited = false;
14786 		}
14787 		tcp_lro_dereg_mbufq();
14788 		err = 0;
14789 		break;
14790 	default:
14791 		return (EOPNOTSUPP);
14792 	}
14793 	return (err);
14794 }
14795 
14796 static moduledata_t tcp_bbr = {
14797 	.name = __XSTRING(MODNAME),
14798 	    .evhand = tcp_addbbr,
14799 	    .priv = 0
14800 };
14801 
14802 MODULE_VERSION(MODNAME, 1);
14803 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14804 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14805