xref: /freebsd/sys/netinet/tcp_stacks/bbr.c (revision 3b68c491d37196bb76a95bce3c02f7c6d5ba22fd)
1 /*-
2  * Copyright (c) 2016-2020 Netflix, Inc.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  */
26 /**
27  * Author: Randall Stewart <rrs@netflix.com>
28  * This work is based on the ACM Queue paper
29  * BBR - Congestion Based Congestion Control
30  * and also numerous discussions with Neal, Yuchung and Van.
31  */
32 
33 #include <sys/cdefs.h>
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_ratelimit.h"
38 #include <sys/param.h>
39 #include <sys/arb.h>
40 #include <sys/module.h>
41 #include <sys/kernel.h>
42 #include <sys/libkern.h>
43 #ifdef TCP_HHOOK
44 #include <sys/hhook.h>
45 #endif
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/proc.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #ifdef STATS
54 #include <sys/qmath.h>
55 #include <sys/tree.h>
56 #include <sys/stats.h> /* Must come after qmath.h and tree.h */
57 #endif
58 #include <sys/refcount.h>
59 #include <sys/queue.h>
60 #include <sys/eventhandler.h>
61 #include <sys/smp.h>
62 #include <sys/kthread.h>
63 #include <sys/lock.h>
64 #include <sys/mutex.h>
65 #include <sys/tim_filter.h>
66 #include <sys/time.h>
67 #include <sys/protosw.h>
68 #include <vm/uma.h>
69 #include <sys/kern_prefetch.h>
70 
71 #include <net/route.h>
72 #include <net/route/nhop.h>
73 #include <net/vnet.h>
74 
75 #define TCPSTATES		/* for logging */
76 
77 #include <netinet/in.h>
78 #include <netinet/in_kdtrace.h>
79 #include <netinet/in_pcb.h>
80 #include <netinet/ip.h>
81 #include <netinet/ip_icmp.h>	/* required for icmp_var.h */
82 #include <netinet/icmp_var.h>	/* for ICMP_BANDLIM */
83 #include <netinet/ip_var.h>
84 #include <netinet/ip6.h>
85 #include <netinet6/in6_pcb.h>
86 #include <netinet6/ip6_var.h>
87 #define	TCPOUTFLAGS
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/tcpip.h>
94 #include <netinet/tcp_hpts.h>
95 #include <netinet/cc/cc.h>
96 #include <netinet/tcp_log_buf.h>
97 #include <netinet/tcp_ratelimit.h>
98 #include <netinet/tcp_lro.h>
99 #ifdef TCP_OFFLOAD
100 #include <netinet/tcp_offload.h>
101 #endif
102 #ifdef INET6
103 #include <netinet6/tcp6_var.h>
104 #endif
105 #include <netinet/tcp_fastopen.h>
106 
107 #include <netipsec/ipsec_support.h>
108 #include <net/if.h>
109 #include <net/if_var.h>
110 #include <net/ethernet.h>
111 
112 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
113 #include <netipsec/ipsec.h>
114 #include <netipsec/ipsec6.h>
115 #endif				/* IPSEC */
116 
117 #include <netinet/udp.h>
118 #include <netinet/udp_var.h>
119 #include <machine/in_cksum.h>
120 
121 #ifdef MAC
122 #include <security/mac/mac_framework.h>
123 #endif
124 
125 #include "sack_filter.h"
126 #include "tcp_bbr.h"
127 #include "rack_bbr_common.h"
128 uma_zone_t bbr_zone;
129 uma_zone_t bbr_pcb_zone;
130 
131 struct sysctl_ctx_list bbr_sysctl_ctx;
132 struct sysctl_oid *bbr_sysctl_root;
133 
134 #define	TCPT_RANGESET_NOSLOP(tv, value, tvmin, tvmax) do { \
135 	(tv) = (value); \
136 	if ((u_long)(tv) < (u_long)(tvmin)) \
137 		(tv) = (tvmin); \
138 	if ((u_long)(tv) > (u_long)(tvmax)) \
139 		(tv) = (tvmax); \
140 } while(0)
141 
142 /*#define BBR_INVARIANT 1*/
143 
144 /*
145  * initial window
146  */
147 static uint32_t bbr_def_init_win = 10;
148 static int32_t bbr_persist_min = 250000;	/* 250ms */
149 static int32_t bbr_persist_max = 1000000;	/* 1 Second */
150 static int32_t bbr_cwnd_may_shrink = 0;
151 static int32_t bbr_cwndtarget_rtt_touse = BBR_RTT_PROP;
152 static int32_t bbr_num_pktepo_for_del_limit = BBR_NUM_RTTS_FOR_DEL_LIMIT;
153 static int32_t bbr_hardware_pacing_limit = 8000;
154 static int32_t bbr_quanta = 3;	/* How much extra quanta do we get? */
155 static int32_t bbr_no_retran = 0;
156 
157 static int32_t bbr_error_base_paceout = 10000; /* usec to pace */
158 static int32_t bbr_max_net_error_cnt = 10;
159 /* Should the following be dynamic too -- loss wise */
160 static int32_t bbr_rtt_gain_thresh = 0;
161 /* Measurement controls */
162 static int32_t bbr_use_google_algo = 1;
163 static int32_t bbr_ts_limiting = 1;
164 static int32_t bbr_ts_can_raise = 0;
165 static int32_t bbr_do_red = 600;
166 static int32_t bbr_red_scale = 20000;
167 static int32_t bbr_red_mul = 1;
168 static int32_t bbr_red_div = 2;
169 static int32_t bbr_red_growth_restrict = 1;
170 static int32_t  bbr_target_is_bbunit = 0;
171 static int32_t bbr_drop_limit = 0;
172 /*
173  * How much gain do we need to see to
174  * stay in startup?
175  */
176 static int32_t bbr_marks_rxt_sack_passed = 0;
177 static int32_t bbr_start_exit = 25;
178 static int32_t bbr_low_start_exit = 25;	/* When we are in reduced gain */
179 static int32_t bbr_startup_loss_thresh = 2000;	/* 20.00% loss */
180 static int32_t bbr_hptsi_max_mul = 1;	/* These two mul/div assure a min pacing */
181 static int32_t bbr_hptsi_max_div = 2;	/* time, 0 means turned off. We need this
182 					 * if we go back ever to where the pacer
183 					 * has priority over timers.
184 					 */
185 static int32_t bbr_policer_call_from_rack_to = 0;
186 static int32_t bbr_policer_detection_enabled = 1;
187 static int32_t bbr_min_measurements_req = 1;	/* We need at least 2
188 						 * measurements before we are
189 						 * "good" note that 2 == 1.
190 						 * This is because we use a >
191 						 * comparison. This means if
192 						 * min_measure was 0, it takes
193 						 * num-measures > min(0) and
194 						 * you get 1 measurement and
195 						 * you are good. Set to 1, you
196 						 * have to have two
197 						 * measurements (this is done
198 						 * to prevent it from being ok
199 						 * to have no measurements). */
200 static int32_t bbr_no_pacing_until = 4;
201 
202 static int32_t bbr_min_usec_delta = 20000;	/* 20,000 usecs */
203 static int32_t bbr_min_peer_delta = 20;		/* 20 units */
204 static int32_t bbr_delta_percent = 150;		/* 15.0 % */
205 
206 static int32_t bbr_target_cwnd_mult_limit = 8;
207 /*
208  * bbr_cwnd_min_val is the number of
209  * segments we hold to in the RTT probe
210  * state typically 4.
211  */
212 static int32_t bbr_cwnd_min_val = BBR_PROBERTT_NUM_MSS;
213 
214 static int32_t bbr_cwnd_min_val_hs = BBR_HIGHSPEED_NUM_MSS;
215 
216 static int32_t bbr_gain_to_target = 1;
217 static int32_t bbr_gain_gets_extra_too = 1;
218 /*
219  * bbr_high_gain is the 2/ln(2) value we need
220  * to double the sending rate in startup. This
221  * is used for both cwnd and hptsi gain's.
222  */
223 static int32_t bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
224 static int32_t bbr_startup_lower = BBR_UNIT * 1500 / 1000 + 1;
225 static int32_t bbr_use_lower_gain_in_startup = 1;
226 
227 /* thresholds for reduction on drain in sub-states/drain */
228 static int32_t bbr_drain_rtt = BBR_SRTT;
229 static int32_t bbr_drain_floor = 88;
230 static int32_t google_allow_early_out = 1;
231 static int32_t google_consider_lost = 1;
232 static int32_t bbr_drain_drop_mul = 4;
233 static int32_t bbr_drain_drop_div = 5;
234 static int32_t bbr_rand_ot = 50;
235 static int32_t bbr_can_force_probertt = 0;
236 static int32_t bbr_can_adjust_probertt = 1;
237 static int32_t bbr_probertt_sets_rtt = 0;
238 static int32_t bbr_can_use_ts_for_rtt = 1;
239 static int32_t bbr_is_ratio = 0;
240 static int32_t bbr_sub_drain_app_limit = 1;
241 static int32_t bbr_prtt_slam_cwnd = 1;
242 static int32_t bbr_sub_drain_slam_cwnd = 1;
243 static int32_t bbr_slam_cwnd_in_main_drain = 1;
244 static int32_t bbr_filter_len_sec = 6;	/* How long does the rttProp filter
245 					 * hold */
246 static uint32_t bbr_rtt_probe_limit = (USECS_IN_SECOND * 4);
247 /*
248  * bbr_drain_gain is the reverse of the high_gain
249  * designed to drain back out the standing queue
250  * that is formed in startup by causing a larger
251  * hptsi gain and thus drainging the packets
252  * in flight.
253  */
254 static int32_t bbr_drain_gain = BBR_UNIT * 1000 / 2885;
255 static int32_t bbr_rttprobe_gain = 192;
256 
257 /*
258  * The cwnd_gain is the default cwnd gain applied when
259  * calculating a target cwnd. Note that the cwnd is
260  * a secondary factor in the way BBR works (see the
261  * paper and think about it, it will take some time).
262  * Basically the hptsi_gain spreads the packets out
263  * so you never get more than BDP to the peer even
264  * if the cwnd is high. In our implemenation that
265  * means in non-recovery/retransmission scenarios
266  * cwnd will never be reached by the flight-size.
267  */
268 static int32_t bbr_cwnd_gain = BBR_UNIT * 2;
269 static int32_t bbr_tlp_type_to_use = BBR_SRTT;
270 static int32_t bbr_delack_time = 100000;	/* 100ms in useconds */
271 static int32_t bbr_sack_not_required = 0;	/* set to one to allow non-sack to use bbr */
272 static int32_t bbr_initial_bw_bps = 62500;	/* 500kbps in bytes ps */
273 static int32_t bbr_ignore_data_after_close = 1;
274 static int16_t bbr_hptsi_gain[] = {
275 	(BBR_UNIT *5 / 4),
276 	(BBR_UNIT * 3 / 4),
277 	BBR_UNIT,
278 	BBR_UNIT,
279 	BBR_UNIT,
280 	BBR_UNIT,
281 	BBR_UNIT,
282 	BBR_UNIT
283 };
284 int32_t bbr_use_rack_resend_cheat = 1;
285 int32_t bbr_sends_full_iwnd = 1;
286 
287 #define BBR_HPTSI_GAIN_MAX 8
288 /*
289  * The BBR module incorporates a number of
290  * TCP ideas that have been put out into the IETF
291  * over the last few years:
292  * - Yuchung Cheng's RACK TCP (for which its named) that
293  *    will stop us using the number of dup acks and instead
294  *    use time as the gage of when we retransmit.
295  * - Reorder Detection of RFC4737 and the Tail-Loss probe draft
296  *    of Dukkipati et.al.
297  * - Van Jacobson's et.al BBR.
298  *
299  * RACK depends on SACK, so if an endpoint arrives that
300  * cannot do SACK the state machine below will shuttle the
301  * connection back to using the "default" TCP stack that is
302  * in FreeBSD.
303  *
304  * To implement BBR and RACK the original TCP stack was first decomposed
305  * into a functional state machine with individual states
306  * for each of the possible TCP connection states. The do_segment
307  * functions role in life is to mandate the connection supports SACK
308  * initially and then assure that the RACK state matches the conenction
309  * state before calling the states do_segment function. Data processing
310  * of inbound segments also now happens in the hpts_do_segment in general
311  * with only one exception. This is so we can keep the connection on
312  * a single CPU.
313  *
314  * Each state is simplified due to the fact that the original do_segment
315  * has been decomposed and we *know* what state we are in (no
316  * switches on the state) and all tests for SACK are gone. This
317  * greatly simplifies what each state does.
318  *
319  * TCP output is also over-written with a new version since it
320  * must maintain the new rack scoreboard and has had hptsi
321  * integrated as a requirment. Still todo is to eliminate the
322  * use of the callout_() system and use the hpts for all
323  * timers as well.
324  */
325 static uint32_t bbr_rtt_probe_time = 200000;	/* 200ms in micro seconds */
326 static uint32_t bbr_rtt_probe_cwndtarg = 4;	/* How many mss's outstanding */
327 static const int32_t bbr_min_req_free = 2;	/* The min we must have on the
328 						 * free list */
329 static int32_t bbr_tlp_thresh = 1;
330 static int32_t bbr_reorder_thresh = 2;
331 static int32_t bbr_reorder_fade = 60000000;	/* 0 - never fade, def
332 						 * 60,000,000 - 60 seconds */
333 static int32_t bbr_pkt_delay = 1000;
334 static int32_t bbr_min_to = 1000;	/* Number of usec's minimum timeout */
335 static int32_t bbr_incr_timers = 1;
336 
337 static int32_t bbr_tlp_min = 10000;	/* 10ms in usecs */
338 static int32_t bbr_delayed_ack_time = 200000;	/* 200ms in usecs */
339 static int32_t bbr_exit_startup_at_loss = 1;
340 
341 /*
342  * bbr_lt_bw_ratio is 1/8th
343  * bbr_lt_bw_diff is  < 4 Kbit/sec
344  */
345 static uint64_t bbr_lt_bw_diff = 4000 / 8;	/* In bytes per second */
346 static uint64_t bbr_lt_bw_ratio = 8;	/* For 1/8th */
347 static uint32_t bbr_lt_bw_max_rtts = 48;	/* How many rtt's do we use
348 						 * the lt_bw for */
349 static uint32_t bbr_lt_intvl_min_rtts = 4;	/* Min num of RTT's to measure
350 						 * lt_bw */
351 static int32_t bbr_lt_intvl_fp = 0;		/* False positive epoch diff */
352 static int32_t bbr_lt_loss_thresh = 196;	/* Lost vs delivered % */
353 static int32_t bbr_lt_fd_thresh = 100;		/* false detection % */
354 
355 static int32_t bbr_verbose_logging = 0;
356 /*
357  * Currently regular tcp has a rto_min of 30ms
358  * the backoff goes 12 times so that ends up
359  * being a total of 122.850 seconds before a
360  * connection is killed.
361  */
362 static int32_t bbr_rto_min_ms = 30;	/* 30ms same as main freebsd */
363 static int32_t bbr_rto_max_sec = 4;	/* 4 seconds */
364 
365 /****************************************************/
366 /* DEFAULT TSO SIZING  (cpu performance impacting)  */
367 /****************************************************/
368 /* What amount is our formula using to get TSO size */
369 static int32_t bbr_hptsi_per_second = 1000;
370 
371 /*
372  * For hptsi under bbr_cross_over connections what is delay
373  * target 7ms (in usec) combined with a seg_max of 2
374  * gets us close to identical google behavior in
375  * TSO size selection (possibly more 1MSS sends).
376  */
377 static int32_t bbr_hptsi_segments_delay_tar = 7000;
378 
379 /* Does pacing delay include overhead's in its time calculations? */
380 static int32_t bbr_include_enet_oh = 0;
381 static int32_t bbr_include_ip_oh = 1;
382 static int32_t bbr_include_tcp_oh = 1;
383 static int32_t bbr_google_discount = 10;
384 
385 /* Do we use (nf mode) pkt-epoch to drive us or rttProp? */
386 static int32_t bbr_state_is_pkt_epoch = 0;
387 static int32_t bbr_state_drain_2_tar = 1;
388 /* What is the max the 0 - bbr_cross_over MBPS TSO target
389  * can reach using our delay target. Note that this
390  * value becomes the floor for the cross over
391  * algorithm.
392  */
393 static int32_t bbr_hptsi_segments_max = 2;
394 static int32_t bbr_hptsi_segments_floor = 1;
395 static int32_t bbr_hptsi_utter_max = 0;
396 
397 /* What is the min the 0 - bbr_cross-over MBPS  TSO target can be */
398 static int32_t bbr_hptsi_bytes_min = 1460;
399 static int32_t bbr_all_get_min = 0;
400 
401 /* Cross over point from algo-a to algo-b */
402 static uint32_t bbr_cross_over = TWENTY_THREE_MBPS;
403 
404 /* Do we deal with our restart state? */
405 static int32_t bbr_uses_idle_restart = 0;
406 static int32_t bbr_idle_restart_threshold = 100000;	/* 100ms in useconds */
407 
408 /* Do we allow hardware pacing? */
409 static int32_t bbr_allow_hdwr_pacing = 0;
410 static int32_t bbr_hdwr_pace_adjust = 2;	/* multipler when we calc the tso size */
411 static int32_t bbr_hdwr_pace_floor = 1;
412 static int32_t bbr_hdwr_pacing_delay_cnt = 10;
413 
414 /****************************************************/
415 static int32_t bbr_resends_use_tso = 0;
416 static int32_t bbr_tlp_max_resend = 2;
417 static int32_t bbr_sack_block_limit = 128;
418 
419 #define  BBR_MAX_STAT 19
420 counter_u64_t bbr_state_time[BBR_MAX_STAT];
421 counter_u64_t bbr_state_lost[BBR_MAX_STAT];
422 counter_u64_t bbr_state_resend[BBR_MAX_STAT];
423 counter_u64_t bbr_stat_arry[BBR_STAT_SIZE];
424 counter_u64_t bbr_opts_arry[BBR_OPTS_SIZE];
425 counter_u64_t bbr_out_size[TCP_MSS_ACCT_SIZE];
426 counter_u64_t bbr_flows_whdwr_pacing;
427 counter_u64_t bbr_flows_nohdwr_pacing;
428 
429 counter_u64_t bbr_nohdwr_pacing_enobuf;
430 counter_u64_t bbr_hdwr_pacing_enobuf;
431 
432 static inline uint64_t bbr_get_bw(struct tcp_bbr *bbr);
433 
434 /*
435  * Static defintions we need for forward declarations.
436  */
437 static uint32_t
438 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain,
439 		      uint32_t useconds_time, uint64_t bw);
440 static uint32_t
441 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain);
442 static void
443 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win);
444 static void
445 bbr_set_probebw_gains(struct tcp_bbr *bbr,  uint32_t cts, uint32_t losses);
446 static void
447 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int line,
448 		    int dolog);
449 static uint32_t
450 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain);
451 static void
452 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch,
453 		 int32_t pkt_epoch, uint32_t losses);
454 static uint32_t
455 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts,
456 		     struct bbr_sendmap *rsm);
457 static uint32_t
458 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp);
459 static uint32_t
460 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
461 		    struct bbr_sendmap *rsm, uint32_t srtt, uint32_t cts);
462 static void
463 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
464 		 int32_t line);
465 static void
466 bbr_set_state_target(struct tcp_bbr *bbr, int line);
467 static void
468 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line);
469 static void
470 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick,
471 		       int event, int line);
472 static void
473 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts);
474 static void
475 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts);
476 static void
477 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
478 		    uint32_t rtt, uint32_t line, uint8_t is_start,
479 		    uint16_t set);
480 static struct bbr_sendmap *
481 bbr_find_lowest_rsm(struct tcp_bbr *bbr);
482 static __inline uint32_t
483 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type);
484 static void
485 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot,
486 		 uint8_t which);
487 static void
488 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts,
489 		  uint32_t time_since_sent, uint32_t srtt,
490 		  uint32_t thresh, uint32_t to);
491 static void
492 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag);
493 static void
494 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot,
495 		    uint32_t del_by, uint32_t cts, uint32_t sloton,
496 		    uint32_t prev_delay);
497 static void
498 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts,
499 		  int32_t line);
500 static void
501 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr);
502 static void
503 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts);
504 static void
505 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts);
506 static void
507 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts);
508 static void
509 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
510 			  uint32_t cts, uint32_t usecs, uint64_t bw,
511 			  uint32_t override, int mod);
512 static int bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt);
513 
514 static inline uint8_t
515 bbr_state_val(struct tcp_bbr *bbr)
516 {
517 	return(bbr->rc_bbr_substate);
518 }
519 
520 static inline uint32_t
521 get_min_cwnd(struct tcp_bbr *bbr)
522 {
523 	int mss;
524 
525 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
526 		  bbr->r_ctl.rc_pace_max_segs);
527 	if (bbr_get_rtt(bbr, BBR_RTT_PROP) < BBR_HIGH_SPEED)
528 		return (bbr_cwnd_min_val_hs * mss);
529 	else
530 		return (bbr_cwnd_min_val * mss);
531 }
532 
533 static uint32_t
534 bbr_get_persists_timer_val(struct tcpcb *tp, struct tcp_bbr *bbr)
535 {
536 	uint64_t srtt, var;
537 	uint64_t ret_val;
538 
539 	bbr->r_ctl.rc_hpts_flags |= PACE_TMR_PERSIT;
540 	if (tp->t_srtt == 0) {
541 		srtt = (uint64_t)BBR_INITIAL_RTO;
542 		var = 0;
543 	} else {
544 		srtt = ((uint64_t)TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
545 		var = ((uint64_t)TICKS_2_USEC(tp->t_rttvar) >> TCP_RTT_SHIFT);
546 	}
547 	TCPT_RANGESET_NOSLOP(ret_val, ((srtt + var) * tcp_backoff[tp->t_rxtshift]),
548 	    bbr_persist_min, bbr_persist_max);
549 	return ((uint32_t)ret_val);
550 }
551 
552 static uint32_t
553 bbr_timer_start(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
554 {
555 	/*
556 	 * Start the FR timer, we do this based on getting the first one in
557 	 * the rc_tmap. Note that if its NULL we must stop the timer. in all
558 	 * events we need to stop the running timer (if its running) before
559 	 * starting the new one.
560 	 */
561 	uint32_t thresh, exp, to, srtt, time_since_sent, tstmp_touse;
562 	int32_t idx;
563 	int32_t is_tlp_timer = 0;
564 	struct bbr_sendmap *rsm;
565 
566 	if (bbr->rc_all_timers_stopped) {
567 		/* All timers have been stopped none are to run */
568 		return (0);
569 	}
570 	if (bbr->rc_in_persist) {
571 		/* We can't start any timer in persists */
572 		return (bbr_get_persists_timer_val(tp, bbr));
573 	}
574 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
575 	if ((rsm == NULL) ||
576 	    ((tp->t_flags & TF_SACK_PERMIT) == 0) ||
577 	    (tp->t_state < TCPS_ESTABLISHED)) {
578 		/* Nothing on the send map */
579 activate_rxt:
580 		if (SEQ_LT(tp->snd_una, tp->snd_max) ||
581 		    sbavail(&tptosocket(tp)->so_snd)) {
582 			uint64_t tov;
583 
584 			time_since_sent = 0;
585 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
586 			if (rsm) {
587 				idx = rsm->r_rtr_cnt - 1;
588 				if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
589 					tstmp_touse = rsm->r_tim_lastsent[idx];
590 				else
591 					tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
592 				if (TSTMP_GT(tstmp_touse, cts))
593 				    time_since_sent = cts - tstmp_touse;
594 			}
595 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RXT;
596 			if (tp->t_srtt == 0)
597 				tov = BBR_INITIAL_RTO;
598 			else
599 				tov = ((uint64_t)(TICKS_2_USEC(tp->t_srtt) +
600 				    ((uint64_t)TICKS_2_USEC(tp->t_rttvar) * (uint64_t)4)) >> TCP_RTT_SHIFT);
601 			if (tp->t_rxtshift)
602 				tov *= tcp_backoff[tp->t_rxtshift];
603 			if (tov > time_since_sent)
604 				tov -= time_since_sent;
605 			else
606 				tov = bbr->r_ctl.rc_min_to;
607 			TCPT_RANGESET_NOSLOP(to, tov,
608 			    (bbr->r_ctl.rc_min_rto_ms * MS_IN_USEC),
609 			    (bbr->rc_max_rto_sec * USECS_IN_SECOND));
610 			bbr_log_timer_var(bbr, 2, cts, 0, srtt, 0, to);
611 			return (to);
612 		}
613 		return (0);
614 	}
615 	if (rsm->r_flags & BBR_ACKED) {
616 		rsm = bbr_find_lowest_rsm(bbr);
617 		if (rsm == NULL) {
618 			/* No lowest? */
619 			goto activate_rxt;
620 		}
621 	}
622 	/* Convert from ms to usecs */
623 	if (rsm->r_flags & BBR_SACK_PASSED) {
624 		if ((tp->t_flags & TF_SENTFIN) &&
625 		    ((tp->snd_max - tp->snd_una) == 1) &&
626 		    (rsm->r_flags & BBR_HAS_FIN)) {
627 			/*
628 			 * We don't start a bbr rack timer if all we have is
629 			 * a FIN outstanding.
630 			 */
631 			goto activate_rxt;
632 		}
633 		srtt = bbr_get_rtt(bbr, BBR_RTT_RACK);
634 		thresh = bbr_calc_thresh_rack(bbr, srtt, cts, rsm);
635 		idx = rsm->r_rtr_cnt - 1;
636 		exp = rsm->r_tim_lastsent[idx] + thresh;
637 		if (SEQ_GEQ(exp, cts)) {
638 			to = exp - cts;
639 			if (to < bbr->r_ctl.rc_min_to) {
640 				to = bbr->r_ctl.rc_min_to;
641 			}
642 		} else {
643 			to = bbr->r_ctl.rc_min_to;
644 		}
645 	} else {
646 		/* Ok we need to do a TLP not RACK */
647 		if (bbr->rc_tlp_in_progress != 0) {
648 			/*
649 			 * The previous send was a TLP.
650 			 */
651 			goto activate_rxt;
652 		}
653 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_tmap, bbr_sendmap, r_tnext);
654 		if (rsm == NULL) {
655 			/* We found no rsm to TLP with. */
656 			goto activate_rxt;
657 		}
658 		if (rsm->r_flags & BBR_HAS_FIN) {
659 			/* If its a FIN we don't do TLP */
660 			rsm = NULL;
661 			goto activate_rxt;
662 		}
663 		time_since_sent = 0;
664 		idx = rsm->r_rtr_cnt - 1;
665 		if (TSTMP_GEQ(rsm->r_tim_lastsent[idx], bbr->r_ctl.rc_tlp_rxt_last_time))
666 			tstmp_touse = rsm->r_tim_lastsent[idx];
667 		else
668 			tstmp_touse = bbr->r_ctl.rc_tlp_rxt_last_time;
669 		if (TSTMP_GT(tstmp_touse, cts))
670 		    time_since_sent = cts - tstmp_touse;
671 		is_tlp_timer = 1;
672 		srtt = bbr_get_rtt(bbr, bbr_tlp_type_to_use);
673 		thresh = bbr_calc_thresh_tlp(tp, bbr, rsm, srtt, cts);
674 		if (thresh > time_since_sent)
675 			to = thresh - time_since_sent;
676 		else
677 			to = bbr->r_ctl.rc_min_to;
678 		if (to > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
679 			/*
680 			 * If the TLP time works out to larger than the max
681 			 * RTO lets not do TLP.. just RTO.
682 			 */
683 			goto activate_rxt;
684 		}
685 		if ((bbr->rc_tlp_rtx_out == 1) &&
686 		    (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq)) {
687 			/*
688 			 * Second retransmit of the same TLP
689 			 * lets not.
690 			 */
691 			bbr->rc_tlp_rtx_out = 0;
692 			goto activate_rxt;
693 		}
694 		if (rsm->r_start != bbr->r_ctl.rc_last_tlp_seq) {
695 			/*
696 			 * The tail is no longer the last one I did a probe
697 			 * on
698 			 */
699 			bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
700 			bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
701 		}
702 	}
703 	if (is_tlp_timer == 0) {
704 		BBR_STAT_INC(bbr_to_arm_rack);
705 		bbr->r_ctl.rc_hpts_flags |= PACE_TMR_RACK;
706 	} else {
707 		bbr_log_timer_var(bbr, 1, cts, time_since_sent, srtt, thresh, to);
708 		if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
709 			/*
710 			 * We have exceeded how many times we can retran the
711 			 * current TLP timer, switch to the RTO timer.
712 			 */
713 			goto activate_rxt;
714 		} else {
715 			BBR_STAT_INC(bbr_to_arm_tlp);
716 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_TLP;
717 		}
718 	}
719 	return (to);
720 }
721 
722 static inline int32_t
723 bbr_minseg(struct tcp_bbr *bbr)
724 {
725 	return (bbr->r_ctl.rc_pace_min_segs - bbr->rc_last_options);
726 }
727 
728 static void
729 bbr_start_hpts_timer(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts, int32_t frm, int32_t slot, uint32_t tot_len)
730 {
731 	struct inpcb *inp = tptoinpcb(tp);
732 	struct hpts_diag diag;
733 	uint32_t delayed_ack = 0;
734 	uint32_t left = 0;
735 	uint32_t hpts_timeout;
736 	uint8_t stopped;
737 	int32_t delay_calc = 0;
738 	uint32_t prev_delay = 0;
739 
740 	if (tcp_in_hpts(tp)) {
741 		/* A previous call is already set up */
742 		return;
743 	}
744 	if ((tp->t_state == TCPS_CLOSED) ||
745 	    (tp->t_state == TCPS_LISTEN)) {
746 		return;
747 	}
748 	stopped = bbr->rc_tmr_stopped;
749 	if (stopped && TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
750 		left = bbr->r_ctl.rc_timer_exp - cts;
751 	}
752 	bbr->r_ctl.rc_hpts_flags = 0;
753 	bbr->r_ctl.rc_timer_exp = 0;
754 	prev_delay = bbr->r_ctl.rc_last_delay_val;
755 	if (bbr->r_ctl.rc_last_delay_val &&
756 	    (slot == 0)) {
757 		/*
758 		 * If a previous pacer delay was in place we
759 		 * are not coming from the output side (where
760 		 * we calculate a delay, more likely a timer).
761 		 */
762 		slot = bbr->r_ctl.rc_last_delay_val;
763 		if (TSTMP_GT(cts, bbr->rc_pacer_started)) {
764 			/* Compensate for time passed  */
765 			delay_calc = cts - bbr->rc_pacer_started;
766 			if (delay_calc <= slot)
767 				slot -= delay_calc;
768 		}
769 	}
770 	/* Do we have early to make up for by pushing out the pacing time? */
771 	if (bbr->r_agg_early_set) {
772 		bbr_log_pacing_delay_calc(bbr, 0, bbr->r_ctl.rc_agg_early, cts, slot, 0, bbr->r_agg_early_set, 2);
773 		slot += bbr->r_ctl.rc_agg_early;
774 		bbr->r_ctl.rc_agg_early = 0;
775 		bbr->r_agg_early_set = 0;
776 	}
777 	/* Are we running a total debt that needs to be compensated for? */
778 	if (bbr->r_ctl.rc_hptsi_agg_delay) {
779 		if (slot > bbr->r_ctl.rc_hptsi_agg_delay) {
780 			/* We nuke the delay */
781 			slot -= bbr->r_ctl.rc_hptsi_agg_delay;
782 			bbr->r_ctl.rc_hptsi_agg_delay = 0;
783 		} else {
784 			/* We nuke some of the delay, put in a minimal 100usecs  */
785 			bbr->r_ctl.rc_hptsi_agg_delay -= slot;
786 			bbr->r_ctl.rc_last_delay_val = slot = 100;
787 		}
788 	}
789 	bbr->r_ctl.rc_last_delay_val = slot;
790 	hpts_timeout = bbr_timer_start(tp, bbr, cts);
791 	if (tp->t_flags & TF_DELACK) {
792 		if (bbr->rc_in_persist == 0) {
793 			delayed_ack = bbr_delack_time;
794 		} else {
795 			/*
796 			 * We are in persists and have
797 			 * gotten a new data element.
798 			 */
799 			if (hpts_timeout > bbr_delack_time) {
800 				/*
801 				 * Lets make the persists timer (which acks)
802 				 * be the smaller of hpts_timeout and bbr_delack_time.
803 				 */
804 				hpts_timeout = bbr_delack_time;
805 			}
806 		}
807 	}
808 	if (delayed_ack &&
809 	    ((hpts_timeout == 0) ||
810 	     (delayed_ack < hpts_timeout))) {
811 		/* We need a Delayed ack timer */
812 		bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
813 		hpts_timeout = delayed_ack;
814 	}
815 	if (slot) {
816 		/* Mark that we have a pacing timer up */
817 		BBR_STAT_INC(bbr_paced_segments);
818 		bbr->r_ctl.rc_hpts_flags |= PACE_PKT_OUTPUT;
819 	}
820 	/*
821 	 * If no timers are going to run and we will fall off thfe hptsi
822 	 * wheel, we resort to a keep-alive timer if its configured.
823 	 */
824 	if ((hpts_timeout == 0) &&
825 	    (slot == 0)) {
826 		if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
827 		    (tp->t_state <= TCPS_CLOSING)) {
828 			/*
829 			 * Ok we have no timer (persists, rack, tlp, rxt  or
830 			 * del-ack), we don't have segments being paced. So
831 			 * all that is left is the keepalive timer.
832 			 */
833 			if (TCPS_HAVEESTABLISHED(tp->t_state)) {
834 				hpts_timeout = TICKS_2_USEC(TP_KEEPIDLE(tp));
835 			} else {
836 				hpts_timeout = TICKS_2_USEC(TP_KEEPINIT(tp));
837 			}
838 			bbr->r_ctl.rc_hpts_flags |= PACE_TMR_KEEP;
839 		}
840 	}
841 	if (left && (stopped & (PACE_TMR_KEEP | PACE_TMR_DELACK)) ==
842 	    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK)) {
843 		/*
844 		 * RACK, TLP, persists and RXT timers all are restartable
845 		 * based on actions input .. i.e we received a packet (ack
846 		 * or sack) and that changes things (rw, or snd_una etc).
847 		 * Thus we can restart them with a new value. For
848 		 * keep-alive, delayed_ack we keep track of what was left
849 		 * and restart the timer with a smaller value.
850 		 */
851 		if (left < hpts_timeout)
852 			hpts_timeout = left;
853 	}
854 	if (bbr->r_ctl.rc_incr_tmrs && slot &&
855 	    (bbr->r_ctl.rc_hpts_flags & (PACE_TMR_TLP|PACE_TMR_RXT))) {
856 		/*
857 		 * If configured to do so, and the timer is either
858 		 * the TLP or RXT timer, we need to increase the timeout
859 		 * by the pacing time. Consider the bottleneck at my
860 		 * machine as an example, we are sending something
861 		 * to start a TLP on. The last packet won't be emitted
862 		 * fully until the pacing time (the bottleneck will hold
863 		 * the data in place). Once the packet is emitted that
864 		 * is when we want to start waiting for the TLP. This
865 		 * is most evident with hardware pacing (where the nic
866 		 * is holding the packet(s) before emitting). But it
867 		 * can also show up in the network so we do it for all
868 		 * cases. Technically we would take off one packet from
869 		 * this extra delay but this is easier and being more
870 		 * conservative is probably better.
871 		 */
872 		hpts_timeout += slot;
873 	}
874 	if (hpts_timeout) {
875 		/*
876 		 * Hack alert for now we can't time-out over 2147 seconds (a
877 		 * bit more than 35min)
878 		 */
879 		if (hpts_timeout > 0x7ffffffe)
880 			hpts_timeout = 0x7ffffffe;
881 		bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
882 	} else
883 		bbr->r_ctl.rc_timer_exp = 0;
884 	if ((slot) &&
885 	    (bbr->rc_use_google ||
886 	     bbr->output_error_seen ||
887 	     (slot <= hpts_timeout))  ) {
888 		/*
889 		 * Tell LRO that it can queue packets while
890 		 * we pace.
891 		 */
892 		bbr->rc_tp->t_flags2 |= TF2_MBUF_QUEUE_READY;
893 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
894 		    (bbr->rc_cwnd_limited == 0)) {
895 			/*
896 			 * If we are not cwnd limited and we
897 			 * are running a rack timer we put on
898 			 * the do not disturbe even for sack.
899 			 */
900 			tp->t_flags2 |= TF2_DONT_SACK_QUEUE;
901 		} else
902 			tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
903 		bbr->rc_pacer_started = cts;
904 
905 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(slot),
906 					   __LINE__, &diag);
907 		bbr->rc_timer_first = 0;
908 		bbr->bbr_timer_src = frm;
909 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 1);
910 		bbr_log_hpts_diag(bbr, cts, &diag);
911 	} else if (hpts_timeout) {
912 		(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(hpts_timeout),
913 					   __LINE__, &diag);
914 		/*
915 		 * We add the flag here as well if the slot is set,
916 		 * since hpts will call in to clear the queue first before
917 		 * calling the output routine (which does our timers).
918 		 * We don't want to set the flag if its just a timer
919 		 * else the arrival of data might (that causes us
920 		 * to send more) might get delayed. Imagine being
921 		 * on a keep-alive timer and a request comes in for
922 		 * more data.
923 		 */
924 		if (slot)
925 			bbr->rc_pacer_started = cts;
926 		if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) &&
927 		    (bbr->rc_cwnd_limited == 0)) {
928 			/*
929 			 * For a rack timer, don't wake us even
930 			 * if a sack arrives as long as we are
931 			 * not cwnd limited.
932 			 */
933 			tp->t_flags2 |= (TF2_MBUF_QUEUE_READY |
934 			    TF2_DONT_SACK_QUEUE);
935 		} else {
936 			/* All other timers wake us up */
937 			tp->t_flags2 &= ~(TF2_MBUF_QUEUE_READY |
938 			    TF2_DONT_SACK_QUEUE);
939 		}
940 		bbr->bbr_timer_src = frm;
941 		bbr_log_to_start(bbr, cts, hpts_timeout, slot, 0);
942 		bbr_log_hpts_diag(bbr, cts, &diag);
943 		bbr->rc_timer_first = 1;
944 	}
945 	bbr->rc_tmr_stopped = 0;
946 	bbr_log_type_bbrsnd(bbr, tot_len, slot, delay_calc, cts, frm, prev_delay);
947 }
948 
949 static void
950 bbr_timer_audit(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, struct sockbuf *sb)
951 {
952 	/*
953 	 * We received an ack, and then did not call send or were bounced
954 	 * out due to the hpts was running. Now a timer is up as well, is it
955 	 * the right timer?
956 	 */
957 	struct inpcb *inp;
958 	struct bbr_sendmap *rsm;
959 	uint32_t hpts_timeout;
960 	int tmr_up;
961 
962 	tmr_up = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
963 	if (bbr->rc_in_persist && (tmr_up == PACE_TMR_PERSIT))
964 		return;
965 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
966 	if (((rsm == NULL) || (tp->t_state < TCPS_ESTABLISHED)) &&
967 	    (tmr_up == PACE_TMR_RXT)) {
968 		/* Should be an RXT */
969 		return;
970 	}
971 	inp = bbr->rc_inp;
972 	if (rsm == NULL) {
973 		/* Nothing outstanding? */
974 		if (tp->t_flags & TF_DELACK) {
975 			if (tmr_up == PACE_TMR_DELACK)
976 				/*
977 				 * We are supposed to have delayed ack up
978 				 * and we do
979 				 */
980 				return;
981 		} else if (sbavail(&inp->inp_socket->so_snd) &&
982 		    (tmr_up == PACE_TMR_RXT)) {
983 			/*
984 			 * if we hit enobufs then we would expect the
985 			 * possibility of nothing outstanding and the RXT up
986 			 * (and the hptsi timer).
987 			 */
988 			return;
989 		} else if (((V_tcp_always_keepalive ||
990 			    inp->inp_socket->so_options & SO_KEEPALIVE) &&
991 			    (tp->t_state <= TCPS_CLOSING)) &&
992 			    (tmr_up == PACE_TMR_KEEP) &&
993 		    (tp->snd_max == tp->snd_una)) {
994 			/* We should have keep alive up and we do */
995 			return;
996 		}
997 	}
998 	if (rsm && (rsm->r_flags & BBR_SACK_PASSED)) {
999 		if ((tp->t_flags & TF_SENTFIN) &&
1000 		    ((tp->snd_max - tp->snd_una) == 1) &&
1001 		    (rsm->r_flags & BBR_HAS_FIN)) {
1002 			/* needs to be a RXT */
1003 			if (tmr_up == PACE_TMR_RXT)
1004 				return;
1005 			else
1006 				goto wrong_timer;
1007 		} else if (tmr_up == PACE_TMR_RACK)
1008 			return;
1009 		else
1010 			goto wrong_timer;
1011 	} else if (rsm && (tmr_up == PACE_TMR_RACK)) {
1012 		/* Rack timer has priority if we have data out */
1013 		return;
1014 	} else if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1015 		    ((tmr_up == PACE_TMR_TLP) ||
1016 	    (tmr_up == PACE_TMR_RXT))) {
1017 		/*
1018 		 * Either a TLP or RXT is fine if no sack-passed is in place
1019 		 * and data is outstanding.
1020 		 */
1021 		return;
1022 	} else if (tmr_up == PACE_TMR_DELACK) {
1023 		/*
1024 		 * If the delayed ack was going to go off before the
1025 		 * rtx/tlp/rack timer were going to expire, then that would
1026 		 * be the timer in control. Note we don't check the time
1027 		 * here trusting the code is correct.
1028 		 */
1029 		return;
1030 	}
1031 	if (SEQ_GT(tp->snd_max, tp->snd_una) &&
1032 	    ((tmr_up == PACE_TMR_RXT) ||
1033 	     (tmr_up == PACE_TMR_TLP) ||
1034 	     (tmr_up == PACE_TMR_RACK))) {
1035 		/*
1036 		 * We have outstanding data and
1037 		 * we *do* have a RACK, TLP or RXT
1038 		 * timer running. We won't restart
1039 		 * anything here since thats probably ok we
1040 		 * will get called with some timer here shortly.
1041 		 */
1042 		return;
1043 	}
1044 	/*
1045 	 * Ok the timer originally started is not what we want now. We will
1046 	 * force the hpts to be stopped if any, and restart with the slot
1047 	 * set to what was in the saved slot.
1048 	 */
1049 wrong_timer:
1050 	if ((bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) == 0) {
1051 		if (tcp_in_hpts(tp))
1052 			tcp_hpts_remove(tp);
1053 		bbr_timer_cancel(bbr, __LINE__, cts);
1054 		bbr_start_hpts_timer(bbr, tp, cts, 1, bbr->r_ctl.rc_last_delay_val,
1055 		    0);
1056 	} else {
1057 		/*
1058 		 * Output is hptsi so we just need to switch the type of
1059 		 * timer. We don't bother with keep-alive, since when we
1060 		 * jump through the output, it will start the keep-alive if
1061 		 * nothing is sent.
1062 		 *
1063 		 * We only need a delayed-ack added and or the hpts_timeout.
1064 		 */
1065 		hpts_timeout = bbr_timer_start(tp, bbr, cts);
1066 		if (tp->t_flags & TF_DELACK) {
1067 			if (hpts_timeout == 0) {
1068 				hpts_timeout = bbr_delack_time;
1069 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1070 			}
1071 			else if (hpts_timeout > bbr_delack_time) {
1072 				hpts_timeout = bbr_delack_time;
1073 				bbr->r_ctl.rc_hpts_flags = PACE_TMR_DELACK;
1074 			}
1075 		}
1076 		if (hpts_timeout) {
1077 			if (hpts_timeout > 0x7ffffffe)
1078 				hpts_timeout = 0x7ffffffe;
1079 			bbr->r_ctl.rc_timer_exp = cts + hpts_timeout;
1080 		}
1081 	}
1082 }
1083 
1084 int32_t bbr_clear_lost = 0;
1085 
1086 /*
1087  * Considers the two time values now (cts) and earlier.
1088  * If cts is smaller than earlier, we could have
1089  * had a sequence wrap (our counter wraps every
1090  * 70 min or so) or it could be just clock skew
1091  * getting us two different time values. Clock skew
1092  * will show up within 10ms or so. So in such
1093  * a case (where cts is behind earlier time by
1094  * less than 10ms) we return 0. Otherwise we
1095  * return the true difference between them.
1096  */
1097 static inline uint32_t
1098 bbr_calc_time(uint32_t cts, uint32_t earlier_time) {
1099 	/*
1100 	 * Given two timestamps, the current time stamp cts, and some other
1101 	 * time-stamp taken in theory earlier return the difference. The
1102 	 * trick is here sometimes locking will get the other timestamp
1103 	 * after the cts. If this occurs we need to return 0.
1104 	 */
1105 	if (TSTMP_GEQ(cts, earlier_time))
1106 		return (cts - earlier_time);
1107 	/*
1108 	 * cts is behind earlier_time if its less than 10ms consider it 0.
1109 	 * If its more than 10ms difference then we had a time wrap. Else
1110 	 * its just the normal locking foo. I wonder if we should not go to
1111 	 * 64bit TS and get rid of this issue.
1112 	 */
1113 	if (TSTMP_GEQ((cts + 10000), earlier_time))
1114 		return (0);
1115 	/*
1116 	 * Ok the time must have wrapped. So we need to answer a large
1117 	 * amount of time, which the normal subtraction should do.
1118 	 */
1119 	return (cts - earlier_time);
1120 }
1121 
1122 static int
1123 sysctl_bbr_clear_lost(SYSCTL_HANDLER_ARGS)
1124 {
1125 	uint32_t stat;
1126 	int32_t error;
1127 
1128 	error = SYSCTL_OUT(req, &bbr_clear_lost, sizeof(uint32_t));
1129 	if (error || req->newptr == NULL)
1130 		return error;
1131 
1132 	error = SYSCTL_IN(req, &stat, sizeof(uint32_t));
1133 	if (error)
1134 		return (error);
1135 	if (stat == 1) {
1136 #ifdef BBR_INVARIANTS
1137 		printf("Clearing BBR lost counters\n");
1138 #endif
1139 		COUNTER_ARRAY_ZERO(bbr_state_lost, BBR_MAX_STAT);
1140 		COUNTER_ARRAY_ZERO(bbr_state_time, BBR_MAX_STAT);
1141 		COUNTER_ARRAY_ZERO(bbr_state_resend, BBR_MAX_STAT);
1142 	} else if (stat == 2) {
1143 #ifdef BBR_INVARIANTS
1144 		printf("Clearing BBR option counters\n");
1145 #endif
1146 		COUNTER_ARRAY_ZERO(bbr_opts_arry, BBR_OPTS_SIZE);
1147 	} else if (stat == 3) {
1148 #ifdef BBR_INVARIANTS
1149 		printf("Clearing BBR stats counters\n");
1150 #endif
1151 		COUNTER_ARRAY_ZERO(bbr_stat_arry, BBR_STAT_SIZE);
1152 	} else if (stat == 4) {
1153 #ifdef BBR_INVARIANTS
1154 		printf("Clearing BBR out-size counters\n");
1155 #endif
1156 		COUNTER_ARRAY_ZERO(bbr_out_size, TCP_MSS_ACCT_SIZE);
1157 	}
1158 	bbr_clear_lost = 0;
1159 	return (0);
1160 }
1161 
1162 static void
1163 bbr_init_sysctls(void)
1164 {
1165 	struct sysctl_oid *bbr_probertt;
1166 	struct sysctl_oid *bbr_hptsi;
1167 	struct sysctl_oid *bbr_measure;
1168 	struct sysctl_oid *bbr_cwnd;
1169 	struct sysctl_oid *bbr_timeout;
1170 	struct sysctl_oid *bbr_states;
1171 	struct sysctl_oid *bbr_startup;
1172 	struct sysctl_oid *bbr_policer;
1173 
1174 	/* Probe rtt controls */
1175 	bbr_probertt = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1176 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1177 	    OID_AUTO,
1178 	    "probertt",
1179 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1180 	    "");
1181 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1182 	    SYSCTL_CHILDREN(bbr_probertt),
1183 	    OID_AUTO, "gain", CTLFLAG_RW,
1184 	    &bbr_rttprobe_gain, 192,
1185 	    "What is the filter gain drop in probe_rtt (0=disable)?");
1186 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1187 	    SYSCTL_CHILDREN(bbr_probertt),
1188 	    OID_AUTO, "cwnd", CTLFLAG_RW,
1189 	    &bbr_rtt_probe_cwndtarg, 4,
1190 	    "How many mss's are outstanding during probe-rtt");
1191 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1192 	    SYSCTL_CHILDREN(bbr_probertt),
1193 	    OID_AUTO, "int", CTLFLAG_RW,
1194 	    &bbr_rtt_probe_limit, 4000000,
1195 	    "If RTT has not shrank in this many micro-seconds enter probe-rtt");
1196 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1197 	    SYSCTL_CHILDREN(bbr_probertt),
1198 	    OID_AUTO, "mintime", CTLFLAG_RW,
1199 	    &bbr_rtt_probe_time, 200000,
1200 	    "How many microseconds in probe-rtt");
1201 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1202 	    SYSCTL_CHILDREN(bbr_probertt),
1203 	    OID_AUTO, "filter_len_sec", CTLFLAG_RW,
1204 	    &bbr_filter_len_sec, 6,
1205 	    "How long in seconds does the rttProp filter run?");
1206 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1207 	    SYSCTL_CHILDREN(bbr_probertt),
1208 	    OID_AUTO, "drain_rtt", CTLFLAG_RW,
1209 	    &bbr_drain_rtt, BBR_SRTT,
1210 	    "What is the drain rtt to use in probeRTT (rtt_prop=0, rtt_rack=1, rtt_pkt=2, rtt_srtt=3?");
1211 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1212 	    SYSCTL_CHILDREN(bbr_probertt),
1213 	    OID_AUTO, "can_force", CTLFLAG_RW,
1214 	    &bbr_can_force_probertt, 0,
1215 	    "If we keep setting new low rtt's but delay going in probe-rtt can we force in??");
1216 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1217 	    SYSCTL_CHILDREN(bbr_probertt),
1218 	    OID_AUTO, "enter_sets_force", CTLFLAG_RW,
1219 	    &bbr_probertt_sets_rtt, 0,
1220 	    "In NF mode, do we imitate google_mode and set the rttProp on entry to probe-rtt?");
1221 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1222 	    SYSCTL_CHILDREN(bbr_probertt),
1223 	    OID_AUTO, "can_adjust", CTLFLAG_RW,
1224 	    &bbr_can_adjust_probertt, 1,
1225 	    "Can we dynamically adjust the probe-rtt limits and times?");
1226 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1227 	    SYSCTL_CHILDREN(bbr_probertt),
1228 	    OID_AUTO, "is_ratio", CTLFLAG_RW,
1229 	    &bbr_is_ratio, 0,
1230 	    "is the limit to filter a ratio?");
1231 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1232 	    SYSCTL_CHILDREN(bbr_probertt),
1233 	    OID_AUTO, "use_cwnd", CTLFLAG_RW,
1234 	    &bbr_prtt_slam_cwnd, 0,
1235 	    "Should we set/recover cwnd?");
1236 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1237 	    SYSCTL_CHILDREN(bbr_probertt),
1238 	    OID_AUTO, "can_use_ts", CTLFLAG_RW,
1239 	    &bbr_can_use_ts_for_rtt, 1,
1240 	    "Can we use the ms timestamp if available for retransmistted rtt calculations?");
1241 
1242 	/* Pacing controls */
1243 	bbr_hptsi = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1244 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1245 	    OID_AUTO,
1246 	    "pacing",
1247 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1248 	    "");
1249 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1250 	    SYSCTL_CHILDREN(bbr_hptsi),
1251 	    OID_AUTO, "hw_pacing", CTLFLAG_RW,
1252 	    &bbr_allow_hdwr_pacing, 1,
1253 	    "Do we allow hardware pacing?");
1254 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1255 	    SYSCTL_CHILDREN(bbr_hptsi),
1256 	    OID_AUTO, "hw_pacing_limit", CTLFLAG_RW,
1257 	    &bbr_hardware_pacing_limit, 4000,
1258 	    "Do we have a limited number of connections for pacing chelsio (0=no limit)?");
1259 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1260 	    SYSCTL_CHILDREN(bbr_hptsi),
1261 	    OID_AUTO, "hw_pacing_adj", CTLFLAG_RW,
1262 	    &bbr_hdwr_pace_adjust, 2,
1263 	    "Multiplier to calculated tso size?");
1264 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1265 	    SYSCTL_CHILDREN(bbr_hptsi),
1266 	    OID_AUTO, "hw_pacing_floor", CTLFLAG_RW,
1267 	    &bbr_hdwr_pace_floor, 1,
1268 	    "Do we invoke the hardware pacing floor?");
1269 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1270 	    SYSCTL_CHILDREN(bbr_hptsi),
1271 	    OID_AUTO, "hw_pacing_delay_cnt", CTLFLAG_RW,
1272 	    &bbr_hdwr_pacing_delay_cnt, 10,
1273 	    "How many packets must be sent after hdwr pacing is enabled");
1274 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1275 	    SYSCTL_CHILDREN(bbr_hptsi),
1276 	    OID_AUTO, "bw_cross", CTLFLAG_RW,
1277 	    &bbr_cross_over, 3000000,
1278 	    "What is the point where we cross over to linux like TSO size set");
1279 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1280 	    SYSCTL_CHILDREN(bbr_hptsi),
1281 	    OID_AUTO, "seg_deltarg", CTLFLAG_RW,
1282 	    &bbr_hptsi_segments_delay_tar, 7000,
1283 	    "What is the worse case delay target for hptsi < 48Mbp connections");
1284 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1285 	    SYSCTL_CHILDREN(bbr_hptsi),
1286 	    OID_AUTO, "enet_oh", CTLFLAG_RW,
1287 	    &bbr_include_enet_oh, 0,
1288 	    "Do we include the ethernet overhead in calculating pacing delay?");
1289 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1290 	    SYSCTL_CHILDREN(bbr_hptsi),
1291 	    OID_AUTO, "ip_oh", CTLFLAG_RW,
1292 	    &bbr_include_ip_oh, 1,
1293 	    "Do we include the IP overhead in calculating pacing delay?");
1294 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1295 	    SYSCTL_CHILDREN(bbr_hptsi),
1296 	    OID_AUTO, "tcp_oh", CTLFLAG_RW,
1297 	    &bbr_include_tcp_oh, 0,
1298 	    "Do we include the TCP overhead in calculating pacing delay?");
1299 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1300 	    SYSCTL_CHILDREN(bbr_hptsi),
1301 	    OID_AUTO, "google_discount", CTLFLAG_RW,
1302 	    &bbr_google_discount, 10,
1303 	    "What is the default google discount percentage wise for pacing (11 = 1.1%%)?");
1304 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1305 	    SYSCTL_CHILDREN(bbr_hptsi),
1306 	    OID_AUTO, "all_get_min", CTLFLAG_RW,
1307 	    &bbr_all_get_min, 0,
1308 	    "If you are less than a MSS do you just get the min?");
1309 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1310 	    SYSCTL_CHILDREN(bbr_hptsi),
1311 	    OID_AUTO, "tso_min", CTLFLAG_RW,
1312 	    &bbr_hptsi_bytes_min, 1460,
1313 	    "For 0 -> 24Mbps what is floor number of segments for TSO");
1314 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1315 	    SYSCTL_CHILDREN(bbr_hptsi),
1316 	    OID_AUTO, "seg_tso_max", CTLFLAG_RW,
1317 	    &bbr_hptsi_segments_max, 6,
1318 	    "For 0 -> 24Mbps what is top number of segments for TSO");
1319 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1320 	    SYSCTL_CHILDREN(bbr_hptsi),
1321 	    OID_AUTO, "seg_floor", CTLFLAG_RW,
1322 	    &bbr_hptsi_segments_floor, 1,
1323 	    "Minimum TSO size we will fall too in segments");
1324 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1325 	    SYSCTL_CHILDREN(bbr_hptsi),
1326 	    OID_AUTO, "utter_max", CTLFLAG_RW,
1327 	    &bbr_hptsi_utter_max, 0,
1328 	    "The absolute maximum that any pacing (outside of hardware) can be");
1329 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1330 	    SYSCTL_CHILDREN(bbr_hptsi),
1331 	    OID_AUTO, "seg_divisor", CTLFLAG_RW,
1332 	    &bbr_hptsi_per_second, 100,
1333 	    "What is the divisor in our hptsi TSO calculation 512Mbps < X > 24Mbps ");
1334 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1335 	    SYSCTL_CHILDREN(bbr_hptsi),
1336 	    OID_AUTO, "srtt_mul", CTLFLAG_RW,
1337 	    &bbr_hptsi_max_mul, 1,
1338 	    "The multiplier for pace len max");
1339 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1340 	    SYSCTL_CHILDREN(bbr_hptsi),
1341 	    OID_AUTO, "srtt_div", CTLFLAG_RW,
1342 	    &bbr_hptsi_max_div, 2,
1343 	    "The divisor for pace len max");
1344 	/* Measurement controls */
1345 	bbr_measure = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1346 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1347 	    OID_AUTO,
1348 	    "measure",
1349 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1350 	    "Measurement controls");
1351 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1352 	    SYSCTL_CHILDREN(bbr_measure),
1353 	    OID_AUTO, "min_i_bw", CTLFLAG_RW,
1354 	    &bbr_initial_bw_bps, 62500,
1355 	    "Minimum initial b/w in bytes per second");
1356 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1357 	    SYSCTL_CHILDREN(bbr_measure),
1358 	    OID_AUTO, "no_sack_needed", CTLFLAG_RW,
1359 	    &bbr_sack_not_required, 0,
1360 	    "Do we allow bbr to run on connections not supporting SACK?");
1361 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1362 	    SYSCTL_CHILDREN(bbr_measure),
1363 	    OID_AUTO, "use_google", CTLFLAG_RW,
1364 	    &bbr_use_google_algo, 0,
1365 	    "Use has close to google V1.0 has possible?");
1366 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1367 	    SYSCTL_CHILDREN(bbr_measure),
1368 	    OID_AUTO, "ts_limiting", CTLFLAG_RW,
1369 	    &bbr_ts_limiting, 1,
1370 	    "Do we attempt to use the peers timestamp to limit b/w caculations?");
1371 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1372 	    SYSCTL_CHILDREN(bbr_measure),
1373 	    OID_AUTO, "ts_can_raise", CTLFLAG_RW,
1374 	    &bbr_ts_can_raise, 0,
1375 	    "Can we raise the b/w via timestamp b/w calculation?");
1376 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1377 	    SYSCTL_CHILDREN(bbr_measure),
1378 	    OID_AUTO, "ts_delta", CTLFLAG_RW,
1379 	    &bbr_min_usec_delta, 20000,
1380 	    "How long in usec between ts of our sends in ts validation code?");
1381 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1382 	    SYSCTL_CHILDREN(bbr_measure),
1383 	    OID_AUTO, "ts_peer_delta", CTLFLAG_RW,
1384 	    &bbr_min_peer_delta, 20,
1385 	    "What min numerical value should be between the peer deltas?");
1386 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1387 	    SYSCTL_CHILDREN(bbr_measure),
1388 	    OID_AUTO, "ts_delta_percent", CTLFLAG_RW,
1389 	    &bbr_delta_percent, 150,
1390 	    "What percentage (150 = 15.0) do we allow variance for?");
1391 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1392 	    SYSCTL_CHILDREN(bbr_measure),
1393 	    OID_AUTO, "min_measure_good_bw", CTLFLAG_RW,
1394 	    &bbr_min_measurements_req, 1,
1395 	    "What is the minimum measurement count we need before we switch to our b/w estimate");
1396 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1397 	    SYSCTL_CHILDREN(bbr_measure),
1398 	    OID_AUTO, "min_measure_before_pace", CTLFLAG_RW,
1399 	    &bbr_no_pacing_until, 4,
1400 	    "How many pkt-epoch's (0 is off) do we need before pacing is on?");
1401 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1402 	    SYSCTL_CHILDREN(bbr_measure),
1403 	    OID_AUTO, "quanta", CTLFLAG_RW,
1404 	    &bbr_quanta, 2,
1405 	    "Extra quanta to add when calculating the target (ID section 4.2.3.2).");
1406 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1407 	    SYSCTL_CHILDREN(bbr_measure),
1408 	    OID_AUTO, "noretran", CTLFLAG_RW,
1409 	    &bbr_no_retran, 0,
1410 	    "Should google mode not use retransmission measurements for the b/w estimation?");
1411 	/* State controls */
1412 	bbr_states = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1413 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1414 	    OID_AUTO,
1415 	    "states",
1416 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1417 	    "State controls");
1418 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1419 	    SYSCTL_CHILDREN(bbr_states),
1420 	    OID_AUTO, "idle_restart", CTLFLAG_RW,
1421 	    &bbr_uses_idle_restart, 0,
1422 	    "Do we use a new special idle_restart state to ramp back up quickly?");
1423 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1424 	    SYSCTL_CHILDREN(bbr_states),
1425 	    OID_AUTO, "idle_restart_threshold", CTLFLAG_RW,
1426 	    &bbr_idle_restart_threshold, 100000,
1427 	    "How long must we be idle before we restart??");
1428 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1429 	    SYSCTL_CHILDREN(bbr_states),
1430 	    OID_AUTO, "use_pkt_epoch", CTLFLAG_RW,
1431 	    &bbr_state_is_pkt_epoch, 0,
1432 	    "Do we use a pkt-epoch for substate if 0 rttProp?");
1433 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1434 	    SYSCTL_CHILDREN(bbr_states),
1435 	    OID_AUTO, "startup_rtt_gain", CTLFLAG_RW,
1436 	    &bbr_rtt_gain_thresh, 0,
1437 	    "What increase in RTT triggers us to stop ignoring no-loss and possibly exit startup?");
1438 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1439 	    SYSCTL_CHILDREN(bbr_states),
1440 	    OID_AUTO, "drain_floor", CTLFLAG_RW,
1441 	    &bbr_drain_floor, 88,
1442 	    "What is the lowest we can drain (pg) too?");
1443 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1444 	    SYSCTL_CHILDREN(bbr_states),
1445 	    OID_AUTO, "drain_2_target", CTLFLAG_RW,
1446 	    &bbr_state_drain_2_tar, 1,
1447 	    "Do we drain to target in drain substate?");
1448 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1449 	    SYSCTL_CHILDREN(bbr_states),
1450 	    OID_AUTO, "gain_2_target", CTLFLAG_RW,
1451 	    &bbr_gain_to_target, 1,
1452 	    "Does probe bw gain to target??");
1453 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1454 	    SYSCTL_CHILDREN(bbr_states),
1455 	    OID_AUTO, "gain_extra_time", CTLFLAG_RW,
1456 	    &bbr_gain_gets_extra_too, 1,
1457 	    "Does probe bw gain get the extra time too?");
1458 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1459 	    SYSCTL_CHILDREN(bbr_states),
1460 	    OID_AUTO, "ld_div", CTLFLAG_RW,
1461 	    &bbr_drain_drop_div, 5,
1462 	    "Long drain drop divider?");
1463 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1464 	    SYSCTL_CHILDREN(bbr_states),
1465 	    OID_AUTO, "ld_mul", CTLFLAG_RW,
1466 	    &bbr_drain_drop_mul, 4,
1467 	    "Long drain drop multiplier?");
1468 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1469 	    SYSCTL_CHILDREN(bbr_states),
1470 	    OID_AUTO, "rand_ot_disc", CTLFLAG_RW,
1471 	    &bbr_rand_ot, 50,
1472 	    "Random discount of the ot?");
1473 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1474 	    SYSCTL_CHILDREN(bbr_states),
1475 	    OID_AUTO, "dr_filter_life", CTLFLAG_RW,
1476 	    &bbr_num_pktepo_for_del_limit, BBR_NUM_RTTS_FOR_DEL_LIMIT,
1477 	    "How many packet-epochs does the b/w delivery rate last?");
1478 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1479 	    SYSCTL_CHILDREN(bbr_states),
1480 	    OID_AUTO, "subdrain_applimited", CTLFLAG_RW,
1481 	    &bbr_sub_drain_app_limit, 0,
1482 	    "Does our sub-state drain invoke app limited if its long?");
1483 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1484 	    SYSCTL_CHILDREN(bbr_states),
1485 	    OID_AUTO, "use_cwnd_subdrain", CTLFLAG_RW,
1486 	    &bbr_sub_drain_slam_cwnd, 0,
1487 	    "Should we set/recover cwnd for sub-state drain?");
1488 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1489 	    SYSCTL_CHILDREN(bbr_states),
1490 	    OID_AUTO, "use_cwnd_maindrain", CTLFLAG_RW,
1491 	    &bbr_slam_cwnd_in_main_drain, 0,
1492 	    "Should we set/recover cwnd for main-state drain?");
1493 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1494 	    SYSCTL_CHILDREN(bbr_states),
1495 	    OID_AUTO, "google_gets_earlyout", CTLFLAG_RW,
1496 	    &google_allow_early_out, 1,
1497 	    "Should we allow google probe-bw/drain to exit early at flight target?");
1498 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1499 	    SYSCTL_CHILDREN(bbr_states),
1500 	    OID_AUTO, "google_exit_loss", CTLFLAG_RW,
1501 	    &google_consider_lost, 1,
1502 	    "Should we have losses exit gain of probebw in google mode??");
1503 	/* Startup controls */
1504 	bbr_startup = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1505 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1506 	    OID_AUTO,
1507 	    "startup",
1508 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1509 	    "Startup controls");
1510 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1511 	    SYSCTL_CHILDREN(bbr_startup),
1512 	    OID_AUTO, "cheat_iwnd", CTLFLAG_RW,
1513 	    &bbr_sends_full_iwnd, 1,
1514 	    "Do we not pace but burst out initial windows has our TSO size?");
1515 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1516 	    SYSCTL_CHILDREN(bbr_startup),
1517 	    OID_AUTO, "loss_threshold", CTLFLAG_RW,
1518 	    &bbr_startup_loss_thresh, 2000,
1519 	    "In startup what is the loss threshold in a pe that will exit us from startup?");
1520 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1521 	    SYSCTL_CHILDREN(bbr_startup),
1522 	    OID_AUTO, "use_lowerpg", CTLFLAG_RW,
1523 	    &bbr_use_lower_gain_in_startup, 1,
1524 	    "Should we use a lower hptsi gain if we see loss in startup?");
1525 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1526 	    SYSCTL_CHILDREN(bbr_startup),
1527 	    OID_AUTO, "gain", CTLFLAG_RW,
1528 	    &bbr_start_exit, 25,
1529 	    "What gain percent do we need to see to stay in startup??");
1530 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1531 	    SYSCTL_CHILDREN(bbr_startup),
1532 	    OID_AUTO, "low_gain", CTLFLAG_RW,
1533 	    &bbr_low_start_exit, 15,
1534 	    "What gain percent do we need to see to stay in the lower gain startup??");
1535 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1536 	    SYSCTL_CHILDREN(bbr_startup),
1537 	    OID_AUTO, "loss_exit", CTLFLAG_RW,
1538 	    &bbr_exit_startup_at_loss, 1,
1539 	    "Should we exit startup at loss in an epoch if we are not gaining?");
1540 	/* CWND controls */
1541 	bbr_cwnd = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1542 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1543 	    OID_AUTO,
1544 	    "cwnd",
1545 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1546 	    "Cwnd controls");
1547 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1548 	    SYSCTL_CHILDREN(bbr_cwnd),
1549 	    OID_AUTO, "tar_rtt", CTLFLAG_RW,
1550 	    &bbr_cwndtarget_rtt_touse, 0,
1551 	    "Target cwnd rtt measurement to use (0=rtt_prop, 1=rtt_rack, 2=pkt_rtt, 3=srtt)?");
1552 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1553 	    SYSCTL_CHILDREN(bbr_cwnd),
1554 	    OID_AUTO, "may_shrink", CTLFLAG_RW,
1555 	    &bbr_cwnd_may_shrink, 0,
1556 	    "Can the cwnd shrink if it would grow to more than the target?");
1557 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1558 	    SYSCTL_CHILDREN(bbr_cwnd),
1559 	    OID_AUTO, "max_target_limit", CTLFLAG_RW,
1560 	    &bbr_target_cwnd_mult_limit, 8,
1561 	    "Do we limit the cwnd to some multiple of the cwnd target if cwnd can't shrink 0=no?");
1562 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1563 	    SYSCTL_CHILDREN(bbr_cwnd),
1564 	    OID_AUTO, "highspeed_min", CTLFLAG_RW,
1565 	    &bbr_cwnd_min_val_hs, BBR_HIGHSPEED_NUM_MSS,
1566 	    "What is the high-speed min cwnd (rttProp under 1ms)");
1567 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1568 	    SYSCTL_CHILDREN(bbr_cwnd),
1569 	    OID_AUTO, "lowspeed_min", CTLFLAG_RW,
1570 	    &bbr_cwnd_min_val, BBR_PROBERTT_NUM_MSS,
1571 	    "What is the min cwnd (rttProp > 1ms)");
1572 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1573 	    SYSCTL_CHILDREN(bbr_cwnd),
1574 	    OID_AUTO, "initwin", CTLFLAG_RW,
1575 	    &bbr_def_init_win, 10,
1576 	    "What is the BBR initial window, if 0 use tcp version");
1577 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1578 	    SYSCTL_CHILDREN(bbr_cwnd),
1579 	    OID_AUTO, "do_loss_red", CTLFLAG_RW,
1580 	    &bbr_do_red, 600,
1581 	    "Do we reduce the b/w at exit from recovery based on ratio of prop/srtt (800=80.0, 0=off)?");
1582 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1583 	    SYSCTL_CHILDREN(bbr_cwnd),
1584 	    OID_AUTO, "red_scale", CTLFLAG_RW,
1585 	    &bbr_red_scale, 20000,
1586 	    "What RTT do we scale with?");
1587 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1588 	    SYSCTL_CHILDREN(bbr_cwnd),
1589 	    OID_AUTO, "red_growslow", CTLFLAG_RW,
1590 	    &bbr_red_growth_restrict, 1,
1591 	    "Do we restrict cwnd growth for whats in flight?");
1592 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1593 	    SYSCTL_CHILDREN(bbr_cwnd),
1594 	    OID_AUTO, "red_div", CTLFLAG_RW,
1595 	    &bbr_red_div, 2,
1596 	    "If we reduce whats the divisor?");
1597 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1598 	    SYSCTL_CHILDREN(bbr_cwnd),
1599 	    OID_AUTO, "red_mul", CTLFLAG_RW,
1600 	    &bbr_red_mul, 1,
1601 	    "If we reduce whats the mulitiplier?");
1602 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1603 	    SYSCTL_CHILDREN(bbr_cwnd),
1604 	    OID_AUTO, "target_is_unit", CTLFLAG_RW,
1605 	    &bbr_target_is_bbunit, 0,
1606 	    "Is the state target the pacing_gain or BBR_UNIT?");
1607 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1608 	    SYSCTL_CHILDREN(bbr_cwnd),
1609 	    OID_AUTO, "drop_limit", CTLFLAG_RW,
1610 	    &bbr_drop_limit, 0,
1611 	    "Number of segments limit for drop (0=use min_cwnd w/flight)?");
1612 
1613 	/* Timeout controls */
1614 	bbr_timeout = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1615 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1616 	    OID_AUTO,
1617 	    "timeout",
1618 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1619 	    "Time out controls");
1620 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1621 	    SYSCTL_CHILDREN(bbr_timeout),
1622 	    OID_AUTO, "delack", CTLFLAG_RW,
1623 	    &bbr_delack_time, 100000,
1624 	    "BBR's delayed ack time");
1625 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1626 	    SYSCTL_CHILDREN(bbr_timeout),
1627 	    OID_AUTO, "tlp_uses", CTLFLAG_RW,
1628 	    &bbr_tlp_type_to_use, 3,
1629 	    "RTT that TLP uses in its calculations, 0=rttProp, 1=Rack_rtt, 2=pkt_rtt and 3=srtt");
1630 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1631 	    SYSCTL_CHILDREN(bbr_timeout),
1632 	    OID_AUTO, "persmin", CTLFLAG_RW,
1633 	    &bbr_persist_min, 250000,
1634 	    "What is the minimum time in microseconds between persists");
1635 	SYSCTL_ADD_U32(&bbr_sysctl_ctx,
1636 	    SYSCTL_CHILDREN(bbr_timeout),
1637 	    OID_AUTO, "persmax", CTLFLAG_RW,
1638 	    &bbr_persist_max, 1000000,
1639 	    "What is the largest delay in microseconds between persists");
1640 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1641 	    SYSCTL_CHILDREN(bbr_timeout),
1642 	    OID_AUTO, "tlp_minto", CTLFLAG_RW,
1643 	    &bbr_tlp_min, 10000,
1644 	    "TLP Min timeout in usecs");
1645 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1646 	    SYSCTL_CHILDREN(bbr_timeout),
1647 	    OID_AUTO, "tlp_dack_time", CTLFLAG_RW,
1648 	    &bbr_delayed_ack_time, 200000,
1649 	    "TLP delayed ack compensation value");
1650 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1651 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1652 	    OID_AUTO, "minrto", CTLFLAG_RW,
1653 	    &bbr_rto_min_ms, 30,
1654 	    "Minimum RTO in ms");
1655 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1656 	    SYSCTL_CHILDREN(bbr_timeout),
1657 	    OID_AUTO, "maxrto", CTLFLAG_RW,
1658 	    &bbr_rto_max_sec, 4,
1659 	    "Maximum RTO in seconds -- should be at least as large as min_rto");
1660 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1661 	    SYSCTL_CHILDREN(bbr_timeout),
1662 	    OID_AUTO, "tlp_retry", CTLFLAG_RW,
1663 	    &bbr_tlp_max_resend, 2,
1664 	    "How many times does TLP retry a single segment or multiple with no ACK");
1665 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1666 	    SYSCTL_CHILDREN(bbr_timeout),
1667 	    OID_AUTO, "minto", CTLFLAG_RW,
1668 	    &bbr_min_to, 1000,
1669 	    "Minimum rack timeout in useconds");
1670 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1671 	    SYSCTL_CHILDREN(bbr_timeout),
1672 	    OID_AUTO, "pktdelay", CTLFLAG_RW,
1673 	    &bbr_pkt_delay, 1000,
1674 	    "Extra RACK time (in useconds) besides reordering thresh");
1675 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1676 	    SYSCTL_CHILDREN(bbr_timeout),
1677 	    OID_AUTO, "incr_tmrs", CTLFLAG_RW,
1678 	    &bbr_incr_timers, 1,
1679 	    "Increase the RXT/TLP timer by the pacing time used?");
1680 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1681 	    SYSCTL_CHILDREN(bbr_timeout),
1682 	    OID_AUTO, "rxtmark_sackpassed", CTLFLAG_RW,
1683 	    &bbr_marks_rxt_sack_passed, 0,
1684 	    "Mark sack passed on all those not ack'd when a RXT hits?");
1685 	/* Policer controls */
1686 	bbr_policer = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
1687 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1688 	    OID_AUTO,
1689 	    "policer",
1690 	    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1691 	    "Policer controls");
1692 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1693 	    SYSCTL_CHILDREN(bbr_policer),
1694 	    OID_AUTO, "detect_enable", CTLFLAG_RW,
1695 	    &bbr_policer_detection_enabled, 1,
1696 	    "Is policer detection enabled??");
1697 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1698 	    SYSCTL_CHILDREN(bbr_policer),
1699 	    OID_AUTO, "min_pes", CTLFLAG_RW,
1700 	    &bbr_lt_intvl_min_rtts, 4,
1701 	    "Minimum number of PE's?");
1702 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1703 	    SYSCTL_CHILDREN(bbr_policer),
1704 	    OID_AUTO, "bwdiff", CTLFLAG_RW,
1705 	    &bbr_lt_bw_diff, (4000/8),
1706 	    "Minimal bw diff?");
1707 	SYSCTL_ADD_U64(&bbr_sysctl_ctx,
1708 	    SYSCTL_CHILDREN(bbr_policer),
1709 	    OID_AUTO, "bwratio", CTLFLAG_RW,
1710 	    &bbr_lt_bw_ratio, 8,
1711 	    "Minimal bw diff?");
1712 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1713 	    SYSCTL_CHILDREN(bbr_policer),
1714 	    OID_AUTO, "from_rack_rxt", CTLFLAG_RW,
1715 	    &bbr_policer_call_from_rack_to, 0,
1716 	    "Do we call the policer detection code from a rack-timeout?");
1717 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1718 	    SYSCTL_CHILDREN(bbr_policer),
1719 	    OID_AUTO, "false_postive", CTLFLAG_RW,
1720 	    &bbr_lt_intvl_fp, 0,
1721 	    "What packet epoch do we do false-positive detection at (0=no)?");
1722 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1723 	    SYSCTL_CHILDREN(bbr_policer),
1724 	    OID_AUTO, "loss_thresh", CTLFLAG_RW,
1725 	    &bbr_lt_loss_thresh, 196,
1726 	    "Loss threshold 196 = 19.6%?");
1727 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1728 	    SYSCTL_CHILDREN(bbr_policer),
1729 	    OID_AUTO, "false_postive_thresh", CTLFLAG_RW,
1730 	    &bbr_lt_fd_thresh, 100,
1731 	    "What percentage is the false detection threshold (150=15.0)?");
1732 	/* All the rest */
1733 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1734 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1735 	    OID_AUTO, "cheat_rxt", CTLFLAG_RW,
1736 	    &bbr_use_rack_resend_cheat, 0,
1737 	    "Do we burst 1ms between sends on retransmissions (like rack)?");
1738 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1739 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1740 	    OID_AUTO, "error_paceout", CTLFLAG_RW,
1741 	    &bbr_error_base_paceout, 10000,
1742 	    "When we hit an error what is the min to pace out in usec's?");
1743 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1744 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1745 	    OID_AUTO, "kill_paceout", CTLFLAG_RW,
1746 	    &bbr_max_net_error_cnt, 10,
1747 	    "When we hit this many errors in a row, kill the session?");
1748 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1749 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1750 	    OID_AUTO, "data_after_close", CTLFLAG_RW,
1751 	    &bbr_ignore_data_after_close, 1,
1752 	    "Do we hold off sending a RST until all pending data is ack'd");
1753 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1754 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1755 	    OID_AUTO, "resend_use_tso", CTLFLAG_RW,
1756 	    &bbr_resends_use_tso, 0,
1757 	    "Can resends use TSO?");
1758 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1759 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1760 	    OID_AUTO, "sblklimit", CTLFLAG_RW,
1761 	    &bbr_sack_block_limit, 128,
1762 	    "When do we start ignoring small sack blocks");
1763 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1764 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1765 	    OID_AUTO, "bb_verbose", CTLFLAG_RW,
1766 	    &bbr_verbose_logging, 0,
1767 	    "Should BBR black box logging be verbose");
1768 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1769 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1770 	    OID_AUTO, "reorder_thresh", CTLFLAG_RW,
1771 	    &bbr_reorder_thresh, 2,
1772 	    "What factor for rack will be added when seeing reordering (shift right)");
1773 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1774 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1775 	    OID_AUTO, "reorder_fade", CTLFLAG_RW,
1776 	    &bbr_reorder_fade, 0,
1777 	    "Does reorder detection fade, if so how many ms (0 means never)");
1778 	SYSCTL_ADD_S32(&bbr_sysctl_ctx,
1779 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1780 	    OID_AUTO, "rtt_tlp_thresh", CTLFLAG_RW,
1781 	    &bbr_tlp_thresh, 1,
1782 	    "what divisor for TLP rtt/retran will be added (1=rtt, 2=1/2 rtt etc)");
1783 	/* Stats and counters */
1784 	/* The pacing counters for hdwr/software can't be in the array */
1785 	bbr_nohdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1786 	bbr_hdwr_pacing_enobuf = counter_u64_alloc(M_WAITOK);
1787 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1788 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1789 	    OID_AUTO, "enob_hdwr_pacing", CTLFLAG_RD,
1790 	    &bbr_hdwr_pacing_enobuf,
1791 	    "Total number of enobufs for hardware paced flows");
1792 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1793 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1794 	    OID_AUTO, "enob_no_hdwr_pacing", CTLFLAG_RD,
1795 	    &bbr_nohdwr_pacing_enobuf,
1796 	    "Total number of enobufs for non-hardware paced flows");
1797 
1798 	bbr_flows_whdwr_pacing = counter_u64_alloc(M_WAITOK);
1799 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1800 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1801 	    OID_AUTO, "hdwr_pacing", CTLFLAG_RD,
1802 	    &bbr_flows_whdwr_pacing,
1803 	    "Total number of hardware paced flows");
1804 	bbr_flows_nohdwr_pacing = counter_u64_alloc(M_WAITOK);
1805 	SYSCTL_ADD_COUNTER_U64(&bbr_sysctl_ctx,
1806 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1807 	    OID_AUTO, "software_pacing", CTLFLAG_RD,
1808 	    &bbr_flows_nohdwr_pacing,
1809 	    "Total number of software paced flows");
1810 	COUNTER_ARRAY_ALLOC(bbr_stat_arry, BBR_STAT_SIZE, M_WAITOK);
1811 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1812 	    OID_AUTO, "stats", CTLFLAG_RD,
1813 	    bbr_stat_arry, BBR_STAT_SIZE, "BBR Stats");
1814 	COUNTER_ARRAY_ALLOC(bbr_opts_arry, BBR_OPTS_SIZE, M_WAITOK);
1815 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1816 	    OID_AUTO, "opts", CTLFLAG_RD,
1817 	    bbr_opts_arry, BBR_OPTS_SIZE, "BBR Option Stats");
1818 	COUNTER_ARRAY_ALLOC(bbr_state_lost, BBR_MAX_STAT, M_WAITOK);
1819 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1820 	    OID_AUTO, "lost", CTLFLAG_RD,
1821 	    bbr_state_lost, BBR_MAX_STAT, "Stats of when losses occur");
1822 	COUNTER_ARRAY_ALLOC(bbr_state_resend, BBR_MAX_STAT, M_WAITOK);
1823 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1824 	    OID_AUTO, "stateresend", CTLFLAG_RD,
1825 	    bbr_state_resend, BBR_MAX_STAT, "Stats of what states resend");
1826 	COUNTER_ARRAY_ALLOC(bbr_state_time, BBR_MAX_STAT, M_WAITOK);
1827 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1828 	    OID_AUTO, "statetime", CTLFLAG_RD,
1829 	    bbr_state_time, BBR_MAX_STAT, "Stats of time spent in the states");
1830 	COUNTER_ARRAY_ALLOC(bbr_out_size, TCP_MSS_ACCT_SIZE, M_WAITOK);
1831 	SYSCTL_ADD_COUNTER_U64_ARRAY(&bbr_sysctl_ctx, SYSCTL_CHILDREN(bbr_sysctl_root),
1832 	    OID_AUTO, "outsize", CTLFLAG_RD,
1833 	    bbr_out_size, TCP_MSS_ACCT_SIZE, "Size of output calls");
1834 	SYSCTL_ADD_PROC(&bbr_sysctl_ctx,
1835 	    SYSCTL_CHILDREN(bbr_sysctl_root),
1836 	    OID_AUTO, "clrlost", CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1837 	    &bbr_clear_lost, 0, sysctl_bbr_clear_lost, "IU", "Clear lost counters");
1838 }
1839 
1840 static void
1841 bbr_counter_destroy(void)
1842 {
1843 	COUNTER_ARRAY_FREE(bbr_stat_arry, BBR_STAT_SIZE);
1844 	COUNTER_ARRAY_FREE(bbr_opts_arry, BBR_OPTS_SIZE);
1845 	COUNTER_ARRAY_FREE(bbr_out_size, TCP_MSS_ACCT_SIZE);
1846 	COUNTER_ARRAY_FREE(bbr_state_lost, BBR_MAX_STAT);
1847 	COUNTER_ARRAY_FREE(bbr_state_time, BBR_MAX_STAT);
1848 	COUNTER_ARRAY_FREE(bbr_state_resend, BBR_MAX_STAT);
1849 	counter_u64_free(bbr_nohdwr_pacing_enobuf);
1850 	counter_u64_free(bbr_hdwr_pacing_enobuf);
1851 	counter_u64_free(bbr_flows_whdwr_pacing);
1852 	counter_u64_free(bbr_flows_nohdwr_pacing);
1853 
1854 }
1855 
1856 static __inline void
1857 bbr_fill_in_logging_data(struct tcp_bbr *bbr, struct tcp_log_bbr *l, uint32_t cts)
1858 {
1859 	memset(l, 0, sizeof(union tcp_log_stackspecific));
1860 	l->cur_del_rate = bbr->r_ctl.rc_bbr_cur_del_rate;
1861 	l->delRate = get_filter_value(&bbr->r_ctl.rc_delrate);
1862 	l->rttProp = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
1863 	l->bw_inuse = bbr_get_bw(bbr);
1864 	l->inflight = ctf_flight_size(bbr->rc_tp,
1865 			  (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
1866 	l->applimited = bbr->r_ctl.r_app_limited_until;
1867 	l->delivered = bbr->r_ctl.rc_delivered;
1868 	l->timeStamp = cts;
1869 	l->lost = bbr->r_ctl.rc_lost;
1870 	l->bbr_state = bbr->rc_bbr_state;
1871 	l->bbr_substate = bbr_state_val(bbr);
1872 	l->epoch = bbr->r_ctl.rc_rtt_epoch;
1873 	l->lt_epoch = bbr->r_ctl.rc_lt_epoch;
1874 	l->pacing_gain = bbr->r_ctl.rc_bbr_hptsi_gain;
1875 	l->cwnd_gain = bbr->r_ctl.rc_bbr_cwnd_gain;
1876 	l->inhpts = tcp_in_hpts(bbr->rc_tp);
1877 	l->use_lt_bw = bbr->rc_lt_use_bw;
1878 	l->pkts_out = bbr->r_ctl.rc_flight_at_input;
1879 	l->pkt_epoch = bbr->r_ctl.rc_pkt_epoch;
1880 }
1881 
1882 static void
1883 bbr_log_type_bw_reduce(struct tcp_bbr *bbr, int reason)
1884 {
1885 	if (tcp_bblogging_on(bbr->rc_tp)) {
1886 		union tcp_log_stackspecific log;
1887 
1888 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1889 		log.u_bbr.flex1 = 0;
1890 		log.u_bbr.flex2 = 0;
1891 		log.u_bbr.flex5 = 0;
1892 		log.u_bbr.flex3 = 0;
1893 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_loss_rate;
1894 		log.u_bbr.flex7 = reason;
1895 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_enters_probertt;
1896 		log.u_bbr.flex8 = 0;
1897 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1898 		    &bbr->rc_inp->inp_socket->so_rcv,
1899 		    &bbr->rc_inp->inp_socket->so_snd,
1900 		    BBR_LOG_BW_RED_EV, 0,
1901 		    0, &log, false, &bbr->rc_tv);
1902 	}
1903 }
1904 
1905 static void
1906 bbr_log_type_rwnd_collapse(struct tcp_bbr *bbr, int seq, int mode, uint32_t count)
1907 {
1908 	if (tcp_bblogging_on(bbr->rc_tp)) {
1909 		union tcp_log_stackspecific log;
1910 
1911 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1912 		log.u_bbr.flex1 = seq;
1913 		log.u_bbr.flex2 = count;
1914 		log.u_bbr.flex8 = mode;
1915 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1916 		    &bbr->rc_inp->inp_socket->so_rcv,
1917 		    &bbr->rc_inp->inp_socket->so_snd,
1918 		    BBR_LOG_LOWGAIN, 0,
1919 		    0, &log, false, &bbr->rc_tv);
1920 	}
1921 }
1922 
1923 static void
1924 bbr_log_type_just_return(struct tcp_bbr *bbr, uint32_t cts, uint32_t tlen, uint8_t hpts_calling,
1925     uint8_t reason, uint32_t p_maxseg, int len)
1926 {
1927 	if (tcp_bblogging_on(bbr->rc_tp)) {
1928 		union tcp_log_stackspecific log;
1929 
1930 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1931 		log.u_bbr.flex1 = p_maxseg;
1932 		log.u_bbr.flex2 = bbr->r_ctl.rc_hpts_flags;
1933 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
1934 		log.u_bbr.flex4 = reason;
1935 		log.u_bbr.flex5 = bbr->rc_in_persist;
1936 		log.u_bbr.flex6 = bbr->r_ctl.rc_last_delay_val;
1937 		log.u_bbr.flex7 = p_maxseg;
1938 		log.u_bbr.flex8 = bbr->rc_in_persist;
1939 		log.u_bbr.pkts_out = 0;
1940 		log.u_bbr.applimited = len;
1941 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1942 		    &bbr->rc_inp->inp_socket->so_rcv,
1943 		    &bbr->rc_inp->inp_socket->so_snd,
1944 		    BBR_LOG_JUSTRET, 0,
1945 		    tlen, &log, false, &bbr->rc_tv);
1946 	}
1947 }
1948 
1949 static void
1950 bbr_log_type_enter_rec(struct tcp_bbr *bbr, uint32_t seq)
1951 {
1952 	if (tcp_bblogging_on(bbr->rc_tp)) {
1953 		union tcp_log_stackspecific log;
1954 
1955 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
1956 		log.u_bbr.flex1 = seq;
1957 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
1958 		log.u_bbr.flex3 = bbr->r_ctl.rc_recovery_start;
1959 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
1960 		    &bbr->rc_inp->inp_socket->so_rcv,
1961 		    &bbr->rc_inp->inp_socket->so_snd,
1962 		    BBR_LOG_ENTREC, 0,
1963 		    0, &log, false, &bbr->rc_tv);
1964 	}
1965 }
1966 
1967 static void
1968 bbr_log_msgsize_fail(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t len, uint32_t maxseg, uint32_t mtu, int32_t csum_flags, int32_t tso, uint32_t cts)
1969 {
1970 	if (tcp_bblogging_on(tp)) {
1971 		union tcp_log_stackspecific log;
1972 
1973 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
1974 		log.u_bbr.flex1 = tso;
1975 		log.u_bbr.flex2 = maxseg;
1976 		log.u_bbr.flex3 = mtu;
1977 		log.u_bbr.flex4 = csum_flags;
1978 		TCP_LOG_EVENTP(tp, NULL,
1979 		    &bbr->rc_inp->inp_socket->so_rcv,
1980 		    &bbr->rc_inp->inp_socket->so_snd,
1981 		    BBR_LOG_MSGSIZE, 0,
1982 		    0, &log, false, &bbr->rc_tv);
1983 	}
1984 }
1985 
1986 static void
1987 bbr_log_flowend(struct tcp_bbr *bbr)
1988 {
1989 	if (tcp_bblogging_on(bbr->rc_tp)) {
1990 		union tcp_log_stackspecific log;
1991 		struct sockbuf *r, *s;
1992 		struct timeval tv;
1993 
1994 		if (bbr->rc_inp->inp_socket) {
1995 			r = &bbr->rc_inp->inp_socket->so_rcv;
1996 			s = &bbr->rc_inp->inp_socket->so_snd;
1997 		} else {
1998 			r = s = NULL;
1999 		}
2000 		bbr_fill_in_logging_data(bbr, &log.u_bbr, tcp_get_usecs(&tv));
2001 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2002 		    r, s,
2003 		    TCP_LOG_FLOWEND, 0,
2004 		    0, &log, false, &tv);
2005 	}
2006 }
2007 
2008 static void
2009 bbr_log_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line,
2010     uint32_t lost, uint32_t del)
2011 {
2012 	if (tcp_bblogging_on(bbr->rc_tp)) {
2013 		union tcp_log_stackspecific log;
2014 
2015 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2016 		log.u_bbr.flex1 = lost;
2017 		log.u_bbr.flex2 = del;
2018 		log.u_bbr.flex3 = bbr->r_ctl.rc_bbr_lastbtlbw;
2019 		log.u_bbr.flex4 = bbr->r_ctl.rc_pkt_epoch_rtt;
2020 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2021 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2022 		log.u_bbr.flex7 = line;
2023 		log.u_bbr.flex8 = 0;
2024 		log.u_bbr.inflight = bbr->r_ctl.r_measurement_count;
2025 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2026 		    &bbr->rc_inp->inp_socket->so_rcv,
2027 		    &bbr->rc_inp->inp_socket->so_snd,
2028 		    BBR_LOG_PKT_EPOCH, 0,
2029 		    0, &log, false, &bbr->rc_tv);
2030 	}
2031 }
2032 
2033 static void
2034 bbr_log_time_epoch(struct tcp_bbr *bbr, uint32_t cts, uint32_t line, uint32_t epoch_time)
2035 {
2036 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2037 		union tcp_log_stackspecific log;
2038 
2039 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2040 		log.u_bbr.flex1 = bbr->r_ctl.rc_lost;
2041 		log.u_bbr.flex2 = bbr->rc_inp->inp_socket->so_snd.sb_lowat;
2042 		log.u_bbr.flex3 = bbr->rc_inp->inp_socket->so_snd.sb_hiwat;
2043 		log.u_bbr.flex7 = line;
2044 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2045 		    &bbr->rc_inp->inp_socket->so_rcv,
2046 		    &bbr->rc_inp->inp_socket->so_snd,
2047 		    BBR_LOG_TIME_EPOCH, 0,
2048 		    0, &log, false, &bbr->rc_tv);
2049 	}
2050 }
2051 
2052 static void
2053 bbr_log_set_of_state_target(struct tcp_bbr *bbr, uint32_t new_tar, int line, int meth)
2054 {
2055 	if (tcp_bblogging_on(bbr->rc_tp)) {
2056 		union tcp_log_stackspecific log;
2057 
2058 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2059 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2060 		log.u_bbr.flex2 = new_tar;
2061 		log.u_bbr.flex3 = line;
2062 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2063 		log.u_bbr.flex5 = bbr_quanta;
2064 		log.u_bbr.flex6 = bbr->r_ctl.rc_pace_min_segs;
2065 		log.u_bbr.flex7 = bbr->rc_last_options;
2066 		log.u_bbr.flex8 = meth;
2067 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2068 		    &bbr->rc_inp->inp_socket->so_rcv,
2069 		    &bbr->rc_inp->inp_socket->so_snd,
2070 		    BBR_LOG_STATE_TARGET, 0,
2071 		    0, &log, false, &bbr->rc_tv);
2072 	}
2073 
2074 }
2075 
2076 static void
2077 bbr_log_type_statechange(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2078 {
2079 	if (tcp_bblogging_on(bbr->rc_tp)) {
2080 		union tcp_log_stackspecific log;
2081 
2082 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2083 		log.u_bbr.flex1 = line;
2084 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2085 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2086 		if (bbr_state_is_pkt_epoch)
2087 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
2088 		else
2089 			log.u_bbr.flex4 = bbr_get_rtt(bbr, BBR_RTT_PROP);
2090 		log.u_bbr.flex5 = bbr->r_ctl.rc_bbr_last_startup_epoch;
2091 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2092 		log.u_bbr.flex7 = (bbr->r_ctl.rc_target_at_state/1000);
2093 		log.u_bbr.lt_epoch = bbr->r_ctl.rc_level_state_extra;
2094 		log.u_bbr.pkts_out = bbr->r_ctl.rc_target_at_state;
2095 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2096 		    &bbr->rc_inp->inp_socket->so_rcv,
2097 		    &bbr->rc_inp->inp_socket->so_snd,
2098 		    BBR_LOG_STATE, 0,
2099 		    0, &log, false, &bbr->rc_tv);
2100 	}
2101 }
2102 
2103 static void
2104 bbr_log_rtt_shrinks(struct tcp_bbr *bbr, uint32_t cts, uint32_t applied,
2105 		    uint32_t rtt, uint32_t line, uint8_t reas, uint16_t cond)
2106 {
2107 	if (tcp_bblogging_on(bbr->rc_tp)) {
2108 		union tcp_log_stackspecific log;
2109 
2110 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2111 		log.u_bbr.flex1 = line;
2112 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2113 		log.u_bbr.flex3 = bbr->r_ctl.last_in_probertt;
2114 		log.u_bbr.flex4 = applied;
2115 		log.u_bbr.flex5 = rtt;
2116 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2117 		log.u_bbr.flex7 = cond;
2118 		log.u_bbr.flex8 = reas;
2119 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2120 		    &bbr->rc_inp->inp_socket->so_rcv,
2121 		    &bbr->rc_inp->inp_socket->so_snd,
2122 		    BBR_LOG_RTT_SHRINKS, 0,
2123 		    0, &log, false, &bbr->rc_tv);
2124 	}
2125 }
2126 
2127 static void
2128 bbr_log_type_exit_rec(struct tcp_bbr *bbr)
2129 {
2130 	if (tcp_bblogging_on(bbr->rc_tp)) {
2131 		union tcp_log_stackspecific log;
2132 
2133 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2134 		log.u_bbr.flex1 = bbr->r_ctl.rc_recovery_start;
2135 		log.u_bbr.flex2 = bbr->r_ctl.rc_cwnd_on_ent;
2136 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2137 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2138 		    &bbr->rc_inp->inp_socket->so_rcv,
2139 		    &bbr->rc_inp->inp_socket->so_snd,
2140 		    BBR_LOG_EXITREC, 0,
2141 		    0, &log, false, &bbr->rc_tv);
2142 	}
2143 }
2144 
2145 static void
2146 bbr_log_type_cwndupd(struct tcp_bbr *bbr, uint32_t bytes_this_ack, uint32_t chg,
2147     uint32_t prev_acked, int32_t meth, uint32_t target, uint32_t th_ack, int32_t line)
2148 {
2149 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2150 		union tcp_log_stackspecific log;
2151 
2152 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2153 		log.u_bbr.flex1 = line;
2154 		log.u_bbr.flex2 = prev_acked;
2155 		log.u_bbr.flex3 = bytes_this_ack;
2156 		log.u_bbr.flex4 = chg;
2157 		log.u_bbr.flex5 = th_ack;
2158 		log.u_bbr.flex6 = target;
2159 		log.u_bbr.flex8 = meth;
2160 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2161 		    &bbr->rc_inp->inp_socket->so_rcv,
2162 		    &bbr->rc_inp->inp_socket->so_snd,
2163 		    BBR_LOG_CWND, 0,
2164 		    0, &log, false, &bbr->rc_tv);
2165 	}
2166 }
2167 
2168 static void
2169 bbr_log_rtt_sample(struct tcp_bbr *bbr, uint32_t rtt, uint32_t tsin)
2170 {
2171 	/*
2172 	 * Log the rtt sample we are applying to the srtt algorithm in
2173 	 * useconds.
2174 	 */
2175 	if (tcp_bblogging_on(bbr->rc_tp)) {
2176 		union tcp_log_stackspecific log;
2177 
2178 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2179 		log.u_bbr.flex1 = rtt;
2180 		log.u_bbr.flex2 = bbr->r_ctl.rc_bbr_state_time;
2181 		log.u_bbr.flex3 = bbr->r_ctl.rc_ack_hdwr_delay;
2182 		log.u_bbr.flex4 = bbr->rc_tp->ts_offset;
2183 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2184 		log.u_bbr.pkts_out = tcp_tv_to_mssectick(&bbr->rc_tv);
2185 		log.u_bbr.flex6 = tsin;
2186 		log.u_bbr.flex7 = 0;
2187 		log.u_bbr.flex8 = bbr->rc_ack_was_delayed;
2188 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2189 		    &bbr->rc_inp->inp_socket->so_rcv,
2190 		    &bbr->rc_inp->inp_socket->so_snd,
2191 		    TCP_LOG_RTT, 0,
2192 		    0, &log, false, &bbr->rc_tv);
2193 	}
2194 }
2195 
2196 static void
2197 bbr_log_type_pesist(struct tcp_bbr *bbr, uint32_t cts, uint32_t time_in, int32_t line, uint8_t enter_exit)
2198 {
2199 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2200 		union tcp_log_stackspecific log;
2201 
2202 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2203 		log.u_bbr.flex1 = time_in;
2204 		log.u_bbr.flex2 = line;
2205 		log.u_bbr.flex8 = enter_exit;
2206 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2207 		    &bbr->rc_inp->inp_socket->so_rcv,
2208 		    &bbr->rc_inp->inp_socket->so_snd,
2209 		    BBR_LOG_PERSIST, 0,
2210 		    0, &log, false, &bbr->rc_tv);
2211 	}
2212 }
2213 static void
2214 bbr_log_ack_clear(struct tcp_bbr *bbr, uint32_t cts)
2215 {
2216 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2217 		union tcp_log_stackspecific log;
2218 
2219 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2220 		log.u_bbr.flex1 = bbr->rc_tp->ts_recent_age;
2221 		log.u_bbr.flex2 = bbr->r_ctl.rc_rtt_shrinks;
2222 		log.u_bbr.flex3 = bbr->r_ctl.rc_probertt_int;
2223 		log.u_bbr.flex4 = bbr->r_ctl.rc_went_idle_time;
2224 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2225 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2226 		    &bbr->rc_inp->inp_socket->so_rcv,
2227 		    &bbr->rc_inp->inp_socket->so_snd,
2228 		    BBR_LOG_ACKCLEAR, 0,
2229 		    0, &log, false, &bbr->rc_tv);
2230 	}
2231 }
2232 
2233 static void
2234 bbr_log_ack_event(struct tcp_bbr *bbr, struct tcphdr *th, struct tcpopt *to, uint32_t tlen,
2235 		  uint16_t nsegs, uint32_t cts, int32_t nxt_pkt, struct mbuf *m)
2236 {
2237 	if (tcp_bblogging_on(bbr->rc_tp)) {
2238 		union tcp_log_stackspecific log;
2239 		struct timeval tv;
2240 
2241 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2242 		log.u_bbr.flex1 = nsegs;
2243 		log.u_bbr.flex2 = bbr->r_ctl.rc_lost_bytes;
2244 		if (m) {
2245 			struct timespec ts;
2246 
2247 			log.u_bbr.flex3 = m->m_flags;
2248 			if (m->m_flags & M_TSTMP) {
2249 				mbuf_tstmp2timespec(m, &ts);
2250 				tv.tv_sec = ts.tv_sec;
2251 				tv.tv_usec = ts.tv_nsec / 1000;
2252 				log.u_bbr.lt_epoch = tcp_tv_to_usectick(&tv);
2253 			} else {
2254 				log.u_bbr.lt_epoch = 0;
2255 			}
2256 			if (m->m_flags & M_TSTMP_LRO) {
2257 				mbuf_tstmp2timeval(m, &tv);
2258 				log.u_bbr.flex5 = tcp_tv_to_usectick(&tv);
2259 			} else {
2260 				/* No arrival timestamp */
2261 				log.u_bbr.flex5 = 0;
2262 			}
2263 
2264 			log.u_bbr.pkts_out = tcp_get_usecs(&tv);
2265 		} else {
2266 			log.u_bbr.flex3 = 0;
2267 			log.u_bbr.flex5 = 0;
2268 			log.u_bbr.flex6 = 0;
2269 			log.u_bbr.pkts_out = 0;
2270 		}
2271 		log.u_bbr.flex4 = bbr->r_ctl.rc_target_at_state;
2272 		log.u_bbr.flex7 = bbr->r_wanted_output;
2273 		log.u_bbr.flex8 = bbr->rc_in_persist;
2274 		TCP_LOG_EVENTP(bbr->rc_tp, th,
2275 		    &bbr->rc_inp->inp_socket->so_rcv,
2276 		    &bbr->rc_inp->inp_socket->so_snd,
2277 		    TCP_LOG_IN, 0,
2278 		    tlen, &log, true, &bbr->rc_tv);
2279 	}
2280 }
2281 
2282 static void
2283 bbr_log_doseg_done(struct tcp_bbr *bbr, uint32_t cts, int32_t nxt_pkt, int32_t did_out)
2284 {
2285 	if (tcp_bblogging_on(bbr->rc_tp)) {
2286 		union tcp_log_stackspecific log;
2287 
2288 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2289 		log.u_bbr.flex1 = did_out;
2290 		log.u_bbr.flex2 = nxt_pkt;
2291 		log.u_bbr.flex3 = bbr->r_ctl.rc_last_delay_val;
2292 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2293 		log.u_bbr.flex5 = bbr->r_ctl.rc_timer_exp;
2294 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_bytes;
2295 		log.u_bbr.flex7 = bbr->r_wanted_output;
2296 		log.u_bbr.flex8 = bbr->rc_in_persist;
2297 		log.u_bbr.pkts_out = bbr->r_ctl.highest_hdwr_delay;
2298 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2299 		    &bbr->rc_inp->inp_socket->so_rcv,
2300 		    &bbr->rc_inp->inp_socket->so_snd,
2301 		    BBR_LOG_DOSEG_DONE, 0,
2302 		    0, &log, true, &bbr->rc_tv);
2303 	}
2304 }
2305 
2306 static void
2307 bbr_log_enobuf_jmp(struct tcp_bbr *bbr, uint32_t len, uint32_t cts,
2308     int32_t line, uint32_t o_len, uint32_t segcnt, uint32_t segsiz)
2309 {
2310 	if (tcp_bblogging_on(bbr->rc_tp)) {
2311 		union tcp_log_stackspecific log;
2312 
2313 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2314 		log.u_bbr.flex1 = line;
2315 		log.u_bbr.flex2 = o_len;
2316 		log.u_bbr.flex3 = segcnt;
2317 		log.u_bbr.flex4 = segsiz;
2318 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2319 		    &bbr->rc_inp->inp_socket->so_rcv,
2320 		    &bbr->rc_inp->inp_socket->so_snd,
2321 		    BBR_LOG_ENOBUF_JMP, ENOBUFS,
2322 		    len, &log, true, &bbr->rc_tv);
2323 	}
2324 }
2325 
2326 static void
2327 bbr_log_to_processing(struct tcp_bbr *bbr, uint32_t cts, int32_t ret, int32_t timers, uint8_t hpts_calling)
2328 {
2329 	if (tcp_bblogging_on(bbr->rc_tp)) {
2330 		union tcp_log_stackspecific log;
2331 
2332 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2333 		log.u_bbr.flex1 = timers;
2334 		log.u_bbr.flex2 = ret;
2335 		log.u_bbr.flex3 = bbr->r_ctl.rc_timer_exp;
2336 		log.u_bbr.flex4 = bbr->r_ctl.rc_hpts_flags;
2337 		log.u_bbr.flex5 = cts;
2338 		log.u_bbr.flex6 = bbr->r_ctl.rc_target_at_state;
2339 		log.u_bbr.flex8 = hpts_calling;
2340 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2341 		    &bbr->rc_inp->inp_socket->so_rcv,
2342 		    &bbr->rc_inp->inp_socket->so_snd,
2343 		    BBR_LOG_TO_PROCESS, 0,
2344 		    0, &log, false, &bbr->rc_tv);
2345 	}
2346 }
2347 
2348 static void
2349 bbr_log_to_event(struct tcp_bbr *bbr, uint32_t cts, int32_t to_num)
2350 {
2351 	if (tcp_bblogging_on(bbr->rc_tp)) {
2352 		union tcp_log_stackspecific log;
2353 		uint64_t ar;
2354 
2355 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2356 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2357 		log.u_bbr.flex2 = 0;
2358 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2359 		ar = (uintptr_t)(bbr->r_ctl.rc_resend);
2360 		ar >>= 32;
2361 		ar &= 0x00000000ffffffff;
2362 		log.u_bbr.flex4 = (uint32_t)ar;
2363 		ar = (uintptr_t)bbr->r_ctl.rc_resend;
2364 		ar &= 0x00000000ffffffff;
2365 		log.u_bbr.flex5 = (uint32_t)ar;
2366 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2367 		log.u_bbr.flex8 = to_num;
2368 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2369 		    &bbr->rc_inp->inp_socket->so_rcv,
2370 		    &bbr->rc_inp->inp_socket->so_snd,
2371 		    BBR_LOG_RTO, 0,
2372 		    0, &log, false, &bbr->rc_tv);
2373 	}
2374 }
2375 
2376 static void
2377 bbr_log_startup_event(struct tcp_bbr *bbr, uint32_t cts, uint32_t flex1, uint32_t flex2, uint32_t flex3, uint8_t reason)
2378 {
2379 	if (tcp_bblogging_on(bbr->rc_tp)) {
2380 		union tcp_log_stackspecific log;
2381 
2382 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2383 		log.u_bbr.flex1 = flex1;
2384 		log.u_bbr.flex2 = flex2;
2385 		log.u_bbr.flex3 = flex3;
2386 		log.u_bbr.flex4 = 0;
2387 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2388 		log.u_bbr.flex6 = bbr->r_ctl.rc_lost_at_startup;
2389 		log.u_bbr.flex8 = reason;
2390 		log.u_bbr.cur_del_rate = bbr->r_ctl.rc_bbr_lastbtlbw;
2391 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2392 		    &bbr->rc_inp->inp_socket->so_rcv,
2393 		    &bbr->rc_inp->inp_socket->so_snd,
2394 		    BBR_LOG_REDUCE, 0,
2395 		    0, &log, false, &bbr->rc_tv);
2396 	}
2397 }
2398 
2399 static void
2400 bbr_log_hpts_diag(struct tcp_bbr *bbr, uint32_t cts, struct hpts_diag *diag)
2401 {
2402 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2403 		union tcp_log_stackspecific log;
2404 
2405 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2406 		log.u_bbr.flex1 = diag->p_nxt_slot;
2407 		log.u_bbr.flex2 = diag->p_cur_slot;
2408 		log.u_bbr.flex3 = diag->slot_req;
2409 		log.u_bbr.flex4 = diag->inp_hptsslot;
2410 		log.u_bbr.flex5 = diag->slot_remaining;
2411 		log.u_bbr.flex6 = diag->need_new_to;
2412 		log.u_bbr.flex7 = diag->p_hpts_active;
2413 		log.u_bbr.flex8 = diag->p_on_min_sleep;
2414 		/* Hijack other fields as needed  */
2415 		log.u_bbr.epoch = diag->have_slept;
2416 		log.u_bbr.lt_epoch = diag->yet_to_sleep;
2417 		log.u_bbr.pkts_out = diag->co_ret;
2418 		log.u_bbr.applimited = diag->hpts_sleep_time;
2419 		log.u_bbr.delivered = diag->p_prev_slot;
2420 		log.u_bbr.inflight = diag->p_runningslot;
2421 		log.u_bbr.bw_inuse = diag->wheel_slot;
2422 		log.u_bbr.rttProp = diag->wheel_cts;
2423 		log.u_bbr.delRate = diag->maxslots;
2424 		log.u_bbr.cur_del_rate = diag->p_curtick;
2425 		log.u_bbr.cur_del_rate <<= 32;
2426 		log.u_bbr.cur_del_rate |= diag->p_lasttick;
2427 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2428 		    &bbr->rc_inp->inp_socket->so_rcv,
2429 		    &bbr->rc_inp->inp_socket->so_snd,
2430 		    BBR_LOG_HPTSDIAG, 0,
2431 		    0, &log, false, &bbr->rc_tv);
2432 	}
2433 }
2434 
2435 static void
2436 bbr_log_timer_var(struct tcp_bbr *bbr, int mode, uint32_t cts, uint32_t time_since_sent, uint32_t srtt,
2437     uint32_t thresh, uint32_t to)
2438 {
2439 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2440 		union tcp_log_stackspecific log;
2441 
2442 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2443 		log.u_bbr.flex1 = bbr->rc_tp->t_rttvar;
2444 		log.u_bbr.flex2 = time_since_sent;
2445 		log.u_bbr.flex3 = srtt;
2446 		log.u_bbr.flex4 = thresh;
2447 		log.u_bbr.flex5 = to;
2448 		log.u_bbr.flex6 = bbr->rc_tp->t_srtt;
2449 		log.u_bbr.flex8 = mode;
2450 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2451 		    &bbr->rc_inp->inp_socket->so_rcv,
2452 		    &bbr->rc_inp->inp_socket->so_snd,
2453 		    BBR_LOG_TIMERPREP, 0,
2454 		    0, &log, false, &bbr->rc_tv);
2455 	}
2456 }
2457 
2458 static void
2459 bbr_log_pacing_delay_calc(struct tcp_bbr *bbr, uint16_t gain, uint32_t len,
2460     uint32_t cts, uint32_t usecs, uint64_t bw, uint32_t override, int mod)
2461 {
2462 	if (tcp_bblogging_on(bbr->rc_tp)) {
2463 		union tcp_log_stackspecific log;
2464 
2465 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2466 		log.u_bbr.flex1 = usecs;
2467 		log.u_bbr.flex2 = len;
2468 		log.u_bbr.flex3 = (uint32_t)((bw >> 32) & 0x00000000ffffffff);
2469 		log.u_bbr.flex4 = (uint32_t)(bw & 0x00000000ffffffff);
2470 		if (override)
2471 			log.u_bbr.flex5 = (1 << 2);
2472 		else
2473 			log.u_bbr.flex5 = 0;
2474 		log.u_bbr.flex6 = override;
2475 		log.u_bbr.flex7 = gain;
2476 		log.u_bbr.flex8 = mod;
2477 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2478 		    &bbr->rc_inp->inp_socket->so_rcv,
2479 		    &bbr->rc_inp->inp_socket->so_snd,
2480 		    BBR_LOG_HPTSI_CALC, 0,
2481 		    len, &log, false, &bbr->rc_tv);
2482 	}
2483 }
2484 
2485 static void
2486 bbr_log_to_start(struct tcp_bbr *bbr, uint32_t cts, uint32_t to, int32_t slot, uint8_t which)
2487 {
2488 	if (tcp_bblogging_on(bbr->rc_tp)) {
2489 		union tcp_log_stackspecific log;
2490 
2491 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2492 
2493 		log.u_bbr.flex1 = bbr->bbr_timer_src;
2494 		log.u_bbr.flex2 = to;
2495 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2496 		log.u_bbr.flex4 = slot;
2497 		log.u_bbr.flex5 = bbr->rc_tp->t_hpts_slot;
2498 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2499 		log.u_bbr.pkts_out = bbr->rc_tp->t_flags2;
2500 		log.u_bbr.flex8 = which;
2501 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2502 		    &bbr->rc_inp->inp_socket->so_rcv,
2503 		    &bbr->rc_inp->inp_socket->so_snd,
2504 		    BBR_LOG_TIMERSTAR, 0,
2505 		    0, &log, false, &bbr->rc_tv);
2506 	}
2507 }
2508 
2509 static void
2510 bbr_log_thresh_choice(struct tcp_bbr *bbr, uint32_t cts, uint32_t thresh, uint32_t lro, uint32_t srtt, struct bbr_sendmap *rsm, uint8_t frm)
2511 {
2512 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2513 		union tcp_log_stackspecific log;
2514 
2515 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2516 		log.u_bbr.flex1 = thresh;
2517 		log.u_bbr.flex2 = lro;
2518 		log.u_bbr.flex3 = bbr->r_ctl.rc_reorder_ts;
2519 		log.u_bbr.flex4 = rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)];
2520 		log.u_bbr.flex5 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2521 		log.u_bbr.flex6 = srtt;
2522 		log.u_bbr.flex7 = bbr->r_ctl.rc_reorder_shift;
2523 		log.u_bbr.flex8 = frm;
2524 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2525 		    &bbr->rc_inp->inp_socket->so_rcv,
2526 		    &bbr->rc_inp->inp_socket->so_snd,
2527 		    BBR_LOG_THRESH_CALC, 0,
2528 		    0, &log, false, &bbr->rc_tv);
2529 	}
2530 }
2531 
2532 static void
2533 bbr_log_to_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts, uint8_t hpts_removed)
2534 {
2535 	if (tcp_bblogging_on(bbr->rc_tp)) {
2536 		union tcp_log_stackspecific log;
2537 
2538 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2539 		log.u_bbr.flex1 = line;
2540 		log.u_bbr.flex2 = bbr->bbr_timer_src;
2541 		log.u_bbr.flex3 = bbr->r_ctl.rc_hpts_flags;
2542 		log.u_bbr.flex4 = bbr->rc_in_persist;
2543 		log.u_bbr.flex5 = bbr->r_ctl.rc_target_at_state;
2544 		log.u_bbr.flex6 = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
2545 		log.u_bbr.flex8 = hpts_removed;
2546 		log.u_bbr.pkts_out = bbr->rc_pacer_started;
2547 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2548 		    &bbr->rc_inp->inp_socket->so_rcv,
2549 		    &bbr->rc_inp->inp_socket->so_snd,
2550 		    BBR_LOG_TIMERCANC, 0,
2551 		    0, &log, false, &bbr->rc_tv);
2552 	}
2553 }
2554 
2555 static void
2556 bbr_log_tstmp_validation(struct tcp_bbr *bbr, uint64_t peer_delta, uint64_t delta)
2557 {
2558 	if (tcp_bblogging_on(bbr->rc_tp)) {
2559 		union tcp_log_stackspecific log;
2560 
2561 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2562 		log.u_bbr.flex1 = bbr->r_ctl.bbr_peer_tsratio;
2563 		log.u_bbr.flex2 = (peer_delta >> 32);
2564 		log.u_bbr.flex3 = (peer_delta & 0x00000000ffffffff);
2565 		log.u_bbr.flex4 = (delta >> 32);
2566 		log.u_bbr.flex5 = (delta & 0x00000000ffffffff);
2567 		log.u_bbr.flex7 = bbr->rc_ts_clock_set;
2568 		log.u_bbr.flex8 = bbr->rc_ts_cant_be_used;
2569 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2570 		    &bbr->rc_inp->inp_socket->so_rcv,
2571 		    &bbr->rc_inp->inp_socket->so_snd,
2572 		    BBR_LOG_TSTMP_VAL, 0,
2573 		    0, &log, false, &bbr->rc_tv);
2574 	}
2575 }
2576 
2577 static void
2578 bbr_log_type_tsosize(struct tcp_bbr *bbr, uint32_t cts, uint32_t tsosz, uint32_t tls, uint32_t old_val, uint32_t maxseg, int hdwr)
2579 {
2580 	if (tcp_bblogging_on(bbr->rc_tp)) {
2581 		union tcp_log_stackspecific log;
2582 
2583 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2584 		log.u_bbr.flex1 = tsosz;
2585 		log.u_bbr.flex2 = tls;
2586 		log.u_bbr.flex3 = tcp_min_hptsi_time;
2587 		log.u_bbr.flex4 = bbr->r_ctl.bbr_hptsi_bytes_min;
2588 		log.u_bbr.flex5 = old_val;
2589 		log.u_bbr.flex6 = maxseg;
2590 		log.u_bbr.flex7 = bbr->rc_no_pacing;
2591 		log.u_bbr.flex7 <<= 1;
2592 		log.u_bbr.flex7 |= bbr->rc_past_init_win;
2593 		if (hdwr)
2594 			log.u_bbr.flex8 = 0x80 | bbr->rc_use_google;
2595 		else
2596 			log.u_bbr.flex8 = bbr->rc_use_google;
2597 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2598 		    &bbr->rc_inp->inp_socket->so_rcv,
2599 		    &bbr->rc_inp->inp_socket->so_snd,
2600 		    BBR_LOG_BBRTSO, 0,
2601 		    0, &log, false, &bbr->rc_tv);
2602 	}
2603 }
2604 
2605 static void
2606 bbr_log_type_rsmclear(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm,
2607 		      uint32_t flags, uint32_t line)
2608 {
2609 	if (tcp_bblogging_on(bbr->rc_tp)) {
2610 		union tcp_log_stackspecific log;
2611 
2612 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2613 		log.u_bbr.flex1 = line;
2614 		log.u_bbr.flex2 = rsm->r_start;
2615 		log.u_bbr.flex3 = rsm->r_end;
2616 		log.u_bbr.flex4 = rsm->r_delivered;
2617 		log.u_bbr.flex5 = rsm->r_rtr_cnt;
2618 		log.u_bbr.flex6 = rsm->r_dupack;
2619 		log.u_bbr.flex7 = rsm->r_tim_lastsent[0];
2620 		log.u_bbr.flex8 = rsm->r_flags;
2621 		/* Hijack the pkts_out fids */
2622 		log.u_bbr.applimited = flags;
2623 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2624 		    &bbr->rc_inp->inp_socket->so_rcv,
2625 		    &bbr->rc_inp->inp_socket->so_snd,
2626 		    BBR_RSM_CLEARED, 0,
2627 		    0, &log, false, &bbr->rc_tv);
2628 	}
2629 }
2630 
2631 static void
2632 bbr_log_type_bbrupd(struct tcp_bbr *bbr, uint8_t flex8, uint32_t cts,
2633     uint32_t flex3, uint32_t flex2, uint32_t flex5,
2634     uint32_t flex6, uint32_t pkts_out, int flex7,
2635     uint32_t flex4, uint32_t flex1)
2636 {
2637 
2638 	if (tcp_bblogging_on(bbr->rc_tp)) {
2639 		union tcp_log_stackspecific log;
2640 
2641 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2642 		log.u_bbr.flex1 = flex1;
2643 		log.u_bbr.flex2 = flex2;
2644 		log.u_bbr.flex3 = flex3;
2645 		log.u_bbr.flex4 = flex4;
2646 		log.u_bbr.flex5 = flex5;
2647 		log.u_bbr.flex6 = flex6;
2648 		log.u_bbr.flex7 = flex7;
2649 		/* Hijack the pkts_out fids */
2650 		log.u_bbr.pkts_out = pkts_out;
2651 		log.u_bbr.flex8 = flex8;
2652 		if (bbr->rc_ack_was_delayed)
2653 			log.u_bbr.epoch = bbr->r_ctl.rc_ack_hdwr_delay;
2654 		else
2655 			log.u_bbr.epoch = 0;
2656 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2657 		    &bbr->rc_inp->inp_socket->so_rcv,
2658 		    &bbr->rc_inp->inp_socket->so_snd,
2659 		    BBR_LOG_BBRUPD, 0,
2660 		    flex2, &log, false, &bbr->rc_tv);
2661 	}
2662 }
2663 
2664 static void
2665 bbr_log_type_ltbw(struct tcp_bbr *bbr, uint32_t cts, int32_t reason,
2666 	uint32_t newbw, uint32_t obw, uint32_t diff,
2667 	uint32_t tim)
2668 {
2669 	if (/*bbr_verbose_logging && */tcp_bblogging_on(bbr->rc_tp)) {
2670 		union tcp_log_stackspecific log;
2671 
2672 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2673 		log.u_bbr.flex1 = reason;
2674 		log.u_bbr.flex2 = newbw;
2675 		log.u_bbr.flex3 = obw;
2676 		log.u_bbr.flex4 = diff;
2677 		log.u_bbr.flex5 = bbr->r_ctl.rc_lt_lost;
2678 		log.u_bbr.flex6 = bbr->r_ctl.rc_lt_del;
2679 		log.u_bbr.flex7 = bbr->rc_lt_is_sampling;
2680 		log.u_bbr.pkts_out = tim;
2681 		log.u_bbr.bw_inuse = bbr->r_ctl.rc_lt_bw;
2682 		if (bbr->rc_lt_use_bw == 0)
2683 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
2684 		else
2685 			log.u_bbr.epoch = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
2686 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2687 		    &bbr->rc_inp->inp_socket->so_rcv,
2688 		    &bbr->rc_inp->inp_socket->so_snd,
2689 		    BBR_LOG_BWSAMP, 0,
2690 		    0, &log, false, &bbr->rc_tv);
2691 	}
2692 }
2693 
2694 static inline void
2695 bbr_log_progress_event(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t tick, int event, int line)
2696 {
2697 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2698 		union tcp_log_stackspecific log;
2699 
2700 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2701 		log.u_bbr.flex1 = line;
2702 		log.u_bbr.flex2 = tick;
2703 		log.u_bbr.flex3 = tp->t_maxunacktime;
2704 		log.u_bbr.flex4 = tp->t_acktime;
2705 		log.u_bbr.flex8 = event;
2706 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2707 		    &bbr->rc_inp->inp_socket->so_rcv,
2708 		    &bbr->rc_inp->inp_socket->so_snd,
2709 		    BBR_LOG_PROGRESS, 0,
2710 		    0, &log, false, &bbr->rc_tv);
2711 	}
2712 }
2713 
2714 static void
2715 bbr_type_log_hdwr_pacing(struct tcp_bbr *bbr, const struct ifnet *ifp,
2716 			 uint64_t rate, uint64_t hw_rate, int line, uint32_t cts,
2717 			 int error)
2718 {
2719 	if (tcp_bblogging_on(bbr->rc_tp)) {
2720 		union tcp_log_stackspecific log;
2721 		uint64_t ifp64 = (uintptr_t)ifp;
2722 
2723 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2724 		log.u_bbr.flex1 = ((hw_rate >> 32) & 0x00000000ffffffff);
2725 		log.u_bbr.flex2 = (hw_rate & 0x00000000ffffffff);
2726 		log.u_bbr.flex3 = ((ifp64  >> 32) & 0x00000000ffffffff);
2727 		log.u_bbr.flex4 = (ifp64 & 0x00000000ffffffff);
2728 		log.u_bbr.bw_inuse = rate;
2729 		log.u_bbr.flex5 = line;
2730 		log.u_bbr.flex6 = error;
2731 		log.u_bbr.flex8 = bbr->skip_gain;
2732 		log.u_bbr.flex8 <<= 1;
2733 		log.u_bbr.flex8 |= bbr->gain_is_limited;
2734 		log.u_bbr.flex8 <<= 1;
2735 		log.u_bbr.flex8 |= bbr->bbr_hdrw_pacing;
2736 		log.u_bbr.pkts_out = bbr->rc_tp->t_maxseg;
2737 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2738 		    &bbr->rc_inp->inp_socket->so_rcv,
2739 		    &bbr->rc_inp->inp_socket->so_snd,
2740 		    BBR_LOG_HDWR_PACE, 0,
2741 		    0, &log, false, &bbr->rc_tv);
2742 	}
2743 }
2744 
2745 static void
2746 bbr_log_type_bbrsnd(struct tcp_bbr *bbr, uint32_t len, uint32_t slot, uint32_t del_by, uint32_t cts, uint32_t line, uint32_t prev_delay)
2747 {
2748 	if (tcp_bblogging_on(bbr->rc_tp)) {
2749 		union tcp_log_stackspecific log;
2750 
2751 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2752 		log.u_bbr.flex1 = slot;
2753 		log.u_bbr.flex2 = del_by;
2754 		log.u_bbr.flex3 = prev_delay;
2755 		log.u_bbr.flex4 = line;
2756 		log.u_bbr.flex5 = bbr->r_ctl.rc_last_delay_val;
2757 		log.u_bbr.flex6 = bbr->r_ctl.rc_hptsi_agg_delay;
2758 		log.u_bbr.flex7 = (0x0000ffff & bbr->r_ctl.rc_hpts_flags);
2759 		log.u_bbr.flex8 = bbr->rc_in_persist;
2760 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2761 		    &bbr->rc_inp->inp_socket->so_rcv,
2762 		    &bbr->rc_inp->inp_socket->so_snd,
2763 		    BBR_LOG_BBRSND, 0,
2764 		    len, &log, false, &bbr->rc_tv);
2765 	}
2766 }
2767 
2768 static void
2769 bbr_log_type_bbrrttprop(struct tcp_bbr *bbr, uint32_t t, uint32_t end, uint32_t tsconv, uint32_t cts, int32_t match, uint32_t seq, uint8_t flags)
2770 {
2771 	if (tcp_bblogging_on(bbr->rc_tp)) {
2772 		union tcp_log_stackspecific log;
2773 
2774 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2775 		log.u_bbr.flex1 = bbr->r_ctl.rc_delivered;
2776 		log.u_bbr.flex2 = 0;
2777 		log.u_bbr.flex3 = bbr->r_ctl.rc_lowest_rtt;
2778 		log.u_bbr.flex4 = end;
2779 		log.u_bbr.flex5 = seq;
2780 		log.u_bbr.flex6 = t;
2781 		log.u_bbr.flex7 = match;
2782 		log.u_bbr.flex8 = flags;
2783 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2784 		    &bbr->rc_inp->inp_socket->so_rcv,
2785 		    &bbr->rc_inp->inp_socket->so_snd,
2786 		    BBR_LOG_BBRRTT, 0,
2787 		    0, &log, false, &bbr->rc_tv);
2788 	}
2789 }
2790 
2791 static void
2792 bbr_log_exit_gain(struct tcp_bbr *bbr, uint32_t cts, int32_t entry_method)
2793 {
2794 	if (tcp_bblogging_on(bbr->rc_tp)) {
2795 		union tcp_log_stackspecific log;
2796 
2797 		bbr_fill_in_logging_data(bbr, &log.u_bbr, cts);
2798 		log.u_bbr.flex1 = bbr->r_ctl.rc_target_at_state;
2799 		log.u_bbr.flex2 = (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
2800 		log.u_bbr.flex3 = bbr->r_ctl.gain_epoch;
2801 		log.u_bbr.flex4 = bbr->r_ctl.rc_pace_max_segs;
2802 		log.u_bbr.flex5 = bbr->r_ctl.rc_pace_min_segs;
2803 		log.u_bbr.flex6 = bbr->r_ctl.rc_bbr_state_atflight;
2804 		log.u_bbr.flex7 = 0;
2805 		log.u_bbr.flex8 = entry_method;
2806 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2807 		    &bbr->rc_inp->inp_socket->so_rcv,
2808 		    &bbr->rc_inp->inp_socket->so_snd,
2809 		    BBR_LOG_EXIT_GAIN, 0,
2810 		    0, &log, false, &bbr->rc_tv);
2811 	}
2812 }
2813 
2814 static void
2815 bbr_log_settings_change(struct tcp_bbr *bbr, int settings_desired)
2816 {
2817 	if (bbr_verbose_logging && tcp_bblogging_on(bbr->rc_tp)) {
2818 		union tcp_log_stackspecific log;
2819 
2820 		bbr_fill_in_logging_data(bbr, &log.u_bbr, bbr->r_ctl.rc_rcvtime);
2821 		/* R-HU */
2822 		log.u_bbr.flex1 = 0;
2823 		log.u_bbr.flex2 = 0;
2824 		log.u_bbr.flex3 = 0;
2825 		log.u_bbr.flex4 = 0;
2826 		log.u_bbr.flex7 = 0;
2827 		log.u_bbr.flex8 = settings_desired;
2828 
2829 		TCP_LOG_EVENTP(bbr->rc_tp, NULL,
2830 		    &bbr->rc_inp->inp_socket->so_rcv,
2831 		    &bbr->rc_inp->inp_socket->so_snd,
2832 		    BBR_LOG_SETTINGS_CHG, 0,
2833 		    0, &log, false, &bbr->rc_tv);
2834 	}
2835 }
2836 
2837 /*
2838  * Returns the bw from the our filter.
2839  */
2840 static inline uint64_t
2841 bbr_get_full_bw(struct tcp_bbr *bbr)
2842 {
2843 	uint64_t bw;
2844 
2845 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2846 
2847 	return (bw);
2848 }
2849 
2850 static inline void
2851 bbr_set_pktepoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2852 {
2853 	uint64_t calclr;
2854 	uint32_t lost, del;
2855 
2856 	if (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_pktepoch)
2857 		lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lost_at_pktepoch;
2858 	else
2859 		lost = 0;
2860 	del = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_pkt_epoch_del;
2861 	if (lost == 0)  {
2862 		calclr = 0;
2863 	} else if (del) {
2864 		calclr = lost;
2865 		calclr *= (uint64_t)1000;
2866 		calclr /= (uint64_t)del;
2867 	} else {
2868 		/* Nothing delivered? 100.0% loss */
2869 		calclr = 1000;
2870 	}
2871 	bbr->r_ctl.rc_pkt_epoch_loss_rate =  (uint32_t)calclr;
2872 	if (IN_RECOVERY(bbr->rc_tp->t_flags))
2873 		bbr->r_ctl.recovery_lr += (uint32_t)calclr;
2874 	bbr->r_ctl.rc_pkt_epoch++;
2875 	if (bbr->rc_no_pacing &&
2876 	    (bbr->r_ctl.rc_pkt_epoch >= bbr->no_pacing_until)) {
2877 		bbr->rc_no_pacing = 0;
2878 		tcp_bbr_tso_size_check(bbr, cts);
2879 	}
2880 	bbr->r_ctl.rc_pkt_epoch_rtt = bbr_calc_time(cts, bbr->r_ctl.rc_pkt_epoch_time);
2881 	bbr->r_ctl.rc_pkt_epoch_time = cts;
2882 	/* What was our loss rate */
2883 	bbr_log_pkt_epoch(bbr, cts, line, lost, del);
2884 	bbr->r_ctl.rc_pkt_epoch_del = bbr->r_ctl.rc_delivered;
2885 	bbr->r_ctl.rc_lost_at_pktepoch = bbr->r_ctl.rc_lost;
2886 }
2887 
2888 static inline void
2889 bbr_set_epoch(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
2890 {
2891 	uint32_t epoch_time;
2892 
2893 	/* Tick the RTT clock */
2894 	bbr->r_ctl.rc_rtt_epoch++;
2895 	epoch_time = cts - bbr->r_ctl.rc_rcv_epoch_start;
2896 	bbr_log_time_epoch(bbr, cts, line, epoch_time);
2897 	bbr->r_ctl.rc_rcv_epoch_start = cts;
2898 }
2899 
2900 static inline void
2901 bbr_isit_a_pkt_epoch(struct tcp_bbr *bbr, uint32_t cts, struct bbr_sendmap *rsm, int32_t line, int32_t cum_acked)
2902 {
2903 	if (SEQ_GEQ(rsm->r_delivered, bbr->r_ctl.rc_pkt_epoch_del)) {
2904 		bbr->rc_is_pkt_epoch_now = 1;
2905 	}
2906 }
2907 
2908 /*
2909  * Returns the bw from either the b/w filter
2910  * or from the lt_bw (if the connection is being
2911  * policed).
2912  */
2913 static inline uint64_t
2914 __bbr_get_bw(struct tcp_bbr *bbr)
2915 {
2916 	uint64_t bw, min_bw;
2917 	uint64_t rtt;
2918 	int gm_measure_cnt = 1;
2919 
2920 	/*
2921 	 * For startup we make, like google, a
2922 	 * minimum b/w. This is generated from the
2923 	 * IW and the rttProp. We do fall back to srtt
2924 	 * if for some reason (initial handshake) we don't
2925 	 * have a rttProp. We, in the worst case, fall back
2926 	 * to the configured min_bw (rc_initial_hptsi_bw).
2927 	 */
2928 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
2929 		/* Attempt first to use rttProp */
2930 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2931 		if (rtt && (rtt < 0xffffffff)) {
2932 measure:
2933 			min_bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2934 				((uint64_t)1000000);
2935 			min_bw /= rtt;
2936 			if (min_bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2937 				min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2938 			}
2939 
2940 		} else if (bbr->rc_tp->t_srtt != 0) {
2941 			/* No rttProp, use srtt? */
2942 			rtt = bbr_get_rtt(bbr, BBR_SRTT);
2943 			goto measure;
2944 		} else {
2945 			min_bw = bbr->r_ctl.rc_initial_hptsi_bw;
2946 		}
2947 	} else
2948 		min_bw = 0;
2949 
2950 	if ((bbr->rc_past_init_win == 0) &&
2951 	    (bbr->r_ctl.rc_delivered > bbr_initial_cwnd(bbr, bbr->rc_tp)))
2952 		bbr->rc_past_init_win = 1;
2953 	if ((bbr->rc_use_google)  && (bbr->r_ctl.r_measurement_count >= 1))
2954 		gm_measure_cnt = 0;
2955 	if (gm_measure_cnt &&
2956 	    ((bbr->r_ctl.r_measurement_count < bbr_min_measurements_req) ||
2957 	     (bbr->rc_past_init_win == 0))) {
2958 		/* For google we use our guess rate until we get 1 measurement */
2959 
2960 use_initial_window:
2961 		rtt = (uint64_t)get_filter_value_small(&bbr->r_ctl.rc_rttprop);
2962 		if (rtt && (rtt < 0xffffffff)) {
2963 			/*
2964 			 * We have an RTT measurement. Use that in
2965 			 * combination with our initial window to calculate
2966 			 * a b/w.
2967 			 */
2968 			bw = (uint64_t)(bbr_initial_cwnd(bbr, bbr->rc_tp)) *
2969 				((uint64_t)1000000);
2970 			bw /= rtt;
2971 			if (bw < bbr->r_ctl.rc_initial_hptsi_bw) {
2972 				bw = bbr->r_ctl.rc_initial_hptsi_bw;
2973 			}
2974 		} else {
2975 			/* Drop back to the 40 and punt to a default */
2976 			bw = bbr->r_ctl.rc_initial_hptsi_bw;
2977 		}
2978 		if (bw < 1)
2979 			/* Probably should panic */
2980 			bw = 1;
2981 		if (bw > min_bw)
2982 			return (bw);
2983 		else
2984 			return (min_bw);
2985 	}
2986 	if (bbr->rc_lt_use_bw)
2987 		bw = bbr->r_ctl.rc_lt_bw;
2988 	else if (bbr->r_recovery_bw && (bbr->rc_use_google == 0))
2989 		bw = bbr->r_ctl.red_bw;
2990 	else
2991 		bw = get_filter_value(&bbr->r_ctl.rc_delrate);
2992 	if (bw == 0) {
2993 		/* We should not be at 0, go to the initial window then  */
2994 		goto use_initial_window;
2995 	}
2996 	if (bw < 1)
2997 		/* Probably should panic */
2998 		bw = 1;
2999 	if (bw < min_bw)
3000 		bw = min_bw;
3001 	return (bw);
3002 }
3003 
3004 static inline uint64_t
3005 bbr_get_bw(struct tcp_bbr *bbr)
3006 {
3007 	uint64_t bw;
3008 
3009 	bw = __bbr_get_bw(bbr);
3010 	return (bw);
3011 }
3012 
3013 static inline void
3014 bbr_reset_lt_bw_interval(struct tcp_bbr *bbr, uint32_t cts)
3015 {
3016 	bbr->r_ctl.rc_lt_epoch = bbr->r_ctl.rc_pkt_epoch;
3017 	bbr->r_ctl.rc_lt_time = bbr->r_ctl.rc_del_time;
3018 	bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3019 	bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3020 }
3021 
3022 static inline void
3023 bbr_reset_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts)
3024 {
3025 	bbr->rc_lt_is_sampling = 0;
3026 	bbr->rc_lt_use_bw = 0;
3027 	bbr->r_ctl.rc_lt_bw = 0;
3028 	bbr_reset_lt_bw_interval(bbr, cts);
3029 }
3030 
3031 static inline void
3032 bbr_lt_bw_samp_done(struct tcp_bbr *bbr, uint64_t bw, uint32_t cts, uint32_t timin)
3033 {
3034 	uint64_t diff;
3035 
3036 	/* Do we have a previous sample? */
3037 	if (bbr->r_ctl.rc_lt_bw) {
3038 		/* Get the diff in bytes per second */
3039 		if (bbr->r_ctl.rc_lt_bw > bw)
3040 			diff = bbr->r_ctl.rc_lt_bw - bw;
3041 		else
3042 			diff = bw - bbr->r_ctl.rc_lt_bw;
3043 		if ((diff <= bbr_lt_bw_diff) ||
3044 		    (diff <= (bbr->r_ctl.rc_lt_bw / bbr_lt_bw_ratio))) {
3045 			/* Consider us policed */
3046 			uint32_t saved_bw;
3047 
3048 			saved_bw = (uint32_t)bbr->r_ctl.rc_lt_bw;
3049 			bbr->r_ctl.rc_lt_bw = (bw + bbr->r_ctl.rc_lt_bw) / 2;	/* average of two */
3050 			bbr->rc_lt_use_bw = 1;
3051 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
3052 			/*
3053 			 * Use pkt based epoch for measuring length of
3054 			 * policer up
3055 			 */
3056 			bbr->r_ctl.rc_lt_epoch_use = bbr->r_ctl.rc_pkt_epoch;
3057 			/*
3058 			 * reason 4 is we need to start consider being
3059 			 * policed
3060 			 */
3061 			bbr_log_type_ltbw(bbr, cts, 4, (uint32_t)bw, saved_bw, (uint32_t)diff, timin);
3062 			return;
3063 		}
3064 	}
3065 	bbr->r_ctl.rc_lt_bw = bw;
3066 	bbr_reset_lt_bw_interval(bbr, cts);
3067 	bbr_log_type_ltbw(bbr, cts, 5, 0, (uint32_t)bw, 0, timin);
3068 }
3069 
3070 static void
3071 bbr_randomize_extra_state_time(struct tcp_bbr *bbr)
3072 {
3073 	uint32_t ran, deduct;
3074 
3075 	ran = arc4random_uniform(bbr_rand_ot);
3076 	if (ran) {
3077 		deduct = bbr->r_ctl.rc_level_state_extra / ran;
3078 		bbr->r_ctl.rc_level_state_extra -= deduct;
3079 	}
3080 }
3081 /*
3082  * Return randomly the starting state
3083  * to use in probebw.
3084  */
3085 static uint8_t
3086 bbr_pick_probebw_substate(struct tcp_bbr *bbr, uint32_t cts)
3087 {
3088 	uint32_t ran;
3089 	uint8_t ret_val;
3090 
3091 	/* Initialize the offset to 0 */
3092 	bbr->r_ctl.rc_exta_time_gd = 0;
3093 	bbr->rc_hit_state_1 = 0;
3094 	bbr->r_ctl.rc_level_state_extra = 0;
3095 	ran = arc4random_uniform((BBR_SUBSTATE_COUNT-1));
3096 	/*
3097 	 * The math works funny here :) the return value is used to set the
3098 	 * substate and then the state change is called which increments by
3099 	 * one. So if we return 1 (DRAIN) we will increment to 2 (LEVEL1) when
3100 	 * we fully enter the state. Note that the (8 - 1 - ran) assures that
3101 	 * we return 1 - 7, so we dont return 0 and end up starting in
3102 	 * state 1 (DRAIN).
3103 	 */
3104 	ret_val = BBR_SUBSTATE_COUNT - 1 - ran;
3105 	/* Set an epoch */
3106 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP))
3107 		bbr_set_epoch(bbr, cts, __LINE__);
3108 
3109 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
3110 	return (ret_val);
3111 }
3112 
3113 static void
3114 bbr_lt_bw_sampling(struct tcp_bbr *bbr, uint32_t cts, int32_t loss_detected)
3115 {
3116 	uint32_t diff, d_time;
3117 	uint64_t del_time, bw, lost, delivered;
3118 
3119 	if (bbr->r_use_policer == 0)
3120 		return;
3121 	if (bbr->rc_lt_use_bw) {
3122 		/* We are using lt bw do we stop yet? */
3123 		diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch_use;
3124 		if (diff > bbr_lt_bw_max_rtts) {
3125 			/* Reset it all */
3126 reset_all:
3127 			bbr_reset_lt_bw_sampling(bbr, cts);
3128 			if (bbr->rc_filled_pipe) {
3129 				bbr_set_epoch(bbr, cts, __LINE__);
3130 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
3131 				bbr_substate_change(bbr, cts, __LINE__, 0);
3132 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
3133 				bbr_log_type_statechange(bbr, cts, __LINE__);
3134 			} else {
3135 				/*
3136 				 * This should not happen really
3137 				 * unless we remove the startup/drain
3138 				 * restrictions above.
3139 				 */
3140 				bbr->rc_bbr_state = BBR_STATE_STARTUP;
3141 				bbr_set_epoch(bbr, cts, __LINE__);
3142 				bbr->r_ctl.rc_bbr_state_time = cts;
3143 				bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
3144 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
3145 				bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
3146 				bbr_set_state_target(bbr, __LINE__);
3147 				bbr_log_type_statechange(bbr, cts, __LINE__);
3148 			}
3149 			/* reason 0 is to stop using lt-bw */
3150 			bbr_log_type_ltbw(bbr, cts, 0, 0, 0, 0, 0);
3151 			return;
3152 		}
3153 		if (bbr_lt_intvl_fp == 0) {
3154 			/* Not doing false-positive detection */
3155 			return;
3156 		}
3157 		/* False positive detection */
3158 		if (diff == bbr_lt_intvl_fp) {
3159 			/* At bbr_lt_intvl_fp we record the lost */
3160 			bbr->r_ctl.rc_lt_del = bbr->r_ctl.rc_delivered;
3161 			bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
3162 		} else if (diff > (bbr_lt_intvl_min_rtts + bbr_lt_intvl_fp)) {
3163 			/* Now is our loss rate still high? */
3164 			lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3165 			delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3166 			if ((delivered == 0) ||
3167 			    (((lost * 1000)/delivered) < bbr_lt_fd_thresh)) {
3168 				/* No still below our threshold */
3169 				bbr_log_type_ltbw(bbr, cts, 7, lost, delivered, 0, 0);
3170 			} else {
3171 				/* Yikes its still high, it must be a false positive */
3172 				bbr_log_type_ltbw(bbr, cts, 8, lost, delivered, 0, 0);
3173 				goto reset_all;
3174 			}
3175 		}
3176 		return;
3177 	}
3178 	/*
3179 	 * Wait for the first loss before sampling, to let the policer
3180 	 * exhaust its tokens and estimate the steady-state rate allowed by
3181 	 * the policer. Starting samples earlier includes bursts that
3182 	 * over-estimate the bw.
3183 	 */
3184 	if (bbr->rc_lt_is_sampling == 0) {
3185 		/* reason 1 is to begin doing the sampling  */
3186 		if (loss_detected == 0)
3187 			return;
3188 		bbr_reset_lt_bw_interval(bbr, cts);
3189 		bbr->rc_lt_is_sampling = 1;
3190 		bbr_log_type_ltbw(bbr, cts, 1, 0, 0, 0, 0);
3191 		return;
3192 	}
3193 	/* Now how long were we delivering long term last> */
3194 	if (TSTMP_GEQ(bbr->r_ctl.rc_del_time, bbr->r_ctl.rc_lt_time))
3195 		d_time = bbr->r_ctl.rc_del_time - bbr->r_ctl.rc_lt_time;
3196 	else
3197 		d_time = 0;
3198 
3199 	/* To avoid underestimates, reset sampling if we run out of data. */
3200 	if (bbr->r_ctl.r_app_limited_until) {
3201 		/* Can not measure in app-limited state */
3202 		bbr_reset_lt_bw_sampling(bbr, cts);
3203 		/* reason 2 is to reset sampling due to app limits  */
3204 		bbr_log_type_ltbw(bbr, cts, 2, 0, 0, 0, d_time);
3205 		return;
3206 	}
3207 	diff = bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_lt_epoch;
3208 	if (diff < bbr_lt_intvl_min_rtts) {
3209 		/*
3210 		 * need more samples (we don't
3211 		 * start on a round like linux so
3212 		 * we need 1 more).
3213 		 */
3214 		/* 6 is not_enough time or no-loss */
3215 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3216 		return;
3217 	}
3218 	if (diff > (4 * bbr_lt_intvl_min_rtts)) {
3219 		/*
3220 		 * For now if we wait too long, reset all sampling. We need
3221 		 * to do some research here, its possible that we should
3222 		 * base this on how much loss as occurred.. something like
3223 		 * if its under 10% (or some thresh) reset all otherwise
3224 		 * don't.  Thats for phase II I guess.
3225 		 */
3226 		bbr_reset_lt_bw_sampling(bbr, cts);
3227  		/* reason 3 is to reset sampling due too long of sampling */
3228 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3229 		return;
3230 	}
3231 	/*
3232 	 * End sampling interval when a packet is lost, so we estimate the
3233 	 * policer tokens were exhausted. Stopping the sampling before the
3234 	 * tokens are exhausted under-estimates the policed rate.
3235 	 */
3236 	if (loss_detected == 0) {
3237 		/* 6 is not_enough time or no-loss */
3238 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3239 		return;
3240 	}
3241 	/* Calculate packets lost and delivered in sampling interval. */
3242 	lost = bbr->r_ctl.rc_lost - bbr->r_ctl.rc_lt_lost;
3243 	delivered = bbr->r_ctl.rc_delivered - bbr->r_ctl.rc_lt_del;
3244 	if ((delivered == 0) ||
3245 	    (((lost * 1000)/delivered) < bbr_lt_loss_thresh)) {
3246 		bbr_log_type_ltbw(bbr, cts, 6, lost, delivered, 0, d_time);
3247 		return;
3248 	}
3249 	if (d_time < 1000) {
3250 		/* Not enough time. wait */
3251 		/* 6 is not_enough time or no-loss */
3252 		bbr_log_type_ltbw(bbr, cts, 6, 0, 0, 0, d_time);
3253 		return;
3254 	}
3255 	if (d_time >= (0xffffffff / USECS_IN_MSEC)) {
3256 		/* Too long */
3257 		bbr_reset_lt_bw_sampling(bbr, cts);
3258  		/* reason 3 is to reset sampling due too long of sampling */
3259 		bbr_log_type_ltbw(bbr, cts, 3, 0, 0, 0, d_time);
3260 		return;
3261 	}
3262 	del_time = d_time;
3263 	bw = delivered;
3264 	bw *= (uint64_t)USECS_IN_SECOND;
3265 	bw /= del_time;
3266 	bbr_lt_bw_samp_done(bbr, bw, cts, d_time);
3267 }
3268 
3269 /*
3270  * Allocate a sendmap from our zone.
3271  */
3272 static struct bbr_sendmap *
3273 bbr_alloc(struct tcp_bbr *bbr)
3274 {
3275 	struct bbr_sendmap *rsm;
3276 
3277 	BBR_STAT_INC(bbr_to_alloc);
3278 	rsm = uma_zalloc(bbr_zone, (M_NOWAIT | M_ZERO));
3279 	if (rsm) {
3280 		bbr->r_ctl.rc_num_maps_alloced++;
3281 		return (rsm);
3282 	}
3283 	if (bbr->r_ctl.rc_free_cnt) {
3284 		BBR_STAT_INC(bbr_to_alloc_emerg);
3285 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
3286 		TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
3287 		bbr->r_ctl.rc_free_cnt--;
3288 		return (rsm);
3289 	}
3290 	BBR_STAT_INC(bbr_to_alloc_failed);
3291 	return (NULL);
3292 }
3293 
3294 static struct bbr_sendmap *
3295 bbr_alloc_full_limit(struct tcp_bbr *bbr)
3296 {
3297 	if ((V_tcp_map_entries_limit > 0) &&
3298 	    (bbr->r_ctl.rc_num_maps_alloced >= V_tcp_map_entries_limit)) {
3299 		BBR_STAT_INC(bbr_alloc_limited);
3300 		if (!bbr->alloc_limit_reported) {
3301 			bbr->alloc_limit_reported = 1;
3302 			BBR_STAT_INC(bbr_alloc_limited_conns);
3303 		}
3304 		return (NULL);
3305 	}
3306 	return (bbr_alloc(bbr));
3307 }
3308 
3309 /* wrapper to allocate a sendmap entry, subject to a specific limit */
3310 static struct bbr_sendmap *
3311 bbr_alloc_limit(struct tcp_bbr *bbr, uint8_t limit_type)
3312 {
3313 	struct bbr_sendmap *rsm;
3314 
3315 	if (limit_type) {
3316 		/* currently there is only one limit type */
3317 		if (V_tcp_map_split_limit > 0 &&
3318 		    bbr->r_ctl.rc_num_split_allocs >= V_tcp_map_split_limit) {
3319 			BBR_STAT_INC(bbr_split_limited);
3320 			if (!bbr->alloc_limit_reported) {
3321 				bbr->alloc_limit_reported = 1;
3322 				BBR_STAT_INC(bbr_alloc_limited_conns);
3323 			}
3324 			return (NULL);
3325 		}
3326 	}
3327 
3328 	/* allocate and mark in the limit type, if set */
3329 	rsm = bbr_alloc(bbr);
3330 	if (rsm != NULL && limit_type) {
3331 		rsm->r_limit_type = limit_type;
3332 		bbr->r_ctl.rc_num_split_allocs++;
3333 	}
3334 	return (rsm);
3335 }
3336 
3337 static void
3338 bbr_free(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
3339 {
3340 	if (rsm->r_limit_type) {
3341 		/* currently there is only one limit type */
3342 		bbr->r_ctl.rc_num_split_allocs--;
3343 	}
3344 	if (rsm->r_is_smallmap)
3345 		bbr->r_ctl.rc_num_small_maps_alloced--;
3346 	if (bbr->r_ctl.rc_tlp_send == rsm)
3347 		bbr->r_ctl.rc_tlp_send = NULL;
3348 	if (bbr->r_ctl.rc_resend == rsm) {
3349 		bbr->r_ctl.rc_resend = NULL;
3350 	}
3351 	if (bbr->r_ctl.rc_next == rsm)
3352 		bbr->r_ctl.rc_next = NULL;
3353 	if (bbr->r_ctl.rc_sacklast == rsm)
3354 		bbr->r_ctl.rc_sacklast = NULL;
3355 	if (bbr->r_ctl.rc_free_cnt < bbr_min_req_free) {
3356 		memset(rsm, 0, sizeof(struct bbr_sendmap));
3357 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_free, rsm, r_next);
3358 		rsm->r_limit_type = 0;
3359 		bbr->r_ctl.rc_free_cnt++;
3360 		return;
3361 	}
3362 	bbr->r_ctl.rc_num_maps_alloced--;
3363 	uma_zfree(bbr_zone, rsm);
3364 }
3365 
3366 /*
3367  * Returns the BDP.
3368  */
3369 static uint64_t
3370 bbr_get_bw_delay_prod(uint64_t rtt, uint64_t bw) {
3371 	/*
3372 	 * Calculate the bytes in flight needed given the bw (in bytes per
3373 	 * second) and the specifyed rtt in useconds. We need to put out the
3374 	 * returned value per RTT to match that rate. Gain will normally
3375 	 * raise it up from there.
3376 	 *
3377 	 * This should not overflow as long as the bandwidth is below 1
3378 	 * TByte per second (bw < 10**12 = 2**40) and the rtt is smaller
3379 	 * than 1000 seconds (rtt < 10**3 * 10**6 = 10**9 = 2**30).
3380 	 */
3381 	uint64_t usec_per_sec;
3382 
3383 	usec_per_sec = USECS_IN_SECOND;
3384 	return ((rtt * bw) / usec_per_sec);
3385 }
3386 
3387 /*
3388  * Return the initial cwnd.
3389  */
3390 static uint32_t
3391 bbr_initial_cwnd(struct tcp_bbr *bbr, struct tcpcb *tp)
3392 {
3393 	uint32_t i_cwnd;
3394 
3395 	if (bbr->rc_init_win) {
3396 		i_cwnd = bbr->rc_init_win * tp->t_maxseg;
3397 	} else if (V_tcp_initcwnd_segments)
3398 		i_cwnd = min((V_tcp_initcwnd_segments * tp->t_maxseg),
3399 		    max(2 * tp->t_maxseg, 14600));
3400 	else if (V_tcp_do_rfc3390)
3401 		i_cwnd = min(4 * tp->t_maxseg,
3402 		    max(2 * tp->t_maxseg, 4380));
3403 	else {
3404 		/* Per RFC5681 Section 3.1 */
3405 		if (tp->t_maxseg > 2190)
3406 			i_cwnd = 2 * tp->t_maxseg;
3407 		else if (tp->t_maxseg > 1095)
3408 			i_cwnd = 3 * tp->t_maxseg;
3409 		else
3410 			i_cwnd = 4 * tp->t_maxseg;
3411 	}
3412 	return (i_cwnd);
3413 }
3414 
3415 /*
3416  * Given a specified gain, return the target
3417  * cwnd based on that gain.
3418  */
3419 static uint32_t
3420 bbr_get_raw_target_cwnd(struct tcp_bbr *bbr, uint32_t gain, uint64_t bw)
3421 {
3422 	uint64_t bdp, rtt;
3423 	uint32_t cwnd;
3424 
3425 	if ((get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) ||
3426 	    (bbr_get_full_bw(bbr) == 0)) {
3427 		/* No measurements yet */
3428 		return (bbr_initial_cwnd(bbr, bbr->rc_tp));
3429 	}
3430 	/*
3431 	 * Get bytes per RTT needed (rttProp is normally in
3432 	 * bbr_cwndtarget_rtt_touse)
3433 	 */
3434 	rtt = bbr_get_rtt(bbr, bbr_cwndtarget_rtt_touse);
3435 	/* Get the bdp from the two values */
3436 	bdp = bbr_get_bw_delay_prod(rtt, bw);
3437 	/* Now apply the gain */
3438 	cwnd = (uint32_t)(((bdp * ((uint64_t)gain)) + (uint64_t)(BBR_UNIT - 1)) / ((uint64_t)BBR_UNIT));
3439 
3440 	return (cwnd);
3441 }
3442 
3443 static uint32_t
3444 bbr_get_target_cwnd(struct tcp_bbr *bbr, uint64_t bw, uint32_t gain)
3445 {
3446 	uint32_t cwnd, mss;
3447 
3448 	mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
3449 	/* Get the base cwnd with gain rounded to a mss */
3450 	cwnd = roundup(bbr_get_raw_target_cwnd(bbr, bw, gain), mss);
3451 	/*
3452 	 * Add in N (2 default since we do not have a
3453 	 * fq layer to trap packets in) quanta's per the I-D
3454 	 * section 4.2.3.2 quanta adjust.
3455 	 */
3456 	cwnd += (bbr_quanta * bbr->r_ctl.rc_pace_max_segs);
3457 	if (bbr->rc_use_google) {
3458 		if((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3459 		   (bbr_state_val(bbr) == BBR_SUB_GAIN)) {
3460 			/*
3461 			 * The linux implementation adds
3462 			 * an extra 2 x mss in gain cycle which
3463 			 * is documented no-where except in the code.
3464 			 * so we add more for Neal undocumented feature
3465 			 */
3466 			cwnd += 2 * mss;
3467 		}
3468  		if ((cwnd / mss) & 0x1) {
3469 			/* Round up for odd num mss */
3470 			cwnd += mss;
3471 		}
3472 	}
3473 	/* Are we below the min cwnd? */
3474 	if (cwnd < get_min_cwnd(bbr))
3475 		return (get_min_cwnd(bbr));
3476 	return (cwnd);
3477 }
3478 
3479 static uint16_t
3480 bbr_gain_adjust(struct tcp_bbr *bbr, uint16_t gain)
3481 {
3482 	if (gain < 1)
3483 		gain = 1;
3484 	return (gain);
3485 }
3486 
3487 static uint32_t
3488 bbr_get_header_oh(struct tcp_bbr *bbr)
3489 {
3490 	int seg_oh;
3491 
3492 	seg_oh = 0;
3493 	if (bbr->r_ctl.rc_inc_tcp_oh) {
3494 		/* Do we include TCP overhead? */
3495 		seg_oh = (bbr->rc_last_options + sizeof(struct tcphdr));
3496 	}
3497 	if (bbr->r_ctl.rc_inc_ip_oh) {
3498 		/* Do we include IP overhead? */
3499 #ifdef INET6
3500 		if (bbr->r_is_v6) {
3501 			seg_oh += sizeof(struct ip6_hdr);
3502 		} else
3503 #endif
3504 		{
3505 
3506 #ifdef INET
3507 			seg_oh += sizeof(struct ip);
3508 #endif
3509 		}
3510 	}
3511 	if (bbr->r_ctl.rc_inc_enet_oh) {
3512 		/* Do we include the ethernet overhead?  */
3513 		seg_oh += sizeof(struct ether_header);
3514 	}
3515 	return(seg_oh);
3516 }
3517 
3518 static uint32_t
3519 bbr_get_pacing_length(struct tcp_bbr *bbr, uint16_t gain, uint32_t useconds_time, uint64_t bw)
3520 {
3521 	uint64_t divor, res, tim;
3522 
3523 	if (useconds_time == 0)
3524 		return (0);
3525 	gain = bbr_gain_adjust(bbr, gain);
3526 	divor = (uint64_t)USECS_IN_SECOND * (uint64_t)BBR_UNIT;
3527 	tim = useconds_time;
3528 	res = (tim * bw * gain) / divor;
3529 	if (res == 0)
3530 		res = 1;
3531 	return ((uint32_t)res);
3532 }
3533 
3534 /*
3535  * Given a gain and a length return the delay in useconds that
3536  * should be used to evenly space out packets
3537  * on the connection (based on the gain factor).
3538  */
3539 static uint32_t
3540 bbr_get_pacing_delay(struct tcp_bbr *bbr, uint16_t gain, int32_t len, uint32_t cts, int nolog)
3541 {
3542 	uint64_t bw, lentim, res;
3543 	uint32_t usecs, srtt, over = 0;
3544 	uint32_t seg_oh, num_segs, maxseg;
3545 
3546 	if (len == 0)
3547 		return (0);
3548 
3549 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
3550 	num_segs = (len + maxseg - 1) / maxseg;
3551 	if (bbr->rc_use_google == 0) {
3552 		seg_oh = bbr_get_header_oh(bbr);
3553 		len += (num_segs * seg_oh);
3554 	}
3555 	gain = bbr_gain_adjust(bbr, gain);
3556 	bw = bbr_get_bw(bbr);
3557 	if (bbr->rc_use_google) {
3558 		uint64_t cbw;
3559 
3560 		/*
3561 		 * Reduce the b/w by the google discount
3562 		 * factor 10 = 1%.
3563 		 */
3564 		cbw = bw *  (uint64_t)(1000 - bbr->r_ctl.bbr_google_discount);
3565 		cbw /= (uint64_t)1000;
3566 		/* We don't apply a discount if it results in 0 */
3567 		if (cbw > 0)
3568 			bw = cbw;
3569 	}
3570 	lentim = ((uint64_t)len *
3571 		  (uint64_t)USECS_IN_SECOND *
3572 		  (uint64_t)BBR_UNIT);
3573 	res = lentim / ((uint64_t)gain * bw);
3574 	if (res == 0)
3575 		res = 1;
3576 	usecs = (uint32_t)res;
3577 	srtt = bbr_get_rtt(bbr, BBR_SRTT);
3578 	if (bbr_hptsi_max_mul && bbr_hptsi_max_div &&
3579 	    (bbr->rc_use_google == 0) &&
3580 	    (usecs > ((srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div))) {
3581 		/*
3582 		 * We cannot let the delay be more than 1/2 the srtt time.
3583 		 * Otherwise we cannot pace out or send properly.
3584 		 */
3585 		over = usecs = (srtt * bbr_hptsi_max_mul) / bbr_hptsi_max_div;
3586 		BBR_STAT_INC(bbr_hpts_min_time);
3587 	}
3588 	if (!nolog)
3589 		bbr_log_pacing_delay_calc(bbr, gain, len, cts, usecs, bw, over, 1);
3590 	return (usecs);
3591 }
3592 
3593 static void
3594 bbr_ack_received(struct tcpcb *tp, struct tcp_bbr *bbr, struct tcphdr *th, uint32_t bytes_this_ack,
3595 		 uint32_t sack_changed, uint32_t prev_acked, int32_t line, uint32_t losses)
3596 {
3597 	uint64_t bw;
3598 	uint32_t cwnd, target_cwnd, saved_bytes, maxseg;
3599 	int32_t meth;
3600 
3601 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3602 
3603 #ifdef STATS
3604 	if ((tp->t_flags & TF_GPUTINPROG) &&
3605 	    SEQ_GEQ(th->th_ack, tp->gput_ack)) {
3606 		/*
3607 		 * Strech acks and compressed acks will cause this to
3608 		 * oscillate but we are doing it the same way as the main
3609 		 * stack so it will be compariable (though possibly not
3610 		 * ideal).
3611 		 */
3612 		int32_t cgput;
3613 		int64_t gput, time_stamp;
3614 
3615 		gput = (int64_t) (th->th_ack - tp->gput_seq) * 8;
3616 		time_stamp = max(1, ((bbr->r_ctl.rc_rcvtime - tp->gput_ts) / 1000));
3617 		cgput = gput / time_stamp;
3618 		stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_GPUT,
3619 					 cgput);
3620 		if (tp->t_stats_gput_prev > 0)
3621 			stats_voi_update_abs_s32(tp->t_stats,
3622 						 VOI_TCP_GPUT_ND,
3623 						 ((gput - tp->t_stats_gput_prev) * 100) /
3624 						 tp->t_stats_gput_prev);
3625 		tp->t_flags &= ~TF_GPUTINPROG;
3626 		tp->t_stats_gput_prev = cgput;
3627 	}
3628 #endif
3629 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3630 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
3631 		/* We don't change anything in probe-rtt */
3632 		return;
3633 	}
3634 	maxseg = tp->t_maxseg - bbr->rc_last_options;
3635 	saved_bytes = bytes_this_ack;
3636 	bytes_this_ack += sack_changed;
3637 	if (bytes_this_ack > prev_acked) {
3638 		bytes_this_ack -= prev_acked;
3639 		/*
3640 		 * A byte ack'd gives us a full mss
3641 		 * to be like linux i.e. they count packets.
3642 		 */
3643 		if ((bytes_this_ack < maxseg) && bbr->rc_use_google)
3644 			bytes_this_ack = maxseg;
3645 	} else {
3646 		/* Unlikely */
3647 		bytes_this_ack = 0;
3648 	}
3649 	cwnd = tp->snd_cwnd;
3650 	bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3651 	if (bw)
3652 		target_cwnd = bbr_get_target_cwnd(bbr,
3653 						  bw,
3654 						  (uint32_t)bbr->r_ctl.rc_bbr_cwnd_gain);
3655 	else
3656 		target_cwnd = bbr_initial_cwnd(bbr, bbr->rc_tp);
3657 	if (IN_RECOVERY(tp->t_flags) &&
3658 	    (bbr->bbr_prev_in_rec == 0)) {
3659 		/*
3660 		 * We are entering recovery and
3661 		 * thus packet conservation.
3662 		 */
3663 		bbr->pkt_conservation = 1;
3664 		bbr->r_ctl.rc_recovery_start = bbr->r_ctl.rc_rcvtime;
3665 		cwnd = ctf_flight_size(tp,
3666 				       (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3667 			bytes_this_ack;
3668 	}
3669 	if (IN_RECOVERY(tp->t_flags)) {
3670 		uint32_t flight;
3671 
3672 		bbr->bbr_prev_in_rec = 1;
3673 		if (cwnd > losses) {
3674 			cwnd -= losses;
3675 			if (cwnd < maxseg)
3676 				cwnd = maxseg;
3677 		} else
3678 			cwnd = maxseg;
3679 		flight = ctf_flight_size(tp,
3680 					 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3681 		bbr_log_type_cwndupd(bbr, flight, 0,
3682 				     losses, 10, 0, 0, line);
3683 		if (bbr->pkt_conservation) {
3684 			uint32_t time_in;
3685 
3686 			if (TSTMP_GEQ(bbr->r_ctl.rc_rcvtime, bbr->r_ctl.rc_recovery_start))
3687 				time_in = bbr->r_ctl.rc_rcvtime - bbr->r_ctl.rc_recovery_start;
3688 			else
3689 				time_in = 0;
3690 
3691 			if (time_in >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
3692 				/* Clear packet conservation after an rttProp */
3693 				bbr->pkt_conservation = 0;
3694 			} else {
3695 				if ((flight + bytes_this_ack) > cwnd)
3696 					cwnd = flight + bytes_this_ack;
3697 				if (cwnd < get_min_cwnd(bbr))
3698 					cwnd = get_min_cwnd(bbr);
3699 				tp->snd_cwnd = cwnd;
3700 				bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed,
3701 						     prev_acked, 1, target_cwnd, th->th_ack, line);
3702 				return;
3703 			}
3704 		}
3705 	} else
3706 		bbr->bbr_prev_in_rec = 0;
3707 	if ((bbr->rc_use_google == 0) && bbr->r_ctl.restrict_growth) {
3708 		bbr->r_ctl.restrict_growth--;
3709 		if (bytes_this_ack > maxseg)
3710 			bytes_this_ack = maxseg;
3711 	}
3712 	if (bbr->rc_filled_pipe) {
3713 		/*
3714 		 * Here we have exited startup and filled the pipe. We will
3715 		 * thus allow the cwnd to shrink to the target. We hit here
3716 		 * mostly.
3717 		 */
3718 		uint32_t s_cwnd;
3719 
3720 		meth = 2;
3721 		s_cwnd = min((cwnd + bytes_this_ack), target_cwnd);
3722 		if (s_cwnd > cwnd)
3723 			cwnd = s_cwnd;
3724 		else if (bbr_cwnd_may_shrink || bbr->rc_use_google || bbr->rc_no_pacing)
3725 			cwnd = s_cwnd;
3726 	} else {
3727 		/*
3728 		 * Here we are still in startup, we increase cwnd by what
3729 		 * has been acked.
3730 		 */
3731 		if ((cwnd < target_cwnd) ||
3732 		    (bbr->rc_past_init_win == 0)) {
3733 			meth = 3;
3734 			cwnd += bytes_this_ack;
3735 		} else {
3736 			/*
3737 			 * Method 4 means we are at target so no gain in
3738 			 * startup and past the initial window.
3739 			 */
3740 			meth = 4;
3741 		}
3742 	}
3743 	tp->snd_cwnd = max(cwnd, get_min_cwnd(bbr));
3744 	bbr_log_type_cwndupd(bbr, saved_bytes, sack_changed, prev_acked, meth, target_cwnd, th->th_ack, line);
3745 }
3746 
3747 static void
3748 tcp_bbr_partialack(struct tcpcb *tp)
3749 {
3750 	struct tcp_bbr *bbr;
3751 
3752 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3753 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3754 	if (ctf_flight_size(tp,
3755 		(bbr->r_ctl.rc_sacked  + bbr->r_ctl.rc_lost_bytes)) <=
3756 	    tp->snd_cwnd) {
3757 		bbr->r_wanted_output = 1;
3758 	}
3759 }
3760 
3761 static void
3762 bbr_post_recovery(struct tcpcb *tp)
3763 {
3764 	struct tcp_bbr *bbr;
3765 	uint32_t  flight;
3766 
3767 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3768 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3769 	/*
3770 	 * Here we just exit recovery.
3771 	 */
3772 	EXIT_RECOVERY(tp->t_flags);
3773 	/* Lock in our b/w reduction for the specified number of pkt-epochs */
3774 	bbr->r_recovery_bw = 0;
3775 	tp->snd_recover = tp->snd_una;
3776 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3777 	bbr->pkt_conservation = 0;
3778 	if (bbr->rc_use_google == 0) {
3779 		/*
3780 		 * For non-google mode lets
3781 		 * go ahead and make sure we clear
3782 		 * the recovery state so if we
3783 		 * bounce back in to recovery we
3784 		 * will do PC.
3785 		 */
3786 		bbr->bbr_prev_in_rec = 0;
3787 	}
3788 	bbr_log_type_exit_rec(bbr);
3789 	if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3790 		tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3791 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 15, 0, 0, __LINE__);
3792 	} else {
3793 		/* For probe-rtt case lets fix up its saved_cwnd */
3794 		if (bbr->r_ctl.rc_saved_cwnd < bbr->r_ctl.rc_cwnd_on_ent) {
3795 			bbr->r_ctl.rc_saved_cwnd = bbr->r_ctl.rc_cwnd_on_ent;
3796 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 16, 0, 0, __LINE__);
3797 		}
3798 	}
3799 	flight = ctf_flight_size(tp,
3800 		     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
3801 	if ((bbr->rc_use_google == 0) &&
3802 	    bbr_do_red) {
3803 		uint64_t val, lr2use;
3804 		uint32_t maxseg, newcwnd, acks_inflight, ratio, cwnd;
3805 		uint32_t *cwnd_p;
3806 
3807 		if (bbr_get_rtt(bbr, BBR_SRTT)) {
3808 			val = ((uint64_t)bbr_get_rtt(bbr, BBR_RTT_PROP) * (uint64_t)1000);
3809 			val /= bbr_get_rtt(bbr, BBR_SRTT);
3810 			ratio = (uint32_t)val;
3811 		} else
3812 			ratio = 1000;
3813 
3814 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div,
3815 				     bbr->r_ctl.recovery_lr, 21,
3816 				     ratio,
3817 				     bbr->r_ctl.rc_red_cwnd_pe,
3818 				     __LINE__);
3819 		if ((ratio < bbr_do_red) || (bbr_do_red == 0))
3820 			goto done;
3821 		if (((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
3822 		     bbr_prtt_slam_cwnd) ||
3823 		    (bbr_sub_drain_slam_cwnd &&
3824 		     (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
3825 		     bbr->rc_hit_state_1 &&
3826 		     (bbr_state_val(bbr) == BBR_SUB_DRAIN)) ||
3827 		    ((bbr->rc_bbr_state == BBR_STATE_DRAIN) &&
3828 		     bbr_slam_cwnd_in_main_drain)) {
3829 			/*
3830 			 * Here we must poke at the saved cwnd
3831 			 * as well as the cwnd.
3832 			 */
3833 			cwnd = bbr->r_ctl.rc_saved_cwnd;
3834 			cwnd_p = &bbr->r_ctl.rc_saved_cwnd;
3835 		} else {
3836  			cwnd = tp->snd_cwnd;
3837 			cwnd_p = &tp->snd_cwnd;
3838 		}
3839 		maxseg = tp->t_maxseg - bbr->rc_last_options;
3840 		/* Add the overall lr with the recovery lr */
3841 		if (bbr->r_ctl.rc_lost == 0)
3842 			lr2use = 0;
3843 		else if (bbr->r_ctl.rc_delivered == 0)
3844 			lr2use = 1000;
3845 		else {
3846 			lr2use = bbr->r_ctl.rc_lost * 1000;
3847 			lr2use /= bbr->r_ctl.rc_delivered;
3848 		}
3849 		lr2use += bbr->r_ctl.recovery_lr;
3850 		acks_inflight = (flight / (maxseg * 2));
3851 		if (bbr_red_scale) {
3852 			lr2use *= bbr_get_rtt(bbr, BBR_SRTT);
3853 			lr2use /= bbr_red_scale;
3854 			if ((bbr_red_growth_restrict) &&
3855 			    ((bbr_get_rtt(bbr, BBR_SRTT)/bbr_red_scale) > 1))
3856 			    bbr->r_ctl.restrict_growth += acks_inflight;
3857 		}
3858 		if (lr2use) {
3859 			val = (uint64_t)cwnd * lr2use;
3860 			val /= 1000;
3861 			if (cwnd > val)
3862 				newcwnd = roundup((cwnd - val), maxseg);
3863 			else
3864 				newcwnd = maxseg;
3865 		} else {
3866 			val = (uint64_t)cwnd * (uint64_t)bbr_red_mul;
3867 			val /= (uint64_t)bbr_red_div;
3868 			newcwnd = roundup((uint32_t)val, maxseg);
3869 		}
3870 		/* with standard delayed acks how many acks can I expect? */
3871 		if (bbr_drop_limit == 0) {
3872 			/*
3873 			 * Anticpate how much we will
3874 			 * raise the cwnd based on the acks.
3875 			 */
3876 			if ((newcwnd + (acks_inflight * maxseg)) < get_min_cwnd(bbr)) {
3877 				/* We do enforce the min (with the acks) */
3878 				newcwnd = (get_min_cwnd(bbr) - acks_inflight);
3879 			}
3880 		} else {
3881 			/*
3882 			 * A strict drop limit of N is inplace
3883 			 */
3884 			if (newcwnd < (bbr_drop_limit * maxseg)) {
3885 				newcwnd = bbr_drop_limit * maxseg;
3886 			}
3887 		}
3888 		/* For the next N acks do we restrict the growth */
3889 		*cwnd_p = newcwnd;
3890 		if (tp->snd_cwnd > newcwnd)
3891 			tp->snd_cwnd = newcwnd;
3892 		bbr_log_type_cwndupd(bbr, bbr_red_mul, bbr_red_div, val, 22,
3893 				     (uint32_t)lr2use,
3894 				     bbr_get_rtt(bbr, BBR_SRTT), __LINE__);
3895 		bbr->r_ctl.rc_red_cwnd_pe = bbr->r_ctl.rc_pkt_epoch;
3896 	}
3897 done:
3898 	bbr->r_ctl.recovery_lr = 0;
3899 	if (flight <= tp->snd_cwnd) {
3900 		bbr->r_wanted_output = 1;
3901 	}
3902 	tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3903 }
3904 
3905 static void
3906 bbr_setup_red_bw(struct tcp_bbr *bbr, uint32_t cts)
3907 {
3908 	bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
3909 	/* Limit the drop in b/w to 1/2 our current filter. */
3910 	if (bbr->r_ctl.red_bw > bbr->r_ctl.rc_bbr_cur_del_rate)
3911 		bbr->r_ctl.red_bw = bbr->r_ctl.rc_bbr_cur_del_rate;
3912 	if (bbr->r_ctl.red_bw < (get_filter_value(&bbr->r_ctl.rc_delrate) / 2))
3913 		bbr->r_ctl.red_bw = get_filter_value(&bbr->r_ctl.rc_delrate) / 2;
3914 	tcp_bbr_tso_size_check(bbr, cts);
3915 }
3916 
3917 static void
3918 bbr_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type, struct bbr_sendmap *rsm)
3919 {
3920 	struct tcp_bbr *bbr;
3921 
3922 	INP_WLOCK_ASSERT(tptoinpcb(tp));
3923 #ifdef STATS
3924 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_CSIG, type);
3925 #endif
3926 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
3927 	switch (type) {
3928 	case CC_NDUPACK:
3929 		if (!IN_RECOVERY(tp->t_flags)) {
3930 			tp->snd_recover = tp->snd_max;
3931 			/* Start a new epoch */
3932 			bbr_set_pktepoch(bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
3933 			if (bbr->rc_lt_is_sampling || bbr->rc_lt_use_bw) {
3934 				/*
3935 				 * Move forward the lt epoch
3936 				 * so it won't count the truncated
3937 				 * epoch.
3938 				 */
3939 				bbr->r_ctl.rc_lt_epoch++;
3940 			}
3941 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
3942 				/*
3943 				 * Just like the policer detection code
3944 				 * if we are in startup we must push
3945 				 * forward the last startup epoch
3946 				 * to hide the truncated PE.
3947 				 */
3948 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
3949 			}
3950 			bbr->r_ctl.rc_cwnd_on_ent = tp->snd_cwnd;
3951 			ENTER_RECOVERY(tp->t_flags);
3952 			bbr->rc_tlp_rtx_out = 0;
3953 			bbr->r_ctl.recovery_lr = bbr->r_ctl.rc_pkt_epoch_loss_rate;
3954 			tcp_bbr_tso_size_check(bbr, bbr->r_ctl.rc_rcvtime);
3955 			if (tcp_in_hpts(bbr->rc_tp) &&
3956 			    ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK) == 0)) {
3957 				/*
3958 				 * When we enter recovery, we need to restart
3959 				 * any timers. This may mean we gain an agg
3960 				 * early, which will be made up for at the last
3961 				 * rxt out.
3962 				 */
3963 				bbr->rc_timer_first = 1;
3964 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
3965 			}
3966 			/*
3967 			 * Calculate a new cwnd based on to the current
3968 			 * delivery rate with no gain. We get the bdp
3969 			 * without gaining it up like we normally would and
3970 			 * we use the last cur_del_rate.
3971 			 */
3972 			if ((bbr->rc_use_google == 0) &&
3973 			    (bbr->r_ctl.bbr_rttprobe_gain_val ||
3974 			     (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT))) {
3975 				tp->snd_cwnd = ctf_flight_size(tp,
3976 					           (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
3977 					(tp->t_maxseg - bbr->rc_last_options);
3978 				if (tp->snd_cwnd < get_min_cwnd(bbr)) {
3979 					/* We always gate to min cwnd */
3980 					tp->snd_cwnd = get_min_cwnd(bbr);
3981 				}
3982 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 14, 0, 0, __LINE__);
3983 			}
3984 			bbr_log_type_enter_rec(bbr, rsm->r_start);
3985 		}
3986 		break;
3987 	case CC_RTO_ERR:
3988 		KMOD_TCPSTAT_INC(tcps_sndrexmitbad);
3989 		/* RTO was unnecessary, so reset everything. */
3990 		bbr_reset_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime);
3991 		if (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) {
3992 			tp->snd_cwnd = tp->snd_cwnd_prev;
3993 			tp->snd_ssthresh = tp->snd_ssthresh_prev;
3994 			tp->snd_recover = tp->snd_recover_prev;
3995 			tp->snd_cwnd = max(tp->snd_cwnd, bbr->r_ctl.rc_cwnd_on_ent);
3996 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 13, 0, 0, __LINE__);
3997 		}
3998 		tp->t_badrxtwin = 0;
3999 		break;
4000 	}
4001 }
4002 
4003 /*
4004  * Indicate whether this ack should be delayed.  We can delay the ack if
4005  * following conditions are met:
4006  *	- There is no delayed ack timer in progress.
4007  *	- Our last ack wasn't a 0-sized window. We never want to delay
4008  *	  the ack that opens up a 0-sized window.
4009  *	- LRO wasn't used for this segment. We make sure by checking that the
4010  *	  segment size is not larger than the MSS.
4011  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
4012  *	  connection.
4013  *	- The data being acked is less than a full segment (a stretch ack
4014  *        of more than a segment we should ack.
4015  *      - nsegs is 1 (if its more than that we received more than 1 ack).
4016  */
4017 #define DELAY_ACK(tp, bbr, nsegs)				\
4018 	(((tp->t_flags & TF_RXWIN0SENT) == 0) &&		\
4019 	 ((tp->t_flags & TF_DELACK) == 0) && 		 	\
4020 	 ((bbr->bbr_segs_rcvd + nsegs) < tp->t_delayed_ack) &&	\
4021 	 (tp->t_delayed_ack || (tp->t_flags & TF_NEEDSYN)))
4022 
4023 /*
4024  * Return the lowest RSM in the map of
4025  * packets still in flight that is not acked.
4026  * This should normally find on the first one
4027  * since we remove packets from the send
4028  * map after they are marked ACKED.
4029  */
4030 static struct bbr_sendmap *
4031 bbr_find_lowest_rsm(struct tcp_bbr *bbr)
4032 {
4033 	struct bbr_sendmap *rsm;
4034 
4035 	/*
4036 	 * Walk the time-order transmitted list looking for an rsm that is
4037 	 * not acked. This will be the one that was sent the longest time
4038 	 * ago that is still outstanding.
4039 	 */
4040 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_tmap, r_tnext) {
4041 		if (rsm->r_flags & BBR_ACKED) {
4042 			continue;
4043 		}
4044 		goto finish;
4045 	}
4046 finish:
4047 	return (rsm);
4048 }
4049 
4050 static struct bbr_sendmap *
4051 bbr_find_high_nonack(struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
4052 {
4053 	struct bbr_sendmap *prsm;
4054 
4055 	/*
4056 	 * Walk the sequence order list backward until we hit and arrive at
4057 	 * the highest seq not acked. In theory when this is called it
4058 	 * should be the last segment (which it was not).
4059 	 */
4060 	prsm = rsm;
4061 	TAILQ_FOREACH_REVERSE_FROM(prsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4062 		if (prsm->r_flags & (BBR_ACKED | BBR_HAS_FIN)) {
4063 			continue;
4064 		}
4065 		return (prsm);
4066 	}
4067 	return (NULL);
4068 }
4069 
4070 /*
4071  * Returns to the caller the number of microseconds that
4072  * the packet can be outstanding before we think we
4073  * should have had an ack returned.
4074  */
4075 static uint32_t
4076 bbr_calc_thresh_rack(struct tcp_bbr *bbr, uint32_t srtt, uint32_t cts, struct bbr_sendmap *rsm)
4077 {
4078 	/*
4079 	 * lro is the flag we use to determine if we have seen reordering.
4080 	 * If it gets set we have seen reordering. The reorder logic either
4081 	 * works in one of two ways:
4082 	 *
4083 	 * If reorder-fade is configured, then we track the last time we saw
4084 	 * re-ordering occur. If we reach the point where enough time as
4085 	 * passed we no longer consider reordering has occuring.
4086 	 *
4087 	 * Or if reorder-face is 0, then once we see reordering we consider
4088 	 * the connection to alway be subject to reordering and just set lro
4089 	 * to 1.
4090 	 *
4091 	 * In the end if lro is non-zero we add the extra time for
4092 	 * reordering in.
4093 	 */
4094 	int32_t lro;
4095 	uint32_t thresh, t_rxtcur;
4096 
4097 	if (srtt == 0)
4098 		srtt = 1;
4099 	if (bbr->r_ctl.rc_reorder_ts) {
4100 		if (bbr->r_ctl.rc_reorder_fade) {
4101 			if (SEQ_GEQ(cts, bbr->r_ctl.rc_reorder_ts)) {
4102 				lro = cts - bbr->r_ctl.rc_reorder_ts;
4103 				if (lro == 0) {
4104 					/*
4105 					 * No time as passed since the last
4106 					 * reorder, mark it as reordering.
4107 					 */
4108 					lro = 1;
4109 				}
4110 			} else {
4111 				/* Negative time? */
4112 				lro = 0;
4113 			}
4114 			if (lro > bbr->r_ctl.rc_reorder_fade) {
4115 				/* Turn off reordering seen too */
4116 				bbr->r_ctl.rc_reorder_ts = 0;
4117 				lro = 0;
4118 			}
4119 		} else {
4120 			/* Reodering does not fade */
4121 			lro = 1;
4122 		}
4123 	} else {
4124 		lro = 0;
4125 	}
4126 	thresh = srtt + bbr->r_ctl.rc_pkt_delay;
4127 	if (lro) {
4128 		/* It must be set, if not you get 1/4 rtt */
4129 		if (bbr->r_ctl.rc_reorder_shift)
4130 			thresh += (srtt >> bbr->r_ctl.rc_reorder_shift);
4131 		else
4132 			thresh += (srtt >> 2);
4133 	} else {
4134 		thresh += 1000;
4135 	}
4136 	/* We don't let the rack timeout be above a RTO */
4137 	if ((bbr->rc_tp)->t_srtt == 0)
4138 		t_rxtcur = BBR_INITIAL_RTO;
4139 	else
4140 		t_rxtcur = TICKS_2_USEC(bbr->rc_tp->t_rxtcur);
4141 	if (thresh > t_rxtcur) {
4142 		thresh = t_rxtcur;
4143 	}
4144 	/* And we don't want it above the RTO max either */
4145 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4146 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4147 	}
4148 	bbr_log_thresh_choice(bbr, cts, thresh, lro, srtt, rsm, BBR_TO_FRM_RACK);
4149 	return (thresh);
4150 }
4151 
4152 /*
4153  * Return to the caller the amount of time in mico-seconds
4154  * that should be used for the TLP timer from the last
4155  * send time of this packet.
4156  */
4157 static uint32_t
4158 bbr_calc_thresh_tlp(struct tcpcb *tp, struct tcp_bbr *bbr,
4159     struct bbr_sendmap *rsm, uint32_t srtt,
4160     uint32_t cts)
4161 {
4162 	uint32_t thresh, len, maxseg, t_rxtcur;
4163 	struct bbr_sendmap *prsm;
4164 
4165 	if (srtt == 0)
4166 		srtt = 1;
4167 	if (bbr->rc_tlp_threshold)
4168 		thresh = srtt + (srtt / bbr->rc_tlp_threshold);
4169 	else
4170 		thresh = (srtt * 2);
4171 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4172 	/* Get the previous sent packet, if any  */
4173 	len = rsm->r_end - rsm->r_start;
4174 
4175 	/* 2.1 behavior */
4176 	prsm = TAILQ_PREV(rsm, bbr_head, r_tnext);
4177 	if (prsm && (len <= maxseg)) {
4178 		/*
4179 		 * Two packets outstanding, thresh should be (2*srtt) +
4180 		 * possible inter-packet delay (if any).
4181 		 */
4182 		uint32_t inter_gap = 0;
4183 		int idx, nidx;
4184 
4185 		idx = rsm->r_rtr_cnt - 1;
4186 		nidx = prsm->r_rtr_cnt - 1;
4187 		if (TSTMP_GEQ(rsm->r_tim_lastsent[nidx], prsm->r_tim_lastsent[idx])) {
4188 			/* Yes it was sent later (or at the same time) */
4189 			inter_gap = rsm->r_tim_lastsent[idx] - prsm->r_tim_lastsent[nidx];
4190 		}
4191 		thresh += inter_gap;
4192 	} else if (len <= maxseg) {
4193 		/*
4194 		 * Possibly compensate for delayed-ack.
4195 		 */
4196 		uint32_t alt_thresh;
4197 
4198 		alt_thresh = srtt + (srtt / 2) + bbr_delayed_ack_time;
4199 		if (alt_thresh > thresh)
4200 			thresh = alt_thresh;
4201 	}
4202 	/* Not above the current  RTO */
4203 	if (tp->t_srtt == 0)
4204 		t_rxtcur = BBR_INITIAL_RTO;
4205 	else
4206 		t_rxtcur = TICKS_2_USEC(tp->t_rxtcur);
4207 
4208 	bbr_log_thresh_choice(bbr, cts, thresh, t_rxtcur, srtt, rsm, BBR_TO_FRM_TLP);
4209 	/* Not above an RTO */
4210 	if (thresh > t_rxtcur) {
4211 		thresh = t_rxtcur;
4212 	}
4213 	/* Not above a RTO max */
4214 	if (thresh > (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND)) {
4215 		thresh = (((uint32_t)bbr->rc_max_rto_sec) * USECS_IN_SECOND);
4216 	}
4217 	/* And now apply the user TLP min */
4218 	if (thresh < bbr_tlp_min) {
4219 		thresh = bbr_tlp_min;
4220 	}
4221 	return (thresh);
4222 }
4223 
4224 /*
4225  * Return one of three RTTs to use (in microseconds).
4226  */
4227 static __inline uint32_t
4228 bbr_get_rtt(struct tcp_bbr *bbr, int32_t rtt_type)
4229 {
4230 	uint32_t f_rtt;
4231 	uint32_t srtt;
4232 
4233 	f_rtt = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
4234 	if (get_filter_value_small(&bbr->r_ctl.rc_rttprop) == 0xffffffff) {
4235 		/* We have no rtt at all */
4236 		if (bbr->rc_tp->t_srtt == 0)
4237 			f_rtt = BBR_INITIAL_RTO;
4238 		else
4239 			f_rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4240 		/*
4241 		 * Since we don't know how good the rtt is apply a
4242 		 * delayed-ack min
4243 		 */
4244 		if (f_rtt < bbr_delayed_ack_time) {
4245 			f_rtt = bbr_delayed_ack_time;
4246 		}
4247 	}
4248 	/* Take the filter version or last measured pkt-rtt */
4249 	if (rtt_type == BBR_RTT_PROP) {
4250 		srtt = f_rtt;
4251 	} else if (rtt_type == BBR_RTT_PKTRTT) {
4252 		if (bbr->r_ctl.rc_pkt_epoch_rtt) {
4253 			srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
4254 		} else {
4255 			/* No pkt rtt yet */
4256 			srtt = f_rtt;
4257 		}
4258 	} else if (rtt_type == BBR_RTT_RACK) {
4259 		srtt = bbr->r_ctl.rc_last_rtt;
4260 		/* We need to add in any internal delay for our timer */
4261 		if (bbr->rc_ack_was_delayed)
4262 			srtt += bbr->r_ctl.rc_ack_hdwr_delay;
4263 	} else if (rtt_type == BBR_SRTT) {
4264 		srtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
4265 	} else {
4266 		/* TSNH */
4267 		srtt = f_rtt;
4268 #ifdef BBR_INVARIANTS
4269 		panic("Unknown rtt request type %d", rtt_type);
4270 #endif
4271 	}
4272 	return (srtt);
4273 }
4274 
4275 static int
4276 bbr_is_lost(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t cts)
4277 {
4278 	uint32_t thresh;
4279 
4280 	thresh = bbr_calc_thresh_rack(bbr, bbr_get_rtt(bbr, BBR_RTT_RACK),
4281 				      cts, rsm);
4282 	if ((cts - rsm->r_tim_lastsent[(rsm->r_rtr_cnt - 1)]) >= thresh) {
4283 		/* It is lost (past time) */
4284 		return (1);
4285 	}
4286 	return (0);
4287 }
4288 
4289 /*
4290  * Return a sendmap if we need to retransmit something.
4291  */
4292 static struct bbr_sendmap *
4293 bbr_check_recovery_mode(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4294 {
4295 	/*
4296 	 * Check to see that we don't need to fall into recovery. We will
4297 	 * need to do so if our oldest transmit is past the time we should
4298 	 * have had an ack.
4299 	 */
4300 
4301 	struct bbr_sendmap *rsm;
4302 	int32_t idx;
4303 
4304 	if (TAILQ_EMPTY(&bbr->r_ctl.rc_map)) {
4305 		/* Nothing outstanding that we know of */
4306 		return (NULL);
4307 	}
4308 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
4309 	if (rsm == NULL) {
4310 		/* Nothing in the transmit map */
4311 		return (NULL);
4312 	}
4313 	if (tp->t_flags & TF_SENTFIN) {
4314 		/* Fin restricted, don't find anything once a fin is sent */
4315 		return (NULL);
4316 	}
4317 	if (rsm->r_flags & BBR_ACKED) {
4318 		/*
4319 		 * Ok the first one is acked (this really should not happen
4320 		 * since we remove the from the tmap once they are acked)
4321 		 */
4322 		rsm = bbr_find_lowest_rsm(bbr);
4323 		if (rsm == NULL)
4324 			return (NULL);
4325 	}
4326 	idx = rsm->r_rtr_cnt - 1;
4327 	if (SEQ_LEQ(cts, rsm->r_tim_lastsent[idx])) {
4328 		/* Send timestamp is the same or less? can't be ready */
4329 		return (NULL);
4330 	}
4331 	/* Get our RTT time */
4332 	if (bbr_is_lost(bbr, rsm, cts) &&
4333 	    ((rsm->r_dupack >= DUP_ACK_THRESHOLD) ||
4334 	     (rsm->r_flags & BBR_SACK_PASSED))) {
4335 		if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4336 			rsm->r_flags |= BBR_MARKED_LOST;
4337 			bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4338 			bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4339 		}
4340 		bbr_cong_signal(tp, NULL, CC_NDUPACK, rsm);
4341 #ifdef BBR_INVARIANTS
4342 		if ((rsm->r_end - rsm->r_start) == 0)
4343 			panic("tp:%p bbr:%p rsm:%p length is 0?", tp, bbr, rsm);
4344 #endif
4345 		return (rsm);
4346 	}
4347 	return (NULL);
4348 }
4349 
4350 /*
4351  * RACK Timer, here we simply do logging and house keeping.
4352  * the normal bbr_output_wtime() function will call the
4353  * appropriate thing to check if we need to do a RACK retransmit.
4354  * We return 1, saying don't proceed with bbr_output_wtime only
4355  * when all timers have been stopped (destroyed PCB?).
4356  */
4357 static int
4358 bbr_timeout_rack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4359 {
4360 	/*
4361 	 * This timer simply provides an internal trigger to send out data.
4362 	 * The check_recovery_mode call will see if there are needed
4363 	 * retransmissions, if so we will enter fast-recovery. The output
4364 	 * call may or may not do the same thing depending on sysctl
4365 	 * settings.
4366 	 */
4367 	uint32_t lost;
4368 
4369 	if (bbr->rc_all_timers_stopped) {
4370 		return (1);
4371 	}
4372 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4373 		/* Its not time yet */
4374 		return (0);
4375 	}
4376 	BBR_STAT_INC(bbr_to_tot);
4377 	lost = bbr->r_ctl.rc_lost;
4378 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4379 		bbr_set_state(tp, bbr, 0);
4380 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_RACK);
4381 	if (bbr->r_ctl.rc_resend == NULL) {
4382 		/* Lets do the check here */
4383 		bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
4384 	}
4385 	if (bbr_policer_call_from_rack_to)
4386 		bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4387 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RACK;
4388 	return (0);
4389 }
4390 
4391 static __inline void
4392 bbr_clone_rsm(struct tcp_bbr *bbr, struct bbr_sendmap *nrsm, struct bbr_sendmap *rsm, uint32_t start)
4393 {
4394 	int idx;
4395 
4396 	nrsm->r_start = start;
4397 	nrsm->r_end = rsm->r_end;
4398 	nrsm->r_rtr_cnt = rsm->r_rtr_cnt;
4399 	nrsm-> r_rtt_not_allowed = rsm->r_rtt_not_allowed;
4400 	nrsm->r_flags = rsm->r_flags;
4401 	/* We don't transfer forward the SYN flag */
4402 	nrsm->r_flags &= ~BBR_HAS_SYN;
4403 	/* We move forward the FIN flag, not that this should happen */
4404 	rsm->r_flags &= ~BBR_HAS_FIN;
4405 	nrsm->r_dupack = rsm->r_dupack;
4406 	nrsm->r_rtr_bytes = 0;
4407 	nrsm->r_is_gain = rsm->r_is_gain;
4408 	nrsm->r_is_drain = rsm->r_is_drain;
4409 	nrsm->r_delivered = rsm->r_delivered;
4410 	nrsm->r_ts_valid = rsm->r_ts_valid;
4411 	nrsm->r_del_ack_ts = rsm->r_del_ack_ts;
4412 	nrsm->r_del_time = rsm->r_del_time;
4413 	nrsm->r_app_limited = rsm->r_app_limited;
4414 	nrsm->r_first_sent_time = rsm->r_first_sent_time;
4415 	nrsm->r_flight_at_send = rsm->r_flight_at_send;
4416 	/* We split a piece the lower section looses any just_ret flag. */
4417 	nrsm->r_bbr_state = rsm->r_bbr_state;
4418 	for (idx = 0; idx < nrsm->r_rtr_cnt; idx++) {
4419 		nrsm->r_tim_lastsent[idx] = rsm->r_tim_lastsent[idx];
4420 	}
4421 	rsm->r_end = nrsm->r_start;
4422 	idx = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options), bbr->r_ctl.rc_pace_max_segs);
4423 	idx /= 8;
4424 	/* Check if we got too small */
4425 	if ((rsm->r_is_smallmap == 0) &&
4426 	    ((rsm->r_end - rsm->r_start) <= idx)) {
4427 		bbr->r_ctl.rc_num_small_maps_alloced++;
4428 		rsm->r_is_smallmap = 1;
4429 	}
4430 	/* Check the new one as well */
4431 	if ((nrsm->r_end - nrsm->r_start) <= idx) {
4432 		bbr->r_ctl.rc_num_small_maps_alloced++;
4433 		nrsm->r_is_smallmap = 1;
4434 	}
4435 }
4436 
4437 static int
4438 bbr_sack_mergable(struct bbr_sendmap *at,
4439 		  uint32_t start, uint32_t end)
4440 {
4441 	/*
4442 	 * Given a sack block defined by
4443 	 * start and end, and a current position
4444 	 * at. Return 1 if either side of at
4445 	 * would show that the block is mergable
4446 	 * to that side. A block to be mergable
4447 	 * must have overlap with the start/end
4448 	 * and be in the SACK'd state.
4449 	 */
4450 	struct bbr_sendmap *l_rsm;
4451 	struct bbr_sendmap *r_rsm;
4452 
4453 	/* first get the either side blocks */
4454 	l_rsm = TAILQ_PREV(at, bbr_head, r_next);
4455 	r_rsm = TAILQ_NEXT(at, r_next);
4456 	if (l_rsm && (l_rsm->r_flags & BBR_ACKED)) {
4457 		/* Potentially mergeable */
4458 		if ((l_rsm->r_end == start) ||
4459 		    (SEQ_LT(start, l_rsm->r_end) &&
4460 		     SEQ_GT(end, l_rsm->r_end))) {
4461 			    /*
4462 			     * map blk   |------|
4463 			     * sack blk         |------|
4464 			     * <or>
4465 			     * map blk   |------|
4466 			     * sack blk      |------|
4467 			     */
4468 			    return (1);
4469 		    }
4470 	}
4471 	if (r_rsm && (r_rsm->r_flags & BBR_ACKED)) {
4472 		/* Potentially mergeable */
4473 		if ((r_rsm->r_start == end) ||
4474 		    (SEQ_LT(start, r_rsm->r_start) &&
4475 		     SEQ_GT(end, r_rsm->r_start))) {
4476 			/*
4477 			 * map blk          |---------|
4478 			 * sack blk    |----|
4479 			 * <or>
4480 			 * map blk          |---------|
4481 			 * sack blk    |-------|
4482 			 */
4483 			return (1);
4484 		}
4485 	}
4486 	return (0);
4487 }
4488 
4489 static struct bbr_sendmap *
4490 bbr_merge_rsm(struct tcp_bbr *bbr,
4491 	      struct bbr_sendmap *l_rsm,
4492 	      struct bbr_sendmap *r_rsm)
4493 {
4494 	/*
4495 	 * We are merging two ack'd RSM's,
4496 	 * the l_rsm is on the left (lower seq
4497 	 * values) and the r_rsm is on the right
4498 	 * (higher seq value). The simplest way
4499 	 * to merge these is to move the right
4500 	 * one into the left. I don't think there
4501 	 * is any reason we need to try to find
4502 	 * the oldest (or last oldest retransmitted).
4503 	 */
4504 	l_rsm->r_end = r_rsm->r_end;
4505 	if (l_rsm->r_dupack < r_rsm->r_dupack)
4506 		l_rsm->r_dupack = r_rsm->r_dupack;
4507 	if (r_rsm->r_rtr_bytes)
4508 		l_rsm->r_rtr_bytes += r_rsm->r_rtr_bytes;
4509 	if (r_rsm->r_in_tmap) {
4510 		/* This really should not happen */
4511 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, r_rsm, r_tnext);
4512 	}
4513 	if (r_rsm->r_app_limited)
4514 		l_rsm->r_app_limited = r_rsm->r_app_limited;
4515 	/* Now the flags */
4516 	if (r_rsm->r_flags & BBR_HAS_FIN)
4517 		l_rsm->r_flags |= BBR_HAS_FIN;
4518 	if (r_rsm->r_flags & BBR_TLP)
4519 		l_rsm->r_flags |= BBR_TLP;
4520 	if (r_rsm->r_flags & BBR_RWND_COLLAPSED)
4521 		l_rsm->r_flags |= BBR_RWND_COLLAPSED;
4522 	if (r_rsm->r_flags & BBR_MARKED_LOST) {
4523 		/* This really should not happen */
4524 		bbr->r_ctl.rc_lost_bytes -= r_rsm->r_end - r_rsm->r_start;
4525 	}
4526 	TAILQ_REMOVE(&bbr->r_ctl.rc_map, r_rsm, r_next);
4527 	if ((r_rsm->r_limit_type == 0) && (l_rsm->r_limit_type != 0)) {
4528 		/* Transfer the split limit to the map we free */
4529 		r_rsm->r_limit_type = l_rsm->r_limit_type;
4530 		l_rsm->r_limit_type = 0;
4531 	}
4532 	bbr_free(bbr, r_rsm);
4533 	return(l_rsm);
4534 }
4535 
4536 /*
4537  * TLP Timer, here we simply setup what segment we want to
4538  * have the TLP expire on, the normal bbr_output_wtime() will then
4539  * send it out.
4540  *
4541  * We return 1, saying don't proceed with bbr_output_wtime only
4542  * when all timers have been stopped (destroyed PCB?).
4543  */
4544 static int
4545 bbr_timeout_tlp(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4546 {
4547 	/*
4548 	 * Tail Loss Probe.
4549 	 */
4550 	struct bbr_sendmap *rsm = NULL;
4551 	struct socket *so;
4552 	uint32_t amm;
4553 	uint32_t out, avail;
4554 	uint32_t maxseg;
4555 	int collapsed_win = 0;
4556 
4557 	if (bbr->rc_all_timers_stopped) {
4558 		return (1);
4559 	}
4560 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
4561 		/* Its not time yet */
4562 		return (0);
4563 	}
4564 	if (ctf_progress_timeout_check(tp, true)) {
4565 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4566 		return (-ETIMEDOUT);	/* tcp_drop() */
4567 	}
4568 	/* Did we somehow get into persists? */
4569 	if (bbr->rc_in_persist) {
4570 		return (0);
4571 	}
4572 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4573 		bbr_set_state(tp, bbr, 0);
4574 	BBR_STAT_INC(bbr_tlp_tot);
4575 	maxseg = tp->t_maxseg - bbr->rc_last_options;
4576 	/*
4577 	 * A TLP timer has expired. We have been idle for 2 rtts. So we now
4578 	 * need to figure out how to force a full MSS segment out.
4579 	 */
4580 	so = tptosocket(tp);
4581 	avail = sbavail(&so->so_snd);
4582 	out = ctf_outstanding(tp);
4583 	if (out > tp->snd_wnd) {
4584 		/* special case, we need a retransmission */
4585 		collapsed_win = 1;
4586 		goto need_retran;
4587 	}
4588 	if (avail > out) {
4589 		/* New data is available */
4590 		amm = avail - out;
4591 		if (amm > maxseg) {
4592 			amm = maxseg;
4593 		} else if ((amm < maxseg) && ((tp->t_flags & TF_NODELAY) == 0)) {
4594 			/* not enough to fill a MTU and no-delay is off */
4595 			goto need_retran;
4596 		}
4597 		/* Set the send-new override */
4598 		if ((out + amm) <= tp->snd_wnd) {
4599 			bbr->rc_tlp_new_data = 1;
4600 		} else {
4601 			goto need_retran;
4602 		}
4603 		bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4604 		bbr->r_ctl.rc_last_tlp_seq = tp->snd_max;
4605 		bbr->r_ctl.rc_tlp_send = NULL;
4606 		/* cap any slots */
4607 		BBR_STAT_INC(bbr_tlp_newdata);
4608 		goto send;
4609 	}
4610 need_retran:
4611 	/*
4612 	 * Ok we need to arrange the last un-acked segment to be re-sent, or
4613 	 * optionally the first un-acked segment.
4614 	 */
4615 	if (collapsed_win == 0) {
4616 		rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
4617 		if (rsm && (BBR_ACKED | BBR_HAS_FIN)) {
4618 			rsm = bbr_find_high_nonack(bbr, rsm);
4619 		}
4620 		if (rsm == NULL) {
4621 			goto restore;
4622 		}
4623 	} else {
4624 		/*
4625 		 * We must find the last segment
4626 		 * that was acceptable by the client.
4627 		 */
4628 		TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
4629 			if ((rsm->r_flags & BBR_RWND_COLLAPSED) == 0) {
4630 				/* Found one */
4631 				break;
4632 			}
4633 		}
4634 		if (rsm == NULL) {
4635 			/* None? if so send the first */
4636 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4637 			if (rsm == NULL)
4638 				goto restore;
4639 		}
4640 	}
4641 	if ((rsm->r_end - rsm->r_start) > maxseg) {
4642 		/*
4643 		 * We need to split this the last segment in two.
4644 		 */
4645 		struct bbr_sendmap *nrsm;
4646 
4647 		nrsm = bbr_alloc_full_limit(bbr);
4648 		if (nrsm == NULL) {
4649 			/*
4650 			 * We can't get memory to split, we can either just
4651 			 * not split it. Or retransmit the whole piece, lets
4652 			 * do the large send (BTLP :-) ).
4653 			 */
4654 			goto go_for_it;
4655 		}
4656 		bbr_clone_rsm(bbr, nrsm, rsm, (rsm->r_end - maxseg));
4657 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
4658 		if (rsm->r_in_tmap) {
4659 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
4660 			nrsm->r_in_tmap = 1;
4661 		}
4662 		rsm->r_flags &= (~BBR_HAS_FIN);
4663 		rsm = nrsm;
4664 	}
4665 go_for_it:
4666 	bbr->r_ctl.rc_tlp_send = rsm;
4667 	bbr->rc_tlp_rtx_out = 1;
4668 	if (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) {
4669 		bbr->r_ctl.rc_tlp_seg_send_cnt++;
4670 		tp->t_rxtshift++;
4671 	} else {
4672 		bbr->r_ctl.rc_last_tlp_seq = rsm->r_start;
4673 		bbr->r_ctl.rc_tlp_seg_send_cnt = 1;
4674 	}
4675 send:
4676 	if (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend) {
4677 		/*
4678 		 * Can't [re]/transmit a segment we have retransmitted the
4679 		 * max times. We need the retransmit timer to take over.
4680 		 */
4681 restore:
4682 		bbr->rc_tlp_new_data = 0;
4683 		bbr->r_ctl.rc_tlp_send = NULL;
4684 		if (rsm)
4685 			rsm->r_flags &= ~BBR_TLP;
4686 		BBR_STAT_INC(bbr_tlp_retran_fail);
4687 		return (0);
4688 	} else if (rsm) {
4689 		rsm->r_flags |= BBR_TLP;
4690 	}
4691 	if (rsm && (rsm->r_start == bbr->r_ctl.rc_last_tlp_seq) &&
4692 	    (bbr->r_ctl.rc_tlp_seg_send_cnt > bbr_tlp_max_resend)) {
4693 		/*
4694 		 * We have retransmitted to many times for TLP. Switch to
4695 		 * the regular RTO timer
4696 		 */
4697 		goto restore;
4698 	}
4699 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TLP);
4700 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_TLP;
4701 	return (0);
4702 }
4703 
4704 /*
4705  * Delayed ack Timer, here we simply need to setup the
4706  * ACK_NOW flag and remove the DELACK flag. From there
4707  * the output routine will send the ack out.
4708  *
4709  * We only return 1, saying don't proceed, if all timers
4710  * are stopped (destroyed PCB?).
4711  */
4712 static int
4713 bbr_timeout_delack(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4714 {
4715 	if (bbr->rc_all_timers_stopped) {
4716 		return (1);
4717 	}
4718 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_DELACK);
4719 	tp->t_flags &= ~TF_DELACK;
4720 	tp->t_flags |= TF_ACKNOW;
4721 	KMOD_TCPSTAT_INC(tcps_delack);
4722 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_DELACK;
4723 	return (0);
4724 }
4725 
4726 /*
4727  * Here we send a KEEP-ALIVE like probe to the
4728  * peer, we do not send data.
4729  *
4730  * We only return 1, saying don't proceed, if all timers
4731  * are stopped (destroyed PCB?).
4732  */
4733 static int
4734 bbr_timeout_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4735 {
4736 	struct tcptemp *t_template;
4737 	int32_t retval = 1;
4738 
4739 	if (bbr->rc_all_timers_stopped) {
4740 		return (1);
4741 	}
4742 	if (bbr->rc_in_persist == 0)
4743 		return (0);
4744 
4745 	/*
4746 	 * Persistence timer into zero window. Force a byte to be output, if
4747 	 * possible.
4748 	 */
4749 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_PERSIST);
4750 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_PERSIT;
4751 	KMOD_TCPSTAT_INC(tcps_persisttimeo);
4752 	/*
4753 	 * Have we exceeded the user specified progress time?
4754 	 */
4755 	if (ctf_progress_timeout_check(tp, true)) {
4756 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4757 		return (-ETIMEDOUT);	/* tcp_drop() */
4758 	}
4759 	/*
4760 	 * Hack: if the peer is dead/unreachable, we do not time out if the
4761 	 * window is closed.  After a full backoff, drop the connection if
4762 	 * the idle time (no responses to probes) reaches the maximum
4763 	 * backoff that we would use if retransmitting.
4764 	 */
4765 	if (tp->t_rxtshift >= V_tcp_retries &&
4766 	    (ticks - tp->t_rcvtime >= tcp_maxpersistidle ||
4767 	    ticks - tp->t_rcvtime >= TCP_REXMTVAL(tp) * tcp_totbackoff)) {
4768 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4769 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4770 		return (-ETIMEDOUT);	/* tcp_drop() */
4771 	}
4772 	if ((sbavail(&bbr->rc_inp->inp_socket->so_snd) == 0) &&
4773 	    tp->snd_una == tp->snd_max) {
4774 		bbr_exit_persist(tp, bbr, cts, __LINE__);
4775 		retval = 0;
4776 		goto out;
4777 	}
4778 	/*
4779 	 * If the user has closed the socket then drop a persisting
4780 	 * connection after a much reduced timeout.
4781 	 */
4782 	if (tp->t_state > TCPS_CLOSE_WAIT &&
4783 	    (ticks - tp->t_rcvtime) >= TCPTV_PERSMAX) {
4784 		KMOD_TCPSTAT_INC(tcps_persistdrop);
4785 		tcp_log_end_status(tp, TCP_EI_STATUS_PERSIST_MAX);
4786 		return (-ETIMEDOUT);	/* tcp_drop() */
4787 	}
4788 	t_template = tcpip_maketemplate(bbr->rc_inp);
4789 	if (t_template) {
4790 		tcp_respond(tp, t_template->tt_ipgen,
4791 			    &t_template->tt_t, (struct mbuf *)NULL,
4792 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4793 		/* This sends an ack */
4794 		if (tp->t_flags & TF_DELACK)
4795 			tp->t_flags &= ~TF_DELACK;
4796 		free(t_template, M_TEMP);
4797 	}
4798 	if (tp->t_rxtshift < V_tcp_retries)
4799 		tp->t_rxtshift++;
4800 	bbr_start_hpts_timer(bbr, tp, cts, 3, 0, 0);
4801 out:
4802 	return (retval);
4803 }
4804 
4805 /*
4806  * If a keepalive goes off, we had no other timers
4807  * happening. We always return 1 here since this
4808  * routine either drops the connection or sends
4809  * out a segment with respond.
4810  */
4811 static int
4812 bbr_timeout_keepalive(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4813 {
4814 	struct tcptemp *t_template;
4815 	struct inpcb *inp = tptoinpcb(tp);
4816 
4817 	if (bbr->rc_all_timers_stopped) {
4818 		return (1);
4819 	}
4820 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_KEEP;
4821 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_KEEP);
4822 	/*
4823 	 * Keep-alive timer went off; send something or drop connection if
4824 	 * idle for too long.
4825 	 */
4826 	KMOD_TCPSTAT_INC(tcps_keeptimeo);
4827 	if (tp->t_state < TCPS_ESTABLISHED)
4828 		goto dropit;
4829 	if ((V_tcp_always_keepalive || inp->inp_socket->so_options & SO_KEEPALIVE) &&
4830 	    tp->t_state <= TCPS_CLOSING) {
4831 		if (ticks - tp->t_rcvtime >= TP_KEEPIDLE(tp) + TP_MAXIDLE(tp))
4832 			goto dropit;
4833 		/*
4834 		 * Send a packet designed to force a response if the peer is
4835 		 * up and reachable: either an ACK if the connection is
4836 		 * still alive, or an RST if the peer has closed the
4837 		 * connection due to timeout or reboot. Using sequence
4838 		 * number tp->snd_una-1 causes the transmitted zero-length
4839 		 * segment to lie outside the receive window; by the
4840 		 * protocol spec, this requires the correspondent TCP to
4841 		 * respond.
4842 		 */
4843 		KMOD_TCPSTAT_INC(tcps_keepprobe);
4844 		t_template = tcpip_maketemplate(inp);
4845 		if (t_template) {
4846 			tcp_respond(tp, t_template->tt_ipgen,
4847 			    &t_template->tt_t, (struct mbuf *)NULL,
4848 			    tp->rcv_nxt, tp->snd_una - 1, 0);
4849 			free(t_template, M_TEMP);
4850 		}
4851 	}
4852 	bbr_start_hpts_timer(bbr, tp, cts, 4, 0, 0);
4853 	return (1);
4854 dropit:
4855 	KMOD_TCPSTAT_INC(tcps_keepdrops);
4856 	tcp_log_end_status(tp, TCP_EI_STATUS_KEEP_MAX);
4857 	return (-ETIMEDOUT);	/* tcp_drop() */
4858 }
4859 
4860 /*
4861  * Retransmit helper function, clear up all the ack
4862  * flags and take care of important book keeping.
4863  */
4864 static void
4865 bbr_remxt_tmr(struct tcpcb *tp)
4866 {
4867 	/*
4868 	 * The retransmit timer went off, all sack'd blocks must be
4869 	 * un-acked.
4870 	 */
4871 	struct bbr_sendmap *rsm, *trsm = NULL;
4872 	struct tcp_bbr *bbr;
4873 	uint32_t cts, lost;
4874 
4875 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
4876 	cts = tcp_get_usecs(&bbr->rc_tv);
4877 	lost = bbr->r_ctl.rc_lost;
4878 	if (bbr->r_state && (bbr->r_state != tp->t_state))
4879 		bbr_set_state(tp, bbr, 0);
4880 
4881 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
4882 		if (rsm->r_flags & BBR_ACKED) {
4883 			uint32_t old_flags;
4884 
4885 			rsm->r_dupack = 0;
4886 			if (rsm->r_in_tmap == 0) {
4887 				/* We must re-add it back to the tlist */
4888 				if (trsm == NULL) {
4889 					TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
4890 				} else {
4891 					TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, trsm, rsm, r_tnext);
4892 				}
4893 				rsm->r_in_tmap = 1;
4894 			}
4895 			old_flags = rsm->r_flags;
4896 			rsm->r_flags |= BBR_RXT_CLEARED;
4897 			rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS);
4898 			bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
4899 		} else {
4900 			if ((tp->t_state < TCPS_ESTABLISHED) &&
4901 			    (rsm->r_start == tp->snd_una)) {
4902 				/*
4903 				 * Special case for TCP FO. Where
4904 				 * we sent more data beyond the snd_max.
4905 				 * We don't mark that as lost and stop here.
4906 				 */
4907 				break;
4908 			}
4909 			if ((rsm->r_flags & BBR_MARKED_LOST) == 0) {
4910 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
4911 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
4912 			}
4913 			if (bbr_marks_rxt_sack_passed) {
4914 				/*
4915 				 * With this option, we will rack out
4916 				 * in 1ms increments the rest of the packets.
4917 				 */
4918 				rsm->r_flags |= BBR_SACK_PASSED | BBR_MARKED_LOST;
4919 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4920 			} else {
4921 				/*
4922 				 * With this option we only mark them lost
4923 				 * and remove all sack'd markings. We will run
4924 				 * another RXT or a TLP. This will cause
4925 				 * us to eventually send more based on what
4926 				 * ack's come in.
4927 				 */
4928 				rsm->r_flags |= BBR_MARKED_LOST;
4929 				rsm->r_flags &= ~BBR_WAS_SACKPASS;
4930 				rsm->r_flags &= ~BBR_SACK_PASSED;
4931 			}
4932 		}
4933 		trsm = rsm;
4934 	}
4935 	bbr->r_ctl.rc_resend = TAILQ_FIRST(&bbr->r_ctl.rc_map);
4936 	/* Clear the count (we just un-acked them) */
4937 	bbr_log_to_event(bbr, cts, BBR_TO_FRM_TMR);
4938 	bbr->rc_tlp_new_data = 0;
4939 	bbr->r_ctl.rc_tlp_seg_send_cnt = 0;
4940 	/* zap the behindness on a rxt */
4941 	bbr->r_ctl.rc_hptsi_agg_delay = 0;
4942 	bbr->r_agg_early_set = 0;
4943 	bbr->r_ctl.rc_agg_early = 0;
4944 	bbr->rc_tlp_rtx_out = 0;
4945 	bbr->r_ctl.rc_sacked = 0;
4946 	bbr->r_ctl.rc_sacklast = NULL;
4947 	bbr->r_timer_override = 1;
4948 	bbr_lt_bw_sampling(bbr, cts, (bbr->r_ctl.rc_lost > lost));
4949 }
4950 
4951 /*
4952  * Re-transmit timeout! If we drop the PCB we will return 1, otherwise
4953  * we will setup to retransmit the lowest seq number outstanding.
4954  */
4955 static int
4956 bbr_timeout_rxt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
4957 {
4958 	struct inpcb *inp = tptoinpcb(tp);
4959 	int32_t rexmt;
4960 	int32_t retval = 0;
4961 	bool isipv6;
4962 
4963 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_RXT;
4964 	if (bbr->rc_all_timers_stopped) {
4965 		return (1);
4966 	}
4967 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
4968 	    (tp->snd_una == tp->snd_max)) {
4969 		/* Nothing outstanding .. nothing to do */
4970 		return (0);
4971 	}
4972 	/*
4973 	 * Retransmission timer went off.  Message has not been acked within
4974 	 * retransmit interval.  Back off to a longer retransmit interval
4975 	 * and retransmit one segment.
4976 	 */
4977 	if (ctf_progress_timeout_check(tp, true)) {
4978 		bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
4979 		return (-ETIMEDOUT);	/* tcp_drop() */
4980 	}
4981 	bbr_remxt_tmr(tp);
4982 	if ((bbr->r_ctl.rc_resend == NULL) ||
4983 	    ((bbr->r_ctl.rc_resend->r_flags & BBR_RWND_COLLAPSED) == 0)) {
4984 		/*
4985 		 * If the rwnd collapsed on
4986 		 * the one we are retransmitting
4987 		 * it does not count against the
4988 		 * rxt count.
4989 		 */
4990 		tp->t_rxtshift++;
4991 	}
4992 	if (tp->t_rxtshift > V_tcp_retries) {
4993 		tp->t_rxtshift = V_tcp_retries;
4994 		KMOD_TCPSTAT_INC(tcps_timeoutdrop);
4995 		tcp_log_end_status(tp, TCP_EI_STATUS_RETRAN);
4996 		/* XXXGL: previously t_softerror was casted to uint16_t */
4997 		MPASS(tp->t_softerror >= 0);
4998 		retval = tp->t_softerror ? -tp->t_softerror : -ETIMEDOUT;
4999 		return (retval);	/* tcp_drop() */
5000 	}
5001 	if (tp->t_state == TCPS_SYN_SENT) {
5002 		/*
5003 		 * If the SYN was retransmitted, indicate CWND to be limited
5004 		 * to 1 segment in cc_conn_init().
5005 		 */
5006 		tp->snd_cwnd = 1;
5007 	} else if (tp->t_rxtshift == 1) {
5008 		/*
5009 		 * first retransmit; record ssthresh and cwnd so they can be
5010 		 * recovered if this turns out to be a "bad" retransmit. A
5011 		 * retransmit is considered "bad" if an ACK for this segment
5012 		 * is received within RTT/2 interval; the assumption here is
5013 		 * that the ACK was already in flight.  See "On Estimating
5014 		 * End-to-End Network Path Properties" by Allman and Paxson
5015 		 * for more details.
5016 		 */
5017 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5018 		if (!IN_RECOVERY(tp->t_flags)) {
5019 			tp->snd_cwnd_prev = tp->snd_cwnd;
5020 			tp->snd_ssthresh_prev = tp->snd_ssthresh;
5021 			tp->snd_recover_prev = tp->snd_recover;
5022 			tp->t_badrxtwin = ticks + (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
5023 			tp->t_flags |= TF_PREVVALID;
5024 		} else {
5025 			tp->t_flags &= ~TF_PREVVALID;
5026 		}
5027 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5028 	} else {
5029 		tp->snd_cwnd = tp->t_maxseg - bbr->rc_last_options;
5030 		tp->t_flags &= ~TF_PREVVALID;
5031 	}
5032 	KMOD_TCPSTAT_INC(tcps_rexmttimeo);
5033 	if ((tp->t_state == TCPS_SYN_SENT) ||
5034 	    (tp->t_state == TCPS_SYN_RECEIVED))
5035 		rexmt = USEC_2_TICKS(BBR_INITIAL_RTO) * tcp_backoff[tp->t_rxtshift];
5036 	else
5037 		rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
5038 	TCPT_RANGESET(tp->t_rxtcur, rexmt,
5039 	    MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms),
5040 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
5041 	/*
5042 	 * We enter the path for PLMTUD if connection is established or, if
5043 	 * connection is FIN_WAIT_1 status, reason for the last is that if
5044 	 * amount of data we send is very small, we could send it in couple
5045 	 * of packets and process straight to FIN. In that case we won't
5046 	 * catch ESTABLISHED state.
5047 	 */
5048 #ifdef INET6
5049 	isipv6 = (inp->inp_vflag & INP_IPV6) ? true : false;
5050 #else
5051 	isipv6 = false;
5052 #endif
5053 	if (((V_tcp_pmtud_blackhole_detect == 1) ||
5054 	    (V_tcp_pmtud_blackhole_detect == 2 && !isipv6) ||
5055 	    (V_tcp_pmtud_blackhole_detect == 3 && isipv6)) &&
5056 	    ((tp->t_state == TCPS_ESTABLISHED) ||
5057 	    (tp->t_state == TCPS_FIN_WAIT_1))) {
5058 		/*
5059 		 * Idea here is that at each stage of mtu probe (usually,
5060 		 * 1448 -> 1188 -> 524) should be given 2 chances to recover
5061 		 * before further clamping down. 'tp->t_rxtshift % 2 == 0'
5062 		 * should take care of that.
5063 		 */
5064 		if (((tp->t_flags2 & (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) ==
5065 		    (TF2_PLPMTU_PMTUD | TF2_PLPMTU_MAXSEGSNT)) &&
5066 		    (tp->t_rxtshift >= 2 && tp->t_rxtshift < 6 &&
5067 		    tp->t_rxtshift % 2 == 0)) {
5068 			/*
5069 			 * Enter Path MTU Black-hole Detection mechanism: -
5070 			 * Disable Path MTU Discovery (IP "DF" bit). -
5071 			 * Reduce MTU to lower value than what we negotiated
5072 			 * with peer.
5073 			 */
5074 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) == 0) {
5075 				/*
5076 				 * Record that we may have found a black
5077 				 * hole.
5078 				 */
5079 				tp->t_flags2 |= TF2_PLPMTU_BLACKHOLE;
5080 				/* Keep track of previous MSS. */
5081 				tp->t_pmtud_saved_maxseg = tp->t_maxseg;
5082 			}
5083 			/*
5084 			 * Reduce the MSS to blackhole value or to the
5085 			 * default in an attempt to retransmit.
5086 			 */
5087 #ifdef INET6
5088 			isipv6 = bbr->r_is_v6;
5089 			if (isipv6 &&
5090 			    tp->t_maxseg > V_tcp_v6pmtud_blackhole_mss) {
5091 				/* Use the sysctl tuneable blackhole MSS. */
5092 				tp->t_maxseg = V_tcp_v6pmtud_blackhole_mss;
5093 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5094 			} else if (isipv6) {
5095 				/* Use the default MSS. */
5096 				tp->t_maxseg = V_tcp_v6mssdflt;
5097 				/*
5098 				 * Disable Path MTU Discovery when we switch
5099 				 * to minmss.
5100 				 */
5101 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5102 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5103 			}
5104 #endif
5105 #if defined(INET6) && defined(INET)
5106 			else
5107 #endif
5108 #ifdef INET
5109 			if (tp->t_maxseg > V_tcp_pmtud_blackhole_mss) {
5110 				/* Use the sysctl tuneable blackhole MSS. */
5111 				tp->t_maxseg = V_tcp_pmtud_blackhole_mss;
5112 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated);
5113 			} else {
5114 				/* Use the default MSS. */
5115 				tp->t_maxseg = V_tcp_mssdflt;
5116 				/*
5117 				 * Disable Path MTU Discovery when we switch
5118 				 * to minmss.
5119 				 */
5120 				tp->t_flags2 &= ~TF2_PLPMTU_PMTUD;
5121 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_activated_min_mss);
5122 			}
5123 #endif
5124 		} else {
5125 			/*
5126 			 * If further retransmissions are still unsuccessful
5127 			 * with a lowered MTU, maybe this isn't a blackhole
5128 			 * and we restore the previous MSS and blackhole
5129 			 * detection flags. The limit '6' is determined by
5130 			 * giving each probe stage (1448, 1188, 524) 2
5131 			 * chances to recover.
5132 			 */
5133 			if ((tp->t_flags2 & TF2_PLPMTU_BLACKHOLE) &&
5134 			    (tp->t_rxtshift >= 6)) {
5135 				tp->t_flags2 |= TF2_PLPMTU_PMTUD;
5136 				tp->t_flags2 &= ~TF2_PLPMTU_BLACKHOLE;
5137 				tp->t_maxseg = tp->t_pmtud_saved_maxseg;
5138 				if (tp->t_maxseg < V_tcp_mssdflt) {
5139 					/*
5140 					 * The MSS is so small we should not
5141 					 * process incoming SACK's since we are
5142 					 * subject to attack in such a case.
5143 					 */
5144 					tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
5145 				} else {
5146 					tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
5147 				}
5148 				KMOD_TCPSTAT_INC(tcps_pmtud_blackhole_failed);
5149 			}
5150 		}
5151 	}
5152 	/*
5153 	 * Disable RFC1323 and SACK if we haven't got any response to our
5154 	 * third SYN to work-around some broken terminal servers (most of
5155 	 * which have hopefully been retired) that have bad VJ header
5156 	 * compression code which trashes TCP segments containing
5157 	 * unknown-to-them TCP options.
5158 	 */
5159 	if (tcp_rexmit_drop_options && (tp->t_state == TCPS_SYN_SENT) &&
5160 	    (tp->t_rxtshift == 3))
5161 		tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP | TF_SACK_PERMIT);
5162 	/*
5163 	 * If we backed off this far, our srtt estimate is probably bogus.
5164 	 * Clobber it so we'll take the next rtt measurement as our srtt;
5165 	 * move the current srtt into rttvar to keep the current retransmit
5166 	 * times until then.
5167 	 */
5168 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
5169 #ifdef INET6
5170 		if (bbr->r_is_v6)
5171 			in6_losing(inp);
5172 		else
5173 #endif
5174 			in_losing(inp);
5175 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
5176 		tp->t_srtt = 0;
5177 	}
5178 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
5179 	tp->snd_recover = tp->snd_max;
5180 	tp->t_flags |= TF_ACKNOW;
5181 	tp->t_rtttime = 0;
5182 
5183 	return (retval);
5184 }
5185 
5186 static int
5187 bbr_process_timers(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, uint8_t hpts_calling)
5188 {
5189 	int32_t ret = 0;
5190 	int32_t timers = (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK);
5191 
5192 	if (timers == 0) {
5193 		return (0);
5194 	}
5195 	if (tp->t_state == TCPS_LISTEN) {
5196 		/* no timers on listen sockets */
5197 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT)
5198 			return (0);
5199 		return (1);
5200 	}
5201 	if (TSTMP_LT(cts, bbr->r_ctl.rc_timer_exp)) {
5202 		uint32_t left;
5203 
5204 		if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
5205 			ret = -1;
5206 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5207 			return (0);
5208 		}
5209 		if (hpts_calling == 0) {
5210 			ret = -2;
5211 			bbr_log_to_processing(bbr, cts, ret, 0, hpts_calling);
5212 			return (0);
5213 		}
5214 		/*
5215 		 * Ok our timer went off early and we are not paced false
5216 		 * alarm, go back to sleep.
5217 		 */
5218 		left = bbr->r_ctl.rc_timer_exp - cts;
5219 		ret = -3;
5220 		bbr_log_to_processing(bbr, cts, ret, left, hpts_calling);
5221 		tcp_hpts_insert(tp, HPTS_USEC_TO_SLOTS(left));
5222 		return (1);
5223 	}
5224 	bbr->rc_tmr_stopped = 0;
5225 	bbr->r_ctl.rc_hpts_flags &= ~PACE_TMR_MASK;
5226 	if (timers & PACE_TMR_DELACK) {
5227 		ret = bbr_timeout_delack(tp, bbr, cts);
5228 	} else if (timers & PACE_TMR_PERSIT) {
5229 		ret = bbr_timeout_persist(tp, bbr, cts);
5230 	} else if (timers & PACE_TMR_RACK) {
5231 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5232 		ret = bbr_timeout_rack(tp, bbr, cts);
5233 	} else if (timers & PACE_TMR_TLP) {
5234 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5235 		ret = bbr_timeout_tlp(tp, bbr, cts);
5236 	} else if (timers & PACE_TMR_RXT) {
5237 		bbr->r_ctl.rc_tlp_rxt_last_time = cts;
5238 		ret = bbr_timeout_rxt(tp, bbr, cts);
5239 	} else if (timers & PACE_TMR_KEEP) {
5240 		ret = bbr_timeout_keepalive(tp, bbr, cts);
5241 	}
5242 	bbr_log_to_processing(bbr, cts, ret, timers, hpts_calling);
5243 	return (ret);
5244 }
5245 
5246 static void
5247 bbr_timer_cancel(struct tcp_bbr *bbr, int32_t line, uint32_t cts)
5248 {
5249 	if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
5250 		uint8_t hpts_removed = 0;
5251 
5252 		if (tcp_in_hpts(bbr->rc_tp) &&
5253 		    (bbr->rc_timer_first == 1)) {
5254 			/*
5255 			 * If we are canceling timer's when we have the
5256 			 * timer ahead of the output being paced. We also
5257 			 * must remove ourselves from the hpts.
5258 			 */
5259 			hpts_removed = 1;
5260 			tcp_hpts_remove(bbr->rc_tp);
5261 			if (bbr->r_ctl.rc_last_delay_val) {
5262 				/* Update the last hptsi delay too */
5263 				uint32_t time_since_send;
5264 
5265 				if (TSTMP_GT(cts, bbr->rc_pacer_started))
5266 					time_since_send = cts - bbr->rc_pacer_started;
5267 				else
5268 					time_since_send = 0;
5269 				if (bbr->r_ctl.rc_last_delay_val > time_since_send) {
5270 					/* Cut down our slot time */
5271 					bbr->r_ctl.rc_last_delay_val -= time_since_send;
5272 				} else {
5273 					bbr->r_ctl.rc_last_delay_val = 0;
5274 				}
5275 				bbr->rc_pacer_started = cts;
5276 			}
5277 		}
5278 		bbr->rc_timer_first = 0;
5279 		bbr_log_to_cancel(bbr, line, cts, hpts_removed);
5280 		bbr->rc_tmr_stopped = bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK;
5281 		bbr->r_ctl.rc_hpts_flags &= ~(PACE_TMR_MASK);
5282 	}
5283 }
5284 
5285 static int
5286 bbr_stopall(struct tcpcb *tp)
5287 {
5288 	struct tcp_bbr *bbr;
5289 
5290 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
5291 	bbr->rc_all_timers_stopped = 1;
5292 
5293 	tcp_hpts_remove(tp);
5294 
5295 	return (0);
5296 }
5297 
5298 static uint32_t
5299 bbr_get_earliest_send_outstanding(struct tcp_bbr *bbr, struct bbr_sendmap *u_rsm, uint32_t cts)
5300 {
5301 	struct bbr_sendmap *rsm;
5302 
5303 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
5304 	if ((rsm == NULL) || (u_rsm == rsm))
5305 		return (cts);
5306 	return(rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)]);
5307 }
5308 
5309 static void
5310 bbr_update_rsm(struct tcpcb *tp, struct tcp_bbr *bbr,
5311      struct bbr_sendmap *rsm, uint32_t cts, uint32_t pacing_time)
5312 {
5313 	int32_t idx;
5314 
5315 	rsm->r_rtr_cnt++;
5316 	rsm->r_dupack = 0;
5317 	if (rsm->r_rtr_cnt > BBR_NUM_OF_RETRANS) {
5318 		rsm->r_rtr_cnt = BBR_NUM_OF_RETRANS;
5319 		rsm->r_flags |= BBR_OVERMAX;
5320 	}
5321 	if (rsm->r_flags & BBR_RWND_COLLAPSED) {
5322 		/* Take off the collapsed flag at rxt */
5323 		rsm->r_flags &= ~BBR_RWND_COLLAPSED;
5324 	}
5325 	if (rsm->r_flags & BBR_MARKED_LOST) {
5326 		/* We have retransmitted, its no longer lost */
5327 		rsm->r_flags &= ~BBR_MARKED_LOST;
5328 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
5329 	}
5330 	if (rsm->r_flags & BBR_RXT_CLEARED) {
5331 		/*
5332 		 * We hit a RXT timer on it and
5333 		 * we cleared the "acked" flag.
5334 		 * We now have it going back into
5335 		 * flight, we can remove the cleared
5336 		 * flag and possibly do accounting on
5337 		 * this piece.
5338 		 */
5339 		rsm->r_flags &= ~BBR_RXT_CLEARED;
5340 	}
5341 	if ((rsm->r_rtr_cnt > 1) && ((rsm->r_flags & BBR_TLP) == 0)) {
5342 		bbr->r_ctl.rc_holes_rxt += (rsm->r_end - rsm->r_start);
5343 		rsm->r_rtr_bytes += (rsm->r_end - rsm->r_start);
5344 	}
5345 	idx = rsm->r_rtr_cnt - 1;
5346 	rsm->r_tim_lastsent[idx] = cts;
5347 	rsm->r_pacing_delay = pacing_time;
5348 	rsm->r_delivered = bbr->r_ctl.rc_delivered;
5349 	rsm->r_ts_valid = bbr->rc_ts_valid;
5350 	if (bbr->rc_ts_valid)
5351 		rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5352 	if (bbr->r_ctl.r_app_limited_until)
5353 		rsm->r_app_limited = 1;
5354 	else
5355 		rsm->r_app_limited = 0;
5356 	if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5357 		rsm->r_bbr_state = bbr_state_val(bbr);
5358 	else
5359 		rsm->r_bbr_state = 8;
5360 	if (rsm->r_flags & BBR_ACKED) {
5361 		/* Problably MTU discovery messing with us */
5362 		uint32_t old_flags;
5363 
5364 		old_flags = rsm->r_flags;
5365 		rsm->r_flags &= ~BBR_ACKED;
5366 		bbr_log_type_rsmclear(bbr, cts, rsm, old_flags, __LINE__);
5367 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
5368 		if (bbr->r_ctl.rc_sacked == 0)
5369 			bbr->r_ctl.rc_sacklast = NULL;
5370 	}
5371 	if (rsm->r_in_tmap) {
5372 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5373 	}
5374 	TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5375 	rsm->r_in_tmap = 1;
5376 	if (rsm->r_flags & BBR_SACK_PASSED) {
5377 		/* We have retransmitted due to the SACK pass */
5378 		rsm->r_flags &= ~BBR_SACK_PASSED;
5379 		rsm->r_flags |= BBR_WAS_SACKPASS;
5380 	}
5381 	rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5382 	rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5383 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5384 	bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
5385 	if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5386 		rsm->r_is_gain = 1;
5387 		rsm->r_is_drain = 0;
5388 	} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
5389 		rsm->r_is_drain = 1;
5390 		rsm->r_is_gain = 0;
5391 	} else {
5392 		rsm->r_is_drain = 0;
5393 		rsm->r_is_gain = 0;
5394 	}
5395 	rsm->r_del_time = bbr->r_ctl.rc_del_time; /* TEMP GOOGLE CODE */
5396 }
5397 
5398 /*
5399  * Returns 0, or the sequence where we stopped
5400  * updating. We also update the lenp to be the amount
5401  * of data left.
5402  */
5403 
5404 static uint32_t
5405 bbr_update_entry(struct tcpcb *tp, struct tcp_bbr *bbr,
5406     struct bbr_sendmap *rsm, uint32_t cts, int32_t *lenp, uint32_t pacing_time)
5407 {
5408 	/*
5409 	 * We (re-)transmitted starting at rsm->r_start for some length
5410 	 * (possibly less than r_end.
5411 	 */
5412 	struct bbr_sendmap *nrsm;
5413 	uint32_t c_end;
5414 	int32_t len;
5415 
5416 	len = *lenp;
5417 	c_end = rsm->r_start + len;
5418 	if (SEQ_GEQ(c_end, rsm->r_end)) {
5419 		/*
5420 		 * We retransmitted the whole piece or more than the whole
5421 		 * slopping into the next rsm.
5422 		 */
5423 		bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5424 		if (c_end == rsm->r_end) {
5425 			*lenp = 0;
5426 			return (0);
5427 		} else {
5428 			int32_t act_len;
5429 
5430 			/* Hangs over the end return whats left */
5431 			act_len = rsm->r_end - rsm->r_start;
5432 			*lenp = (len - act_len);
5433 			return (rsm->r_end);
5434 		}
5435 		/* We don't get out of this block. */
5436 	}
5437 	/*
5438 	 * Here we retransmitted less than the whole thing which means we
5439 	 * have to split this into what was transmitted and what was not.
5440 	 */
5441 	nrsm = bbr_alloc_full_limit(bbr);
5442 	if (nrsm == NULL) {
5443 		*lenp = 0;
5444 		return (0);
5445 	}
5446 	/*
5447 	 * So here we are going to take the original rsm and make it what we
5448 	 * retransmitted. nrsm will be the tail portion we did not
5449 	 * retransmit. For example say the chunk was 1, 11 (10 bytes). And
5450 	 * we retransmitted 5 bytes i.e. 1, 5. The original piece shrinks to
5451 	 * 1, 6 and the new piece will be 6, 11.
5452 	 */
5453 	bbr_clone_rsm(bbr, nrsm, rsm, c_end);
5454 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
5455 	nrsm->r_dupack = 0;
5456 	if (rsm->r_in_tmap) {
5457 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
5458 		nrsm->r_in_tmap = 1;
5459 	}
5460 	rsm->r_flags &= (~BBR_HAS_FIN);
5461 	bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
5462 	*lenp = 0;
5463 	return (0);
5464 }
5465 
5466 static uint64_t
5467 bbr_get_hardware_rate(struct tcp_bbr *bbr)
5468 {
5469 	uint64_t bw;
5470 
5471 	bw = bbr_get_bw(bbr);
5472 	bw *= (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN];
5473 	bw /= (uint64_t)BBR_UNIT;
5474 	return(bw);
5475 }
5476 
5477 static void
5478 bbr_setup_less_of_rate(struct tcp_bbr *bbr, uint32_t cts,
5479 		       uint64_t act_rate, uint64_t rate_wanted)
5480 {
5481 	/*
5482 	 * We could not get a full gains worth
5483 	 * of rate.
5484 	 */
5485 	if (get_filter_value(&bbr->r_ctl.rc_delrate) >= act_rate) {
5486 		/* we can't even get the real rate */
5487 		uint64_t red;
5488 
5489 		bbr->skip_gain = 1;
5490 		bbr->gain_is_limited = 0;
5491 		red = get_filter_value(&bbr->r_ctl.rc_delrate) - act_rate;
5492 		if (red)
5493 			filter_reduce_by(&bbr->r_ctl.rc_delrate, red, cts);
5494 	} else {
5495 		/* We can use a lower gain */
5496 		bbr->skip_gain = 0;
5497 		bbr->gain_is_limited = 1;
5498 	}
5499 }
5500 
5501 static void
5502 bbr_update_hardware_pacing_rate(struct tcp_bbr *bbr, uint32_t cts)
5503 {
5504 	const struct tcp_hwrate_limit_table *nrte;
5505 	int error, rate = -1;
5506 
5507 	if (bbr->r_ctl.crte == NULL)
5508 		return;
5509 	if ((bbr->rc_inp->inp_route.ro_nh == NULL) ||
5510 	    (bbr->rc_inp->inp_route.ro_nh->nh_ifp == NULL)) {
5511 		/* Lost our routes? */
5512 		/* Clear the way for a re-attempt */
5513 		bbr->bbr_attempt_hdwr_pace = 0;
5514 lost_rate:
5515 		bbr->gain_is_limited = 0;
5516 		bbr->skip_gain = 0;
5517 		bbr->bbr_hdrw_pacing = 0;
5518 		counter_u64_add(bbr_flows_whdwr_pacing, -1);
5519 		counter_u64_add(bbr_flows_nohdwr_pacing, 1);
5520 		tcp_bbr_tso_size_check(bbr, cts);
5521 		return;
5522 	}
5523 	rate = bbr_get_hardware_rate(bbr);
5524 	nrte = tcp_chg_pacing_rate(bbr->r_ctl.crte,
5525 				   bbr->rc_tp,
5526 				   bbr->rc_inp->inp_route.ro_nh->nh_ifp,
5527 				   rate,
5528 				   (RS_PACING_GEQ|RS_PACING_SUB_OK),
5529 				   &error, NULL);
5530 	if (nrte == NULL) {
5531 		goto lost_rate;
5532 	}
5533 	if (nrte != bbr->r_ctl.crte) {
5534 		bbr->r_ctl.crte = nrte;
5535 		if (error == 0)  {
5536 			BBR_STAT_INC(bbr_hdwr_rl_mod_ok);
5537 			if (bbr->r_ctl.crte->rate < rate) {
5538 				/* We have a problem */
5539 				bbr_setup_less_of_rate(bbr, cts,
5540 						       bbr->r_ctl.crte->rate, rate);
5541 			} else {
5542 				/* We are good */
5543 				bbr->gain_is_limited = 0;
5544 				bbr->skip_gain = 0;
5545 			}
5546 		} else {
5547 			/* A failure should release the tag */
5548 			BBR_STAT_INC(bbr_hdwr_rl_mod_fail);
5549 			bbr->gain_is_limited = 0;
5550 			bbr->skip_gain = 0;
5551 			bbr->bbr_hdrw_pacing = 0;
5552 		}
5553 		bbr_type_log_hdwr_pacing(bbr,
5554 					 bbr->r_ctl.crte->ptbl->rs_ifp,
5555 					 rate,
5556 					 ((bbr->r_ctl.crte == NULL) ? 0 : bbr->r_ctl.crte->rate),
5557 					 __LINE__,
5558 					 cts,
5559 					 error);
5560 	}
5561 }
5562 
5563 static void
5564 bbr_adjust_for_hw_pacing(struct tcp_bbr *bbr, uint32_t cts)
5565 {
5566 	/*
5567 	 * If we have hardware pacing support
5568 	 * we need to factor that in for our
5569 	 * TSO size.
5570 	 */
5571 	const struct tcp_hwrate_limit_table *rlp;
5572 	uint32_t cur_delay, seg_sz, maxseg, new_tso, delta, hdwr_delay;
5573 
5574 	if ((bbr->bbr_hdrw_pacing == 0) ||
5575 	    (IN_RECOVERY(bbr->rc_tp->t_flags)) ||
5576 	    (bbr->r_ctl.crte == NULL))
5577 		return;
5578 	if (bbr->hw_pacing_set == 0) {
5579 		/* Not yet by the hdwr pacing count delay */
5580 		return;
5581 	}
5582 	if (bbr_hdwr_pace_adjust == 0) {
5583 		/* No adjustment */
5584 		return;
5585 	}
5586 	rlp = bbr->r_ctl.crte;
5587 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options)
5588 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5589 	else
5590 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5591 	/*
5592 	 * So lets first get the
5593 	 * time we will take between
5594 	 * TSO sized sends currently without
5595 	 * hardware help.
5596 	 */
5597 	cur_delay = bbr_get_pacing_delay(bbr, BBR_UNIT,
5598 		        bbr->r_ctl.rc_pace_max_segs, cts, 1);
5599 	hdwr_delay = bbr->r_ctl.rc_pace_max_segs / maxseg;
5600 	hdwr_delay *= rlp->time_between;
5601 	if (cur_delay > hdwr_delay)
5602 		delta = cur_delay - hdwr_delay;
5603 	else
5604 		delta = 0;
5605 	bbr_log_type_tsosize(bbr, cts, delta, cur_delay, hdwr_delay,
5606 			     (bbr->r_ctl.rc_pace_max_segs / maxseg),
5607 			     1);
5608 	if (delta &&
5609 	    (delta < (max(rlp->time_between,
5610 			  bbr->r_ctl.bbr_hptsi_segments_delay_tar)))) {
5611 		/*
5612 		 * Now lets divide by the pacing
5613 		 * time between each segment the
5614 		 * hardware sends rounding up and
5615 		 * derive a bytes from that. We multiply
5616 		 * that by bbr_hdwr_pace_adjust to get
5617 		 * more bang for our buck.
5618 		 *
5619 		 * The goal is to have the software pacer
5620 		 * waiting no more than an additional
5621 		 * pacing delay if we can (without the
5622 		 * compensation i.e. x bbr_hdwr_pace_adjust).
5623 		 */
5624 		seg_sz = max(((cur_delay + rlp->time_between)/rlp->time_between),
5625 			     (bbr->r_ctl.rc_pace_max_segs/maxseg));
5626 		seg_sz *= bbr_hdwr_pace_adjust;
5627 		if (bbr_hdwr_pace_floor &&
5628 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5629 			/* Currently hardware paces
5630 			 * out rs_min_seg segments at a time.
5631 			 * We need to make sure we always send at least
5632 			 * a full burst of bbr_hdwr_pace_floor down.
5633 			 */
5634 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5635 		}
5636 		seg_sz *= maxseg;
5637 	} else if (delta == 0) {
5638 		/*
5639 		 * The highest pacing rate is
5640 		 * above our b/w gained. This means
5641 		 * we probably are going quite fast at
5642 		 * the hardware highest rate. Lets just multiply
5643 		 * the calculated TSO size by the
5644 		 * multiplier factor (its probably
5645 		 * 4 segments in the default config for
5646 		 * mlx).
5647 		 */
5648 		seg_sz = bbr->r_ctl.rc_pace_max_segs * bbr_hdwr_pace_adjust;
5649 		if (bbr_hdwr_pace_floor &&
5650 		    (seg_sz < bbr->r_ctl.crte->ptbl->rs_min_seg)) {
5651 			/* Currently hardware paces
5652 			 * out rs_min_seg segments at a time.
5653 			 * We need to make sure we always send at least
5654 			 * a full burst of bbr_hdwr_pace_floor down.
5655 			 */
5656 			seg_sz = bbr->r_ctl.crte->ptbl->rs_min_seg;
5657 		}
5658 	} else {
5659 		/*
5660 		 * The pacing time difference is so
5661 		 * big that the hardware will
5662 		 * pace out more rapidly then we
5663 		 * really want and then we
5664 		 * will have a long delay. Lets just keep
5665 		 * the same TSO size so its as if
5666 		 * we were not using hdwr pacing (we
5667 		 * just gain a bit of spacing from the
5668 		 * hardware if seg_sz > 1).
5669 		 */
5670 		seg_sz = bbr->r_ctl.rc_pace_max_segs;
5671 	}
5672 	if (seg_sz > bbr->r_ctl.rc_pace_max_segs)
5673 		new_tso = seg_sz;
5674 	else
5675 		new_tso = bbr->r_ctl.rc_pace_max_segs;
5676 	if (new_tso >= (PACE_MAX_IP_BYTES-maxseg))
5677 		new_tso = PACE_MAX_IP_BYTES - maxseg;
5678 
5679 	if (new_tso != bbr->r_ctl.rc_pace_max_segs) {
5680 		bbr_log_type_tsosize(bbr, cts, new_tso, 0, bbr->r_ctl.rc_pace_max_segs, maxseg, 0);
5681 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5682 	}
5683 }
5684 
5685 static void
5686 tcp_bbr_tso_size_check(struct tcp_bbr *bbr, uint32_t cts)
5687 {
5688 	uint64_t bw;
5689 	uint32_t old_tso = 0, new_tso;
5690 	uint32_t maxseg, bytes;
5691 	uint32_t tls_seg=0;
5692 	/*
5693 	 * Google/linux uses the following algorithm to determine
5694 	 * the TSO size based on the b/w of the link (from Neal Cardwell email 9/27/18):
5695 	 *
5696 	 *  bytes = bw_in_bytes_per_second / 1000
5697 	 *  bytes = min(bytes, 64k)
5698 	 *  tso_segs = bytes / MSS
5699 	 *  if (bw < 1.2Mbs)
5700 	 *      min_tso_segs = 1
5701 	 *  else
5702 	 *	min_tso_segs = 2
5703 	 * tso_segs = max(tso_segs, min_tso_segs)
5704 	 *
5705 	 * * Note apply a device specific limit (we apply this in the
5706 	 *   tcp_m_copym).
5707 	 * Note that before the initial measurement is made google bursts out
5708 	 * a full iwnd just like new-reno/cubic.
5709 	 *
5710 	 * We do not use this algorithm. Instead we
5711 	 * use a two phased approach:
5712 	 *
5713 	 *  if ( bw <= per-tcb-cross-over)
5714 	 *     goal_tso =  calculate how much with this bw we
5715 	 *                 can send in goal-time seconds.
5716 	 *     if (goal_tso > mss)
5717 	 *         seg = goal_tso / mss
5718 	 *         tso = seg * mss
5719 	 *     else
5720 	 *         tso = mss
5721 	 *     if (tso > per-tcb-max)
5722 	 *         tso = per-tcb-max
5723 	 *  else if ( bw > 512Mbps)
5724 	 *     tso = max-tso (64k/mss)
5725 	 *  else
5726 	 *     goal_tso = bw / per-tcb-divsor
5727 	 *     seg = (goal_tso + mss-1)/mss
5728 	 *     tso = seg * mss
5729 	 *
5730 	 * if (tso < per-tcb-floor)
5731 	 *    tso = per-tcb-floor
5732 	 * if (tso > per-tcb-utter_max)
5733 	 *    tso = per-tcb-utter_max
5734 	 *
5735 	 * Note the default per-tcb-divisor is 1000 (same as google).
5736 	 * the goal cross over is 30Mbps however. To recreate googles
5737 	 * algorithm you need to set:
5738 	 *
5739 	 * cross-over = 23,168,000 bps
5740 	 * goal-time = 18000
5741 	 * per-tcb-max = 2
5742 	 * per-tcb-divisor = 1000
5743 	 * per-tcb-floor = 1
5744 	 *
5745 	 * This will get you "google bbr" behavior with respect to tso size.
5746 	 *
5747 	 * Note we do set anything TSO size until we are past the initial
5748 	 * window. Before that we gnerally use either a single MSS
5749 	 * or we use the full IW size (so we burst a IW at a time)
5750 	 */
5751 
5752 	if (bbr->rc_tp->t_maxseg > bbr->rc_last_options) {
5753 		maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5754 	} else {
5755 		maxseg = BBR_MIN_SEG - bbr->rc_last_options;
5756 	}
5757 	old_tso = bbr->r_ctl.rc_pace_max_segs;
5758 	if (bbr->rc_past_init_win == 0) {
5759 		/*
5760 		 * Not enough data has been acknowledged to make a
5761 		 * judgement. Set up the initial TSO based on if we
5762 		 * are sending a full IW at once or not.
5763 		 */
5764 		if (bbr->rc_use_google)
5765 			bbr->r_ctl.rc_pace_max_segs = ((bbr->rc_tp->t_maxseg - bbr->rc_last_options) * 2);
5766 		else if (bbr->bbr_init_win_cheat)
5767 			bbr->r_ctl.rc_pace_max_segs = bbr_initial_cwnd(bbr, bbr->rc_tp);
5768 		else
5769 			bbr->r_ctl.rc_pace_max_segs = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
5770 		if (bbr->r_ctl.rc_pace_min_segs != bbr->rc_tp->t_maxseg)
5771 			bbr->r_ctl.rc_pace_min_segs = bbr->rc_tp->t_maxseg;
5772 		if (bbr->r_ctl.rc_pace_max_segs == 0) {
5773 			bbr->r_ctl.rc_pace_max_segs = maxseg;
5774 		}
5775 		bbr_log_type_tsosize(bbr, cts, bbr->r_ctl.rc_pace_max_segs, tls_seg, old_tso, maxseg, 0);
5776 			bbr_adjust_for_hw_pacing(bbr, cts);
5777 		return;
5778 	}
5779 	/**
5780 	 * Now lets set the TSO goal based on our delivery rate in
5781 	 * bytes per second. Note we only do this if
5782 	 * we have acked at least the initial cwnd worth of data.
5783 	 */
5784 	bw = bbr_get_bw(bbr);
5785 	if (IN_RECOVERY(bbr->rc_tp->t_flags) &&
5786 	     (bbr->rc_use_google == 0)) {
5787 		/* We clamp to one MSS in recovery */
5788 		new_tso = maxseg;
5789 	} else if (bbr->rc_use_google) {
5790 		int min_tso_segs;
5791 
5792 		/* Google considers the gain too */
5793 		if (bbr->r_ctl.rc_bbr_hptsi_gain != BBR_UNIT) {
5794 			bw *= bbr->r_ctl.rc_bbr_hptsi_gain;
5795 			bw /= BBR_UNIT;
5796 		}
5797 		bytes = bw / 1024;
5798 		if (bytes > (64 * 1024))
5799 			bytes = 64 * 1024;
5800 		new_tso = bytes / maxseg;
5801 		if (bw < ONE_POINT_TWO_MEG)
5802 			min_tso_segs = 1;
5803 		else
5804 			min_tso_segs = 2;
5805 		if (new_tso < min_tso_segs)
5806 			new_tso = min_tso_segs;
5807 		new_tso *= maxseg;
5808 	} else if (bbr->rc_no_pacing) {
5809 		new_tso = (PACE_MAX_IP_BYTES / maxseg) * maxseg;
5810 	} else if (bw <= bbr->r_ctl.bbr_cross_over) {
5811 		/*
5812 		 * Calculate the worse case b/w TSO if we are inserting no
5813 		 * more than a delay_target number of TSO's.
5814 		 */
5815 		uint32_t tso_len, min_tso;
5816 
5817 		tso_len = bbr_get_pacing_length(bbr, BBR_UNIT, bbr->r_ctl.bbr_hptsi_segments_delay_tar, bw);
5818 		if (tso_len > maxseg) {
5819 			new_tso = tso_len / maxseg;
5820 			if (new_tso > bbr->r_ctl.bbr_hptsi_segments_max)
5821 				new_tso = bbr->r_ctl.bbr_hptsi_segments_max;
5822 			new_tso *= maxseg;
5823 		} else {
5824 			/*
5825 			 * less than a full sized frame yikes.. long rtt or
5826 			 * low bw?
5827 			 */
5828 			min_tso = bbr_minseg(bbr);
5829 			if ((tso_len > min_tso) && (bbr_all_get_min == 0))
5830 				new_tso = rounddown(tso_len, min_tso);
5831 			else
5832 				new_tso = min_tso;
5833 		}
5834 	} else if (bw > FIVETWELVE_MBPS) {
5835 		/*
5836 		 * This guy is so fast b/w wise that we can TSO as large as
5837 		 * possible of segments that the NIC will allow.
5838 		 */
5839 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5840 	} else {
5841 		/*
5842 		 * This formula is based on attempting to send a segment or
5843 		 * more every bbr_hptsi_per_second. The default is 1000
5844 		 * which means you are targeting what you can send every 1ms
5845 		 * based on the peers bw.
5846 		 *
5847 		 * If the number drops to say 500, then you are looking more
5848 		 * at 2ms and you will raise how much we send in a single
5849 		 * TSO thus saving CPU (less bbr_output_wtime() calls). The
5850 		 * trade off of course is you will send more at once and
5851 		 * thus tend to clump up the sends into larger "bursts"
5852 		 * building a queue.
5853 		 */
5854 		bw /= bbr->r_ctl.bbr_hptsi_per_second;
5855 		new_tso = roundup(bw, (uint64_t)maxseg);
5856 		/*
5857 		 * Gate the floor to match what our lower than 48Mbps
5858 		 * algorithm does. The ceiling (bbr_hptsi_segments_max) thus
5859 		 * becomes the floor for this calculation.
5860 		 */
5861 		if (new_tso < (bbr->r_ctl.bbr_hptsi_segments_max * maxseg))
5862 			new_tso = (bbr->r_ctl.bbr_hptsi_segments_max * maxseg);
5863 	}
5864 	if (bbr->r_ctl.bbr_hptsi_segments_floor && (new_tso < (maxseg * bbr->r_ctl.bbr_hptsi_segments_floor)))
5865 		new_tso = maxseg * bbr->r_ctl.bbr_hptsi_segments_floor;
5866 	if (new_tso > PACE_MAX_IP_BYTES)
5867 		new_tso = rounddown(PACE_MAX_IP_BYTES, maxseg);
5868 	/* Enforce an utter maximum. */
5869 	if (bbr->r_ctl.bbr_utter_max && (new_tso > (bbr->r_ctl.bbr_utter_max * maxseg))) {
5870 		new_tso = bbr->r_ctl.bbr_utter_max * maxseg;
5871 	}
5872 	if (old_tso != new_tso) {
5873 		/* Only log changes */
5874 		bbr_log_type_tsosize(bbr, cts, new_tso, tls_seg, old_tso, maxseg, 0);
5875 		bbr->r_ctl.rc_pace_max_segs = new_tso;
5876 	}
5877 	/* We have hardware pacing! */
5878 	bbr_adjust_for_hw_pacing(bbr, cts);
5879 }
5880 
5881 static void
5882 bbr_log_output(struct tcp_bbr *bbr, struct tcpcb *tp, struct tcpopt *to, int32_t len,
5883     uint32_t seq_out, uint16_t th_flags, int32_t err, uint32_t cts,
5884     struct mbuf *mb, int32_t * abandon, struct bbr_sendmap *hintrsm, uint32_t delay_calc,
5885     struct sockbuf *sb)
5886 {
5887 
5888 	struct bbr_sendmap *rsm, *nrsm;
5889 	register uint32_t snd_max, snd_una;
5890 	uint32_t pacing_time;
5891 	/*
5892 	 * Add to the RACK log of packets in flight or retransmitted. If
5893 	 * there is a TS option we will use the TS echoed, if not we will
5894 	 * grab a TS.
5895 	 *
5896 	 * Retransmissions will increment the count and move the ts to its
5897 	 * proper place. Note that if options do not include TS's then we
5898 	 * won't be able to effectively use the ACK for an RTT on a retran.
5899 	 *
5900 	 * Notes about r_start and r_end. Lets consider a send starting at
5901 	 * sequence 1 for 10 bytes. In such an example the r_start would be
5902 	 * 1 (starting sequence) but the r_end would be r_start+len i.e. 11.
5903 	 * This means that r_end is actually the first sequence for the next
5904 	 * slot (11).
5905 	 *
5906 	 */
5907 	INP_WLOCK_ASSERT(tptoinpcb(tp));
5908 	if (err) {
5909 		/*
5910 		 * We don't log errors -- we could but snd_max does not
5911 		 * advance in this case either.
5912 		 */
5913 		return;
5914 	}
5915 	if (th_flags & TH_RST) {
5916 		/*
5917 		 * We don't log resets and we return immediately from
5918 		 * sending
5919 		 */
5920 		*abandon = 1;
5921 		return;
5922 	}
5923 	snd_una = tp->snd_una;
5924 	if (th_flags & (TH_SYN | TH_FIN) && (hintrsm == NULL)) {
5925 		/*
5926 		 * The call to bbr_log_output is made before bumping
5927 		 * snd_max. This means we can record one extra byte on a SYN
5928 		 * or FIN if seq_out is adding more on and a FIN is present
5929 		 * (and we are not resending).
5930 		 */
5931 		if ((th_flags & TH_SYN) && (tp->iss == seq_out))
5932 			len++;
5933 		if (th_flags & TH_FIN)
5934 			len++;
5935 	}
5936 	if (SEQ_LEQ((seq_out + len), snd_una)) {
5937 		/* Are sending an old segment to induce an ack (keep-alive)? */
5938 		return;
5939 	}
5940 	if (SEQ_LT(seq_out, snd_una)) {
5941 		/* huh? should we panic? */
5942 		uint32_t end;
5943 
5944 		end = seq_out + len;
5945 		seq_out = snd_una;
5946 		len = end - seq_out;
5947 	}
5948 	snd_max = tp->snd_max;
5949 	if (len == 0) {
5950 		/* We don't log zero window probes */
5951 		return;
5952 	}
5953 	pacing_time = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, len, cts, 1);
5954 	/* First question is it a retransmission? */
5955 	if (seq_out == snd_max) {
5956 again:
5957 		rsm = bbr_alloc(bbr);
5958 		if (rsm == NULL) {
5959 			return;
5960 		}
5961 		rsm->r_flags = 0;
5962 		if (th_flags & TH_SYN)
5963 			rsm->r_flags |= BBR_HAS_SYN;
5964 		if (th_flags & TH_FIN)
5965 			rsm->r_flags |= BBR_HAS_FIN;
5966 		rsm->r_tim_lastsent[0] = cts;
5967 		rsm->r_rtr_cnt = 1;
5968 		rsm->r_rtr_bytes = 0;
5969 		rsm->r_start = seq_out;
5970 		rsm->r_end = rsm->r_start + len;
5971 		rsm->r_dupack = 0;
5972 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
5973 		rsm->r_pacing_delay = pacing_time;
5974 		rsm->r_ts_valid = bbr->rc_ts_valid;
5975 		if (bbr->rc_ts_valid)
5976 			rsm->r_del_ack_ts = bbr->r_ctl.last_inbound_ts;
5977 		rsm->r_del_time = bbr->r_ctl.rc_del_time;
5978 		if (bbr->r_ctl.r_app_limited_until)
5979 			rsm->r_app_limited = 1;
5980 		else
5981 			rsm->r_app_limited = 0;
5982 		rsm->r_first_sent_time = bbr_get_earliest_send_outstanding(bbr, rsm, cts);
5983 		rsm->r_flight_at_send = ctf_flight_size(bbr->rc_tp,
5984 						(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
5985 		/*
5986 		 * Here we must also add in this rsm since snd_max
5987 		 * is updated after we return from a new send.
5988 		 */
5989 		rsm->r_flight_at_send += len;
5990 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
5991 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
5992 		rsm->r_in_tmap = 1;
5993 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
5994 			rsm->r_bbr_state = bbr_state_val(bbr);
5995 		else
5996 			rsm->r_bbr_state = 8;
5997 		if (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT) {
5998 			rsm->r_is_gain = 1;
5999 			rsm->r_is_drain = 0;
6000 		} else if (bbr->r_ctl.rc_bbr_hptsi_gain < BBR_UNIT) {
6001 			rsm->r_is_drain = 1;
6002 			rsm->r_is_gain = 0;
6003 		} else {
6004 			rsm->r_is_drain = 0;
6005 			rsm->r_is_gain = 0;
6006 		}
6007 		return;
6008 	}
6009 	/*
6010 	 * If we reach here its a retransmission and we need to find it.
6011 	 */
6012 more:
6013 	if (hintrsm && (hintrsm->r_start == seq_out)) {
6014 		rsm = hintrsm;
6015 		hintrsm = NULL;
6016 	} else if (bbr->r_ctl.rc_next) {
6017 		/* We have a hint from a previous run */
6018 		rsm = bbr->r_ctl.rc_next;
6019 	} else {
6020 		/* No hints sorry */
6021 		rsm = NULL;
6022 	}
6023 	if ((rsm) && (rsm->r_start == seq_out)) {
6024 		/*
6025 		 * We used rc_next or hintrsm  to retransmit, hopefully the
6026 		 * likely case.
6027 		 */
6028 		seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6029 		if (len == 0) {
6030 			return;
6031 		} else {
6032 			goto more;
6033 		}
6034 	}
6035 	/* Ok it was not the last pointer go through it the hard way. */
6036 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6037 		if (rsm->r_start == seq_out) {
6038 			seq_out = bbr_update_entry(tp, bbr, rsm, cts, &len, pacing_time);
6039 			bbr->r_ctl.rc_next = TAILQ_NEXT(rsm, r_next);
6040 			if (len == 0) {
6041 				return;
6042 			} else {
6043 				continue;
6044 			}
6045 		}
6046 		if (SEQ_GEQ(seq_out, rsm->r_start) && SEQ_LT(seq_out, rsm->r_end)) {
6047 			/* Transmitted within this piece */
6048 			/*
6049 			 * Ok we must split off the front and then let the
6050 			 * update do the rest
6051 			 */
6052 			nrsm = bbr_alloc_full_limit(bbr);
6053 			if (nrsm == NULL) {
6054 				bbr_update_rsm(tp, bbr, rsm, cts, pacing_time);
6055 				return;
6056 			}
6057 			/*
6058 			 * copy rsm to nrsm and then trim the front of rsm
6059 			 * to not include this part.
6060 			 */
6061 			bbr_clone_rsm(bbr, nrsm, rsm, seq_out);
6062 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
6063 			if (rsm->r_in_tmap) {
6064 				TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
6065 				nrsm->r_in_tmap = 1;
6066 			}
6067 			rsm->r_flags &= (~BBR_HAS_FIN);
6068 			seq_out = bbr_update_entry(tp, bbr, nrsm, cts, &len, pacing_time);
6069 			if (len == 0) {
6070 				return;
6071 			}
6072 		}
6073 	}
6074 	/*
6075 	 * Hmm not found in map did they retransmit both old and on into the
6076 	 * new?
6077 	 */
6078 	if (seq_out == tp->snd_max) {
6079 		goto again;
6080 	} else if (SEQ_LT(seq_out, tp->snd_max)) {
6081 #ifdef BBR_INVARIANTS
6082 		printf("seq_out:%u len:%d snd_una:%u snd_max:%u -- but rsm not found?\n",
6083 		    seq_out, len, tp->snd_una, tp->snd_max);
6084 		printf("Starting Dump of all rack entries\n");
6085 		TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
6086 			printf("rsm:%p start:%u end:%u\n",
6087 			    rsm, rsm->r_start, rsm->r_end);
6088 		}
6089 		printf("Dump complete\n");
6090 		panic("seq_out not found rack:%p tp:%p",
6091 		    bbr, tp);
6092 #endif
6093 	} else {
6094 #ifdef BBR_INVARIANTS
6095 		/*
6096 		 * Hmm beyond sndmax? (only if we are using the new rtt-pack
6097 		 * flag)
6098 		 */
6099 		panic("seq_out:%u(%d) is beyond snd_max:%u tp:%p",
6100 		    seq_out, len, tp->snd_max, tp);
6101 #endif
6102 	}
6103 }
6104 
6105 static void
6106 bbr_collapse_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, int32_t rtt)
6107 {
6108 	/*
6109 	 * Collapse timeout back the cum-ack moved.
6110 	 */
6111 	tp->t_rxtshift = 0;
6112 	tp->t_softerror = 0;
6113 }
6114 
6115 static void
6116 tcp_bbr_xmit_timer(struct tcp_bbr *bbr, uint32_t rtt_usecs, uint32_t rsm_send_time, uint32_t r_start, uint32_t tsin)
6117 {
6118 	bbr->rtt_valid = 1;
6119 	bbr->r_ctl.cur_rtt = rtt_usecs;
6120 	bbr->r_ctl.ts_in = tsin;
6121 	if (rsm_send_time)
6122 		bbr->r_ctl.cur_rtt_send_time = rsm_send_time;
6123 }
6124 
6125 static void
6126 bbr_make_timestamp_determination(struct tcp_bbr *bbr)
6127 {
6128 	/**
6129 	 * We have in our bbr control:
6130 	 * 1) The timestamp we started observing cum-acks (bbr->r_ctl.bbr_ts_check_tstmp).
6131 	 * 2) Our timestamp indicating when we sent that packet (bbr->r_ctl.rsm->bbr_ts_check_our_cts).
6132 	 * 3) The current timestamp that just came in (bbr->r_ctl.last_inbound_ts)
6133 	 * 4) The time that the packet that generated that ack was sent (bbr->r_ctl.cur_rtt_send_time)
6134 	 *
6135 	 * Now we can calculate the time between the sends by doing:
6136 	 *
6137 	 * delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts
6138 	 *
6139 	 * And the peer's time between receiving them by doing:
6140 	 *
6141 	 * peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp
6142 	 *
6143 	 * We want to figure out if the timestamp values are in msec, 10msec or usec.
6144 	 * We also may find that we can't use the timestamps if say we see
6145 	 * that the peer_delta indicates that though we may have taken 10ms to
6146 	 * pace out the data, it only saw 1ms between the two packets. This would
6147 	 * indicate that somewhere on the path is a batching entity that is giving
6148 	 * out time-slices of the actual b/w. This would mean we could not use
6149 	 * reliably the peers timestamps.
6150 	 *
6151 	 * We expect delta > peer_delta initially. Until we figure out the
6152 	 * timestamp difference which we will store in bbr->r_ctl.bbr_peer_tsratio.
6153 	 * If we place 1000 there then its a ms vs our usec. If we place 10000 there
6154 	 * then its 10ms vs our usec. If the peer is running a usec clock we would
6155 	 * put a 1 there. If the value is faster then ours, we will disable the
6156 	 * use of timestamps (though we could revist this later if we find it to be not
6157 	 * just an isolated one or two flows)).
6158 	 *
6159 	 * To detect the batching middle boxes we will come up with our compensation and
6160 	 * if with it in place, we find the peer is drastically off (by some margin) in
6161 	 * the smaller direction, then we will assume the worst case and disable use of timestamps.
6162 	 *
6163 	 */
6164 	uint64_t delta, peer_delta, delta_up;
6165 
6166 	delta = bbr->r_ctl.cur_rtt_send_time - bbr->r_ctl.bbr_ts_check_our_cts;
6167 	if (delta < bbr_min_usec_delta) {
6168 		/*
6169 		 * Have not seen a min amount of time
6170 		 * between our send times so we can
6171 		 * make a determination of the timestamp
6172 		 * yet.
6173 		 */
6174 		return;
6175 	}
6176 	peer_delta = bbr->r_ctl.last_inbound_ts - bbr->r_ctl.bbr_ts_check_tstmp;
6177 	if (peer_delta < bbr_min_peer_delta) {
6178 		/*
6179 		 * We may have enough in the form of
6180 		 * our delta but the peers number
6181 		 * has not changed that much. It could
6182 		 * be its clock ratio is such that
6183 		 * we need more data (10ms tick) or
6184 		 * there may be other compression scenarios
6185 		 * going on. In any event we need the
6186 		 * spread to be larger.
6187 		 */
6188 		return;
6189 	}
6190 	/* Ok lets first see which way our delta is going */
6191 	if (peer_delta > delta) {
6192 		/* Very unlikely, the peer without
6193 		 * compensation shows that it saw
6194 		 * the two sends arrive further apart
6195 		 * then we saw then in micro-seconds.
6196 		 */
6197 		if (peer_delta < (delta + ((delta * (uint64_t)1000)/ (uint64_t)bbr_delta_percent))) {
6198 			/* well it looks like the peer is a micro-second clock. */
6199 			bbr->rc_ts_clock_set = 1;
6200 			bbr->r_ctl.bbr_peer_tsratio = 1;
6201 		} else {
6202 			bbr->rc_ts_cant_be_used = 1;
6203 			bbr->rc_ts_clock_set = 1;
6204 		}
6205 		return;
6206 	}
6207 	/* Ok we know that the peer_delta is smaller than our send distance */
6208 	bbr->rc_ts_clock_set = 1;
6209 	/* First question is it within the percentage that they are using usec time? */
6210 	delta_up = (peer_delta * 1000) / (uint64_t)bbr_delta_percent;
6211 	if ((peer_delta + delta_up) >= delta) {
6212 		/* Its a usec clock */
6213 		bbr->r_ctl.bbr_peer_tsratio = 1;
6214 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6215 		return;
6216 	}
6217 	/* Ok if not usec, what about 10usec (though unlikely)? */
6218 	delta_up = (peer_delta * 1000 * 10) / (uint64_t)bbr_delta_percent;
6219 	if (((peer_delta * 10) + delta_up) >= delta) {
6220 		bbr->r_ctl.bbr_peer_tsratio = 10;
6221 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6222 		return;
6223 	}
6224 	/* And what about 100usec (though again unlikely)? */
6225 	delta_up = (peer_delta * 1000 * 100) / (uint64_t)bbr_delta_percent;
6226 	if (((peer_delta * 100) + delta_up) >= delta) {
6227 		bbr->r_ctl.bbr_peer_tsratio = 100;
6228 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6229 		return;
6230 	}
6231 	/* And how about 1 msec (the most likely one)? */
6232 	delta_up = (peer_delta * 1000 * 1000) / (uint64_t)bbr_delta_percent;
6233 	if (((peer_delta * 1000) + delta_up) >= delta) {
6234 		bbr->r_ctl.bbr_peer_tsratio = 1000;
6235 		bbr_log_tstmp_validation(bbr, peer_delta, delta);
6236 		return;
6237 	}
6238 	/* Ok if not msec could it be 10 msec? */
6239 	delta_up = (peer_delta * 1000 * 10000) / (uint64_t)bbr_delta_percent;
6240 	if (((peer_delta * 10000) + delta_up) >= delta) {
6241 		bbr->r_ctl.bbr_peer_tsratio = 10000;
6242 		return;
6243 	}
6244 	/* If we fall down here the clock tick so slowly we can't use it */
6245 	bbr->rc_ts_cant_be_used = 1;
6246 	bbr->r_ctl.bbr_peer_tsratio = 0;
6247 	bbr_log_tstmp_validation(bbr, peer_delta, delta);
6248 }
6249 
6250 /*
6251  * Collect new round-trip time estimate
6252  * and update averages and current timeout.
6253  */
6254 static void
6255 tcp_bbr_xmit_timer_commit(struct tcp_bbr *bbr, struct tcpcb *tp, uint32_t cts)
6256 {
6257 	int32_t delta;
6258 	uint32_t rtt, tsin;
6259 	int32_t rtt_ticks;
6260 
6261 	if (bbr->rtt_valid == 0)
6262 		/* No valid sample */
6263 		return;
6264 
6265 	rtt = bbr->r_ctl.cur_rtt;
6266 	tsin = bbr->r_ctl.ts_in;
6267 	if (bbr->rc_prtt_set_ts) {
6268 		/*
6269 		 * We are to force feed the rttProp filter due
6270 		 * to an entry into PROBE_RTT. This assures
6271 		 * that the times are sync'd between when we
6272 		 * go into PROBE_RTT and the filter expiration.
6273 		 *
6274 		 * Google does not use a true filter, so they do
6275 		 * this implicitly since they only keep one value
6276 		 * and when they enter probe-rtt they update the
6277 		 * value to the newest rtt.
6278 		 */
6279 		uint32_t rtt_prop;
6280 
6281 		bbr->rc_prtt_set_ts = 0;
6282 		rtt_prop = get_filter_value_small(&bbr->r_ctl.rc_rttprop);
6283 		if (rtt > rtt_prop)
6284 			filter_increase_by_small(&bbr->r_ctl.rc_rttprop, (rtt - rtt_prop), cts);
6285 		else
6286 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6287 	}
6288 #ifdef STATS
6289 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_PATHRTT, imax(0, rtt));
6290 #endif
6291 	if (bbr->rc_ack_was_delayed)
6292 		rtt += bbr->r_ctl.rc_ack_hdwr_delay;
6293 
6294 	if (rtt < bbr->r_ctl.rc_lowest_rtt)
6295 		bbr->r_ctl.rc_lowest_rtt = rtt;
6296 	bbr_log_rtt_sample(bbr, rtt, tsin);
6297 	if (bbr->r_init_rtt) {
6298 		/*
6299 		 * The initial rtt is not-trusted, nuke it and lets get
6300 		 * our first valid measurement in.
6301 		 */
6302 		bbr->r_init_rtt = 0;
6303 		tp->t_srtt = 0;
6304 	}
6305 	if ((bbr->rc_ts_clock_set == 0) && bbr->rc_ts_valid) {
6306 		/*
6307 		 * So we have not yet figured out
6308 		 * what the peers TSTMP value is
6309 		 * in (most likely ms). We need a
6310 		 * series of cum-ack's to determine
6311 		 * this reliably.
6312 		 */
6313 		if (bbr->rc_ack_is_cumack) {
6314 			if (bbr->rc_ts_data_set) {
6315 				/* Lets attempt to determine the timestamp granularity. */
6316 				bbr_make_timestamp_determination(bbr);
6317 			} else {
6318 				bbr->rc_ts_data_set = 1;
6319 				bbr->r_ctl.bbr_ts_check_tstmp = bbr->r_ctl.last_inbound_ts;
6320 				bbr->r_ctl.bbr_ts_check_our_cts = bbr->r_ctl.cur_rtt_send_time;
6321 			}
6322 		} else {
6323 			/*
6324 			 * We have to have consecutive acks
6325 			 * reset any "filled" state to none.
6326 			 */
6327 			bbr->rc_ts_data_set = 0;
6328 		}
6329 	}
6330 	/* Round it up */
6331 	rtt_ticks = USEC_2_TICKS((rtt + (USECS_IN_MSEC - 1)));
6332 	if (rtt_ticks == 0)
6333 		rtt_ticks = 1;
6334 	if (tp->t_srtt != 0) {
6335 		/*
6336 		 * srtt is stored as fixed point with 5 bits after the
6337 		 * binary point (i.e., scaled by 8).  The following magic is
6338 		 * equivalent to the smoothing algorithm in rfc793 with an
6339 		 * alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed point).
6340 		 * Adjust rtt to origin 0.
6341 		 */
6342 
6343 		delta = ((rtt_ticks - 1) << TCP_DELTA_SHIFT)
6344 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6345 
6346 		tp->t_srtt += delta;
6347 		if (tp->t_srtt <= 0)
6348 			tp->t_srtt = 1;
6349 
6350 		/*
6351 		 * We accumulate a smoothed rtt variance (actually, a
6352 		 * smoothed mean difference), then set the retransmit timer
6353 		 * to smoothed rtt + 4 times the smoothed variance. rttvar
6354 		 * is stored as fixed point with 4 bits after the binary
6355 		 * point (scaled by 16).  The following is equivalent to
6356 		 * rfc793 smoothing with an alpha of .75 (rttvar =
6357 		 * rttvar*3/4 + |delta| / 4).  This replaces rfc793's
6358 		 * wired-in beta.
6359 		 */
6360 		if (delta < 0)
6361 			delta = -delta;
6362 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6363 		tp->t_rttvar += delta;
6364 		if (tp->t_rttvar <= 0)
6365 			tp->t_rttvar = 1;
6366 	} else {
6367 		/*
6368 		 * No rtt measurement yet - use the unsmoothed rtt. Set the
6369 		 * variance to half the rtt (so our first retransmit happens
6370 		 * at 3*rtt).
6371 		 */
6372 		tp->t_srtt = rtt_ticks << TCP_RTT_SHIFT;
6373 		tp->t_rttvar = rtt_ticks << (TCP_RTTVAR_SHIFT - 1);
6374 	}
6375 	KMOD_TCPSTAT_INC(tcps_rttupdated);
6376 	if (tp->t_rttupdated < UCHAR_MAX)
6377 		tp->t_rttupdated++;
6378 #ifdef STATS
6379 	stats_voi_update_abs_u32(tp->t_stats, VOI_TCP_RTT, imax(0, rtt_ticks));
6380 #endif
6381 	/*
6382 	 * the retransmit should happen at rtt + 4 * rttvar. Because of the
6383 	 * way we do the smoothing, srtt and rttvar will each average +1/2
6384 	 * tick of bias.  When we compute the retransmit timer, we want 1/2
6385 	 * tick of rounding and 1 extra tick because of +-1/2 tick
6386 	 * uncertainty in the firing of the timer.  The bias will give us
6387 	 * exactly the 1.5 tick we need.  But, because the bias is
6388 	 * statistical, we have to test that we don't drop below the minimum
6389 	 * feasible timer (which is 2 ticks).
6390 	 */
6391 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6392 	    max(MSEC_2_TICKS(bbr->r_ctl.rc_min_rto_ms), rtt_ticks + 2),
6393 	    MSEC_2_TICKS(((uint32_t)bbr->rc_max_rto_sec) * 1000));
6394 
6395 	/*
6396 	 * We received an ack for a packet that wasn't retransmitted; it is
6397 	 * probably safe to discard any error indications we've received
6398 	 * recently.  This isn't quite right, but close enough for now (a
6399 	 * route might have failed after we sent a segment, and the return
6400 	 * path might not be symmetrical).
6401 	 */
6402 	tp->t_softerror = 0;
6403 	rtt = (TICKS_2_USEC(bbr->rc_tp->t_srtt) >> TCP_RTT_SHIFT);
6404 	if (bbr->r_ctl.bbr_smallest_srtt_this_state > rtt)
6405 		bbr->r_ctl.bbr_smallest_srtt_this_state = rtt;
6406 }
6407 
6408 static void
6409 bbr_set_reduced_rtt(struct tcp_bbr *bbr, uint32_t cts, uint32_t line)
6410 {
6411 	bbr->r_ctl.rc_rtt_shrinks = cts;
6412 	if (bbr_can_force_probertt &&
6413 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
6414 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
6415 		/*
6416 		 * We should enter probe-rtt its been too long
6417 		 * since we have been there.
6418 		 */
6419 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
6420 	} else
6421 		bbr_check_probe_rtt_limits(bbr, cts);
6422 }
6423 
6424 static void
6425 tcp_bbr_commit_bw(struct tcp_bbr *bbr, uint32_t cts)
6426 {
6427 	uint64_t orig_bw;
6428 
6429 	if (bbr->r_ctl.rc_bbr_cur_del_rate == 0) {
6430 		/* We never apply a zero measurement */
6431 		bbr_log_type_bbrupd(bbr, 20, cts, 0, 0,
6432 				    0, 0, 0, 0, 0, 0);
6433 		return;
6434 	}
6435 	if (bbr->r_ctl.r_measurement_count < 0xffffffff)
6436 		bbr->r_ctl.r_measurement_count++;
6437 	orig_bw = get_filter_value(&bbr->r_ctl.rc_delrate);
6438 	apply_filter_max(&bbr->r_ctl.rc_delrate, bbr->r_ctl.rc_bbr_cur_del_rate, bbr->r_ctl.rc_pkt_epoch);
6439 	bbr_log_type_bbrupd(bbr, 21, cts, (uint32_t)orig_bw,
6440 			    (uint32_t)get_filter_value(&bbr->r_ctl.rc_delrate),
6441 			    0, 0, 0, 0, 0, 0);
6442 	if (orig_bw &&
6443 	    (orig_bw != get_filter_value(&bbr->r_ctl.rc_delrate))) {
6444 		if (bbr->bbr_hdrw_pacing) {
6445 			/*
6446 			 * Apply a new rate to the hardware
6447 			 * possibly.
6448 			 */
6449 			bbr_update_hardware_pacing_rate(bbr, cts);
6450 		}
6451 		bbr_set_state_target(bbr, __LINE__);
6452 		tcp_bbr_tso_size_check(bbr, cts);
6453 		if (bbr->r_recovery_bw)  {
6454 			bbr_setup_red_bw(bbr, cts);
6455 			bbr_log_type_bw_reduce(bbr, BBR_RED_BW_USELRBW);
6456 		}
6457 	} else if ((orig_bw == 0) && get_filter_value(&bbr->r_ctl.rc_delrate))
6458 		tcp_bbr_tso_size_check(bbr, cts);
6459 }
6460 
6461 static void
6462 bbr_nf_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6463 {
6464 	if (bbr->rc_in_persist == 0) {
6465 		/* We log only when not in persist */
6466 		/* Translate to a Bytes Per Second */
6467 		uint64_t tim, bw, ts_diff, ts_bw;
6468 		uint32_t delivered;
6469 
6470 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6471 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6472 		else
6473 			tim = 1;
6474 		/*
6475 		 * Now that we have processed the tim (skipping the sample
6476 		 * or possibly updating the time, go ahead and
6477 		 * calculate the cdr.
6478 		 */
6479 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6480 		bw = (uint64_t)delivered;
6481 		bw *= (uint64_t)USECS_IN_SECOND;
6482 		bw /= tim;
6483 		if (bw == 0) {
6484 			/* We must have a calculatable amount */
6485 			return;
6486 		}
6487 		/*
6488 		 * If we are using this b/w shove it in now so we
6489 		 * can see in the trace viewer if it gets over-ridden.
6490 		 */
6491 		if (rsm->r_ts_valid &&
6492 		    bbr->rc_ts_valid &&
6493 		    bbr->rc_ts_clock_set &&
6494 		    (bbr->rc_ts_cant_be_used == 0) &&
6495 		    bbr->rc_use_ts_limit) {
6496 			ts_diff = max((bbr->r_ctl.last_inbound_ts - rsm->r_del_ack_ts), 1);
6497 			ts_diff *= bbr->r_ctl.bbr_peer_tsratio;
6498 			if ((delivered == 0) ||
6499 			    (rtt < 1000)) {
6500 				/* Can't use the ts */
6501 				bbr_log_type_bbrupd(bbr, 61, cts,
6502 						    ts_diff,
6503 						    bbr->r_ctl.last_inbound_ts,
6504 						    rsm->r_del_ack_ts, 0,
6505 						    0, 0, 0, delivered);
6506 			} else {
6507 				ts_bw = (uint64_t)delivered;
6508 				ts_bw *= (uint64_t)USECS_IN_SECOND;
6509 				ts_bw /= ts_diff;
6510 				bbr_log_type_bbrupd(bbr, 62, cts,
6511 						    (ts_bw >> 32),
6512 						    (ts_bw & 0xffffffff), 0, 0,
6513 						    0, 0, ts_diff, delivered);
6514 				if ((bbr->ts_can_raise) &&
6515 				    (ts_bw > bw)) {
6516 					bbr_log_type_bbrupd(bbr, 8, cts,
6517 							    delivered,
6518 							    ts_diff,
6519 							    (bw >> 32),
6520 							    (bw & 0x00000000ffffffff),
6521 							    0, 0, 0, 0);
6522 					bw = ts_bw;
6523 				} else if (ts_bw && (ts_bw < bw)) {
6524 					bbr_log_type_bbrupd(bbr, 7, cts,
6525 							    delivered,
6526 							    ts_diff,
6527 							    (bw >> 32),
6528 							    (bw & 0x00000000ffffffff),
6529 							    0, 0, 0, 0);
6530 					bw = ts_bw;
6531 				}
6532 			}
6533 		}
6534 		if (rsm->r_first_sent_time &&
6535 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6536 			uint64_t sbw, sti;
6537 			/*
6538 			 * We use what was in flight at the time of our
6539 			 * send  and the size of this send to figure
6540 			 * out what we have been sending at (amount).
6541 			 * For the time we take from the time of
6542 			 * the send of the first send outstanding
6543 			 * until this send plus this sends pacing
6544 			 * time. This gives us a good calculation
6545 			 * as to the rate we have been sending at.
6546 			 */
6547 
6548 			sbw = (uint64_t)(rsm->r_flight_at_send);
6549 			sbw *= (uint64_t)USECS_IN_SECOND;
6550 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6551 			sti += rsm->r_pacing_delay;
6552 			sbw /= sti;
6553 			if (sbw < bw) {
6554 				bbr_log_type_bbrupd(bbr, 6, cts,
6555 						    delivered,
6556 						    (uint32_t)sti,
6557 						    (bw >> 32),
6558 						    (uint32_t)bw,
6559 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6560 						    (uint32_t)sbw);
6561 				bw = sbw;
6562 			}
6563 		}
6564 		/* Use the google algorithm for b/w measurements */
6565 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6566 		if ((rsm->r_app_limited == 0) ||
6567 		    (bw > get_filter_value(&bbr->r_ctl.rc_delrate))) {
6568 			tcp_bbr_commit_bw(bbr, cts);
6569 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6570 					    0, 0, 0, 0,  bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6571 		}
6572 	}
6573 }
6574 
6575 static void
6576 bbr_google_measurement(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts)
6577 {
6578 	if (bbr->rc_in_persist == 0) {
6579 		/* We log only when not in persist */
6580 		/* Translate to a Bytes Per Second */
6581 		uint64_t tim, bw;
6582 		uint32_t delivered;
6583 		int no_apply = 0;
6584 
6585 		if (TSTMP_GT(bbr->r_ctl.rc_del_time, rsm->r_del_time))
6586 			tim = (uint64_t)(bbr->r_ctl.rc_del_time - rsm->r_del_time);
6587 		else
6588 			tim = 1;
6589 		/*
6590 		 * Now that we have processed the tim (skipping the sample
6591 		 * or possibly updating the time, go ahead and
6592 		 * calculate the cdr.
6593 		 */
6594 		delivered = (bbr->r_ctl.rc_delivered - rsm->r_delivered);
6595 		bw = (uint64_t)delivered;
6596 		bw *= (uint64_t)USECS_IN_SECOND;
6597 		bw /= tim;
6598 		if (tim < bbr->r_ctl.rc_lowest_rtt) {
6599 			bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6600 					    tim, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6601 
6602 			no_apply = 1;
6603 		}
6604 		/*
6605 		 * If we are using this b/w shove it in now so we
6606 		 * can see in the trace viewer if it gets over-ridden.
6607 		 */
6608 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6609 		/* Gate by the sending rate */
6610 		if (rsm->r_first_sent_time &&
6611 		    TSTMP_GT(rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)],rsm->r_first_sent_time)) {
6612 			uint64_t sbw, sti;
6613 			/*
6614 			 * We use what was in flight at the time of our
6615 			 * send  and the size of this send to figure
6616 			 * out what we have been sending at (amount).
6617 			 * For the time we take from the time of
6618 			 * the send of the first send outstanding
6619 			 * until this send plus this sends pacing
6620 			 * time. This gives us a good calculation
6621 			 * as to the rate we have been sending at.
6622 			 */
6623 
6624 			sbw = (uint64_t)(rsm->r_flight_at_send);
6625 			sbw *= (uint64_t)USECS_IN_SECOND;
6626 			sti = rsm->r_tim_lastsent[(rsm->r_rtr_cnt -1)] - rsm->r_first_sent_time;
6627 			sti += rsm->r_pacing_delay;
6628 			sbw /= sti;
6629 			if (sbw < bw) {
6630 				bbr_log_type_bbrupd(bbr, 6, cts,
6631 						    delivered,
6632 						    (uint32_t)sti,
6633 						    (bw >> 32),
6634 						    (uint32_t)bw,
6635 						    rsm->r_first_sent_time, 0, (sbw >> 32),
6636 						    (uint32_t)sbw);
6637 				bw = sbw;
6638 			}
6639 			if ((sti > tim) &&
6640 			    (sti < bbr->r_ctl.rc_lowest_rtt)) {
6641 				bbr_log_type_bbrupd(bbr, 99, cts, (uint32_t)tim, delivered,
6642 						    (uint32_t)sti, bbr->r_ctl.rc_lowest_rtt, 0, 0, 0, 0);
6643 				no_apply = 1;
6644 			} else
6645 				no_apply = 0;
6646 		}
6647 		bbr->r_ctl.rc_bbr_cur_del_rate = bw;
6648 		if ((no_apply == 0) &&
6649 		    ((rsm->r_app_limited == 0) ||
6650 		     (bw > get_filter_value(&bbr->r_ctl.rc_delrate)))) {
6651 			tcp_bbr_commit_bw(bbr, cts);
6652 			bbr_log_type_bbrupd(bbr, 10, cts, (uint32_t)tim, delivered,
6653 					    0, 0, 0, 0, bbr->r_ctl.rc_del_time,  rsm->r_del_time);
6654 		}
6655 	}
6656 }
6657 
6658 static void
6659 bbr_update_bbr_info(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, uint32_t rtt, uint32_t cts, uint32_t tsin,
6660     uint32_t uts, int32_t match, uint32_t rsm_send_time, int32_t ack_type, struct tcpopt *to)
6661 {
6662 	uint64_t old_rttprop;
6663 
6664 	/* Update our delivery time and amount */
6665 	bbr->r_ctl.rc_delivered += (rsm->r_end - rsm->r_start);
6666 	bbr->r_ctl.rc_del_time = cts;
6667 	if (rtt == 0) {
6668 		/*
6669 		 * 0 means its a retransmit, for now we don't use these for
6670 		 * the rest of BBR.
6671 		 */
6672 		return;
6673 	}
6674 	if ((bbr->rc_use_google == 0) &&
6675 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6676 	    (match != BBR_RTT_BY_TIMESTAMP)){
6677 		/*
6678 		 * We get a lot of rtt updates, lets not pay attention to
6679 		 * any that are not an exact match. That way we don't have
6680 		 * to worry about timestamps and the whole nonsense of
6681 		 * unsure if its a retransmission etc (if we ever had the
6682 		 * timestamp fixed to always have the last thing sent this
6683 		 * would not be a issue).
6684 		 */
6685 		return;
6686 	}
6687 	if ((bbr_no_retran && bbr->rc_use_google) &&
6688 	    (match != BBR_RTT_BY_EXACTMATCH) &&
6689 	    (match != BBR_RTT_BY_TIMESTAMP)){
6690 		/*
6691 		 * We only do measurements in google mode
6692 		 * with bbr_no_retran on for sure things.
6693 		 */
6694 		return;
6695 	}
6696 	/* Only update srtt if we know by exact match */
6697 	tcp_bbr_xmit_timer(bbr, rtt, rsm_send_time, rsm->r_start, tsin);
6698 	if (ack_type == BBR_CUM_ACKED)
6699 		bbr->rc_ack_is_cumack = 1;
6700 	else
6701 		bbr->rc_ack_is_cumack = 0;
6702 	old_rttprop = bbr_get_rtt(bbr, BBR_RTT_PROP);
6703 	/*
6704 	 * Note the following code differs to the original
6705 	 * BBR spec. It calls for <= not <. However after a
6706 	 * long discussion in email with Neal, he acknowledged
6707 	 * that it should be < than so that we will have flows
6708 	 * going into probe-rtt (we were seeing cases where that
6709 	 * did not happen and caused ugly things to occur). We
6710 	 * have added this agreed upon fix to our code base.
6711 	 */
6712 	if (rtt < old_rttprop) {
6713 		/* Update when we last saw a rtt drop */
6714 		bbr_log_rtt_shrinks(bbr, cts, 0, rtt, __LINE__, BBR_RTTS_NEWRTT, 0);
6715 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
6716 	}
6717 	bbr_log_type_bbrrttprop(bbr, rtt, (rsm ? rsm->r_end : 0), uts, cts,
6718 	    match, rsm->r_start, rsm->r_flags);
6719 	apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
6720 	if (old_rttprop != bbr_get_rtt(bbr, BBR_RTT_PROP)) {
6721 		/*
6722 		 * The RTT-prop moved, reset the target (may be a
6723 		 * nop for some states).
6724 		 */
6725 		bbr_set_state_target(bbr, __LINE__);
6726 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)
6727 			bbr_log_rtt_shrinks(bbr, cts, 0, 0,
6728 					    __LINE__, BBR_RTTS_NEW_TARGET, 0);
6729 		else if (old_rttprop < bbr_get_rtt(bbr, BBR_RTT_PROP))
6730 			/* It went up */
6731 			bbr_check_probe_rtt_limits(bbr, cts);
6732 	}
6733 	if ((bbr->rc_use_google == 0) &&
6734 	    (match == BBR_RTT_BY_TIMESTAMP)) {
6735 		/*
6736 		 * We don't do b/w update with
6737 		 * these since they are not really
6738 		 * reliable.
6739 		 */
6740 		return;
6741 	}
6742 	if (bbr->r_ctl.r_app_limited_until &&
6743 	    (bbr->r_ctl.rc_delivered >= bbr->r_ctl.r_app_limited_until)) {
6744 		/* We are no longer app-limited */
6745 		bbr->r_ctl.r_app_limited_until = 0;
6746 	}
6747 	if (bbr->rc_use_google) {
6748 		bbr_google_measurement(bbr, rsm, rtt, cts);
6749 	} else {
6750 		bbr_nf_measurement(bbr, rsm, rtt, cts);
6751 	}
6752 }
6753 
6754 /*
6755  * Convert a timestamp that the main stack
6756  * uses (milliseconds) into one that bbr uses
6757  * (microseconds). Return that converted timestamp.
6758  */
6759 static uint32_t
6760 bbr_ts_convert(uint32_t cts) {
6761 	uint32_t sec, msec;
6762 
6763 	sec = cts / MS_IN_USEC;
6764 	msec = cts - (MS_IN_USEC * sec);
6765 	return ((sec * USECS_IN_SECOND) + (msec * MS_IN_USEC));
6766 }
6767 
6768 /*
6769  * Return 0 if we did not update the RTT time, return
6770  * 1 if we did.
6771  */
6772 static int
6773 bbr_update_rtt(struct tcpcb *tp, struct tcp_bbr *bbr,
6774     struct bbr_sendmap *rsm, struct tcpopt *to, uint32_t cts, int32_t ack_type, uint32_t th_ack)
6775 {
6776 	int32_t i;
6777 	uint32_t t, uts = 0;
6778 
6779 	if ((rsm->r_flags & BBR_ACKED) ||
6780 	    (rsm->r_flags & BBR_WAS_RENEGED) ||
6781 	    (rsm->r_flags & BBR_RXT_CLEARED)) {
6782 		/* Already done */
6783 		return (0);
6784 	}
6785 	if (rsm->r_rtt_not_allowed) {
6786 		/* Not allowed */
6787 		return (0);
6788 	}
6789 	if (rsm->r_rtr_cnt == 1) {
6790 		/*
6791 		 * Only one transmit. Hopefully the normal case.
6792 		 */
6793 		if (TSTMP_GT(cts, rsm->r_tim_lastsent[0]))
6794 			t = cts - rsm->r_tim_lastsent[0];
6795 		else
6796 			t = 1;
6797 		if ((int)t <= 0)
6798 			t = 1;
6799 		bbr->r_ctl.rc_last_rtt = t;
6800 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6801 				    BBR_RTT_BY_EXACTMATCH, rsm->r_tim_lastsent[0], ack_type, to);
6802 		return (1);
6803 	}
6804 	/* Convert to usecs */
6805 	if ((bbr_can_use_ts_for_rtt == 1) &&
6806 	    (bbr->rc_use_google == 1) &&
6807 	    (ack_type == BBR_CUM_ACKED) &&
6808 	    (to->to_flags & TOF_TS) &&
6809 	    (to->to_tsecr != 0)) {
6810 		t = tcp_tv_to_mssectick(&bbr->rc_tv) - to->to_tsecr;
6811 		if (t < 1)
6812 			t = 1;
6813 		t *= MS_IN_USEC;
6814 		bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, 0,
6815 				    BBR_RTT_BY_TIMESTAMP,
6816 				    rsm->r_tim_lastsent[(rsm->r_rtr_cnt-1)],
6817 				    ack_type, to);
6818 		return (1);
6819 	}
6820 	uts = bbr_ts_convert(to->to_tsecr);
6821 	if ((to->to_flags & TOF_TS) &&
6822 	    (to->to_tsecr != 0) &&
6823 	    (ack_type == BBR_CUM_ACKED) &&
6824 	    ((rsm->r_flags & BBR_OVERMAX) == 0)) {
6825 		/*
6826 		 * Now which timestamp does it match? In this block the ACK
6827 		 * may be coming from a previous transmission.
6828 		 */
6829 		uint32_t fudge;
6830 
6831 		fudge = BBR_TIMER_FUDGE;
6832 		for (i = 0; i < rsm->r_rtr_cnt; i++) {
6833 			if ((SEQ_GEQ(uts, (rsm->r_tim_lastsent[i] - fudge))) &&
6834 			    (SEQ_LEQ(uts, (rsm->r_tim_lastsent[i] + fudge)))) {
6835 				if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6836 					t = cts - rsm->r_tim_lastsent[i];
6837 				else
6838 					t = 1;
6839 				if ((int)t <= 0)
6840 					t = 1;
6841 				bbr->r_ctl.rc_last_rtt = t;
6842 				bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_TSMATCHING,
6843 						    rsm->r_tim_lastsent[i], ack_type, to);
6844 				if ((i + 1) < rsm->r_rtr_cnt) {
6845 					/* Likely */
6846 					return (0);
6847 				} else if (rsm->r_flags & BBR_TLP) {
6848 					bbr->rc_tlp_rtx_out = 0;
6849 				}
6850 				return (1);
6851 			}
6852 		}
6853 		/* Fall through if we can't find a matching timestamp */
6854 	}
6855 	/*
6856 	 * Ok its a SACK block that we retransmitted. or a windows
6857 	 * machine without timestamps. We can tell nothing from the
6858 	 * time-stamp since its not there or the time the peer last
6859 	 * received a segment that moved forward its cum-ack point.
6860 	 *
6861 	 * Lets look at the last retransmit and see what we can tell
6862 	 * (with BBR for space we only keep 2 note we have to keep
6863 	 * at least 2 so the map can not be condensed more).
6864 	 */
6865 	i = rsm->r_rtr_cnt - 1;
6866 	if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6867 		t = cts - rsm->r_tim_lastsent[i];
6868 	else
6869 		goto not_sure;
6870 	if (t < bbr->r_ctl.rc_lowest_rtt) {
6871 		/*
6872 		 * We retransmitted and the ack came back in less
6873 		 * than the smallest rtt we have observed in the
6874 		 * windowed rtt. We most likey did an improper
6875 		 * retransmit as outlined in 4.2 Step 3 point 2 in
6876 		 * the rack-draft.
6877 		 *
6878 		 * Use the prior transmission to update all the
6879 		 * information as long as there is only one prior
6880 		 * transmission.
6881 		 */
6882 		if ((rsm->r_flags & BBR_OVERMAX) == 0) {
6883 #ifdef BBR_INVARIANTS
6884 			if (rsm->r_rtr_cnt == 1)
6885 				panic("rsm:%p bbr:%p rsm has overmax and only 1 retranmit flags:%x?", rsm, bbr, rsm->r_flags);
6886 #endif
6887 			i = rsm->r_rtr_cnt - 2;
6888 			if (TSTMP_GT(cts, rsm->r_tim_lastsent[i]))
6889 				t = cts - rsm->r_tim_lastsent[i];
6890 			else
6891 				t = 1;
6892 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts, BBR_RTT_BY_EARLIER_RET,
6893 					    rsm->r_tim_lastsent[i], ack_type, to);
6894 			return (0);
6895 		} else {
6896 			/*
6897 			 * Too many prior transmissions, just
6898 			 * updated BBR delivered
6899 			 */
6900 not_sure:
6901 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6902 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6903 		}
6904 	} else {
6905 		/*
6906 		 * We retransmitted it and the retransmit did the
6907 		 * job.
6908 		 */
6909 		if (rsm->r_flags & BBR_TLP)
6910 			bbr->rc_tlp_rtx_out = 0;
6911 		if ((rsm->r_flags & BBR_OVERMAX) == 0)
6912 			bbr_update_bbr_info(bbr, rsm, t, cts, to->to_tsecr, uts,
6913 					    BBR_RTT_BY_THIS_RETRAN, 0, ack_type, to);
6914 		else
6915 			bbr_update_bbr_info(bbr, rsm, 0, cts, to->to_tsecr, uts,
6916 					    BBR_RTT_BY_SOME_RETRAN, 0, ack_type, to);
6917 		return (1);
6918 	}
6919 	return (0);
6920 }
6921 
6922 /*
6923  * Mark the SACK_PASSED flag on all entries prior to rsm send wise.
6924  */
6925 static void
6926 bbr_log_sack_passed(struct tcpcb *tp,
6927     struct tcp_bbr *bbr, struct bbr_sendmap *rsm)
6928 {
6929 	struct bbr_sendmap *nrsm;
6930 
6931 	nrsm = rsm;
6932 	TAILQ_FOREACH_REVERSE_FROM(nrsm, &bbr->r_ctl.rc_tmap,
6933 	    bbr_head, r_tnext) {
6934 		if (nrsm == rsm) {
6935 			/* Skip original segment he is acked */
6936 			continue;
6937 		}
6938 		if (nrsm->r_flags & BBR_ACKED) {
6939 			/* Skip ack'd segments */
6940 			continue;
6941 		}
6942 		if (nrsm->r_flags & BBR_SACK_PASSED) {
6943 			/*
6944 			 * We found one that is already marked
6945 			 * passed, we have been here before and
6946 			 * so all others below this are marked.
6947 			 */
6948 			break;
6949 		}
6950 		BBR_STAT_INC(bbr_sack_passed);
6951 		nrsm->r_flags |= BBR_SACK_PASSED;
6952 		if (((nrsm->r_flags & BBR_MARKED_LOST) == 0) &&
6953 		    bbr_is_lost(bbr, nrsm, bbr->r_ctl.rc_rcvtime)) {
6954 			bbr->r_ctl.rc_lost += nrsm->r_end - nrsm->r_start;
6955 			bbr->r_ctl.rc_lost_bytes += nrsm->r_end - nrsm->r_start;
6956 			nrsm->r_flags |= BBR_MARKED_LOST;
6957 		}
6958 		nrsm->r_flags &= ~BBR_WAS_SACKPASS;
6959 	}
6960 }
6961 
6962 /*
6963  * Returns the number of bytes that were
6964  * newly ack'd by sack blocks.
6965  */
6966 static uint32_t
6967 bbr_proc_sack_blk(struct tcpcb *tp, struct tcp_bbr *bbr, struct sackblk *sack,
6968     struct tcpopt *to, struct bbr_sendmap **prsm, uint32_t cts)
6969 {
6970 	int32_t times = 0;
6971 	uint32_t start, end, changed = 0;
6972 	struct bbr_sendmap *rsm, *nrsm;
6973 	int32_t used_ref = 1;
6974 	uint8_t went_back = 0, went_fwd = 0;
6975 
6976 	start = sack->start;
6977 	end = sack->end;
6978 	rsm = *prsm;
6979 	if (rsm == NULL)
6980 		used_ref = 0;
6981 
6982 	/* Do we locate the block behind where we last were? */
6983 	if (rsm && SEQ_LT(start, rsm->r_start)) {
6984 		went_back = 1;
6985 		TAILQ_FOREACH_REVERSE_FROM(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
6986 			if (SEQ_GEQ(start, rsm->r_start) &&
6987 			    SEQ_LT(start, rsm->r_end)) {
6988 				goto do_rest_ofb;
6989 			}
6990 		}
6991 	}
6992 start_at_beginning:
6993 	went_fwd = 1;
6994 	/*
6995 	 * Ok lets locate the block where this guy is fwd from rsm (if its
6996 	 * set)
6997 	 */
6998 	TAILQ_FOREACH_FROM(rsm, &bbr->r_ctl.rc_map, r_next) {
6999 		if (SEQ_GEQ(start, rsm->r_start) &&
7000 		    SEQ_LT(start, rsm->r_end)) {
7001 			break;
7002 		}
7003 	}
7004 do_rest_ofb:
7005 	if (rsm == NULL) {
7006 		/*
7007 		 * This happens when we get duplicate sack blocks with the
7008 		 * same end. For example SACK 4: 100 SACK 3: 100 The sort
7009 		 * will not change there location so we would just start at
7010 		 * the end of the first one and get lost.
7011 		 */
7012 		if (tp->t_flags & TF_SENTFIN) {
7013 			/*
7014 			 * Check to see if we have not logged the FIN that
7015 			 * went out.
7016 			 */
7017 			nrsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7018 			if (nrsm && (nrsm->r_end + 1) == tp->snd_max) {
7019 				/*
7020 				 * Ok we did not get the FIN logged.
7021 				 */
7022 				nrsm->r_end++;
7023 				rsm = nrsm;
7024 				goto do_rest_ofb;
7025 			}
7026 		}
7027 		if (times == 1) {
7028 #ifdef BBR_INVARIANTS
7029 			panic("tp:%p bbr:%p sack:%p to:%p prsm:%p",
7030 			    tp, bbr, sack, to, prsm);
7031 #else
7032 			goto out;
7033 #endif
7034 		}
7035 		times++;
7036 		BBR_STAT_INC(bbr_sack_proc_restart);
7037 		rsm = NULL;
7038 		goto start_at_beginning;
7039 	}
7040 	/* Ok we have an ACK for some piece of rsm */
7041 	if (rsm->r_start != start) {
7042 		/*
7043 		 * Need to split this in two pieces the before and after.
7044 		 */
7045 		if (bbr_sack_mergable(rsm, start, end))
7046 			nrsm = bbr_alloc_full_limit(bbr);
7047 		else
7048 			nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7049 		if (nrsm == NULL) {
7050 			/* We could not allocate ignore the sack */
7051 			struct sackblk blk;
7052 
7053 			blk.start = start;
7054 			blk.end = end;
7055 			sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7056 			goto out;
7057 		}
7058 		bbr_clone_rsm(bbr, nrsm, rsm, start);
7059 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7060 		if (rsm->r_in_tmap) {
7061 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7062 			nrsm->r_in_tmap = 1;
7063 		}
7064 		rsm->r_flags &= (~BBR_HAS_FIN);
7065 		rsm = nrsm;
7066 	}
7067 	if (SEQ_GEQ(end, rsm->r_end)) {
7068 		/*
7069 		 * The end of this block is either beyond this guy or right
7070 		 * at this guy.
7071 		 */
7072 		if ((rsm->r_flags & BBR_ACKED) == 0) {
7073 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7074 			changed += (rsm->r_end - rsm->r_start);
7075 			bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7076 			bbr_log_sack_passed(tp, bbr, rsm);
7077 			if (rsm->r_flags & BBR_MARKED_LOST) {
7078 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7079 			}
7080 			/* Is Reordering occuring? */
7081 			if (rsm->r_flags & BBR_SACK_PASSED) {
7082 				BBR_STAT_INC(bbr_reorder_seen);
7083 				bbr->r_ctl.rc_reorder_ts = cts;
7084 				if (rsm->r_flags & BBR_MARKED_LOST) {
7085 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7086 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7087 						/* LT sampling also needs adjustment */
7088 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7089 				}
7090 			}
7091 			rsm->r_flags |= BBR_ACKED;
7092 			rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7093 			if (rsm->r_in_tmap) {
7094 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7095 				rsm->r_in_tmap = 0;
7096 			}
7097 		}
7098 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7099 		if (end == rsm->r_end) {
7100 			/* This block only - done */
7101 			goto out;
7102 		}
7103 		/* There is more not coverend by this rsm move on */
7104 		start = rsm->r_end;
7105 		nrsm = TAILQ_NEXT(rsm, r_next);
7106 		rsm = nrsm;
7107 		times = 0;
7108 		goto do_rest_ofb;
7109 	}
7110 	if (rsm->r_flags & BBR_ACKED) {
7111 		/* Been here done that */
7112 		goto out;
7113 	}
7114 	/* Ok we need to split off this one at the tail */
7115 	if (bbr_sack_mergable(rsm, start, end))
7116 		nrsm = bbr_alloc_full_limit(bbr);
7117 	else
7118 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
7119 	if (nrsm == NULL) {
7120 		/* failed XXXrrs what can we do but loose the sack info? */
7121 		struct sackblk blk;
7122 
7123 		blk.start = start;
7124 		blk.end = end;
7125 		sack_filter_reject(&bbr->r_ctl.bbr_sf, &blk);
7126 		goto out;
7127 	}
7128 	/* Clone it */
7129 	bbr_clone_rsm(bbr, nrsm, rsm, end);
7130 	/* The sack block does not cover this guy fully */
7131 	rsm->r_flags &= (~BBR_HAS_FIN);
7132 	TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
7133 	if (rsm->r_in_tmap) {
7134 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
7135 		nrsm->r_in_tmap = 1;
7136 	}
7137 	nrsm->r_dupack = 0;
7138 	bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_SACKED, 0);
7139 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_SACKED);
7140 	changed += (rsm->r_end - rsm->r_start);
7141 	bbr->r_ctl.rc_sacked += (rsm->r_end - rsm->r_start);
7142 	bbr_log_sack_passed(tp, bbr, rsm);
7143 	/* Is Reordering occuring? */
7144 	if (rsm->r_flags & BBR_MARKED_LOST) {
7145 		bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7146 	}
7147 	if (rsm->r_flags & BBR_SACK_PASSED) {
7148 		BBR_STAT_INC(bbr_reorder_seen);
7149 		bbr->r_ctl.rc_reorder_ts = cts;
7150 		if (rsm->r_flags & BBR_MARKED_LOST) {
7151 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7152 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7153 				/* LT sampling also needs adjustment */
7154 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7155 		}
7156 	}
7157 	rsm->r_flags &= ~(BBR_TLP|BBR_WAS_RENEGED|BBR_RXT_CLEARED|BBR_MARKED_LOST);
7158 	rsm->r_flags |= BBR_ACKED;
7159 	if (rsm->r_in_tmap) {
7160 		TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7161 		rsm->r_in_tmap = 0;
7162 	}
7163 out:
7164 	if (rsm && (rsm->r_flags & BBR_ACKED)) {
7165 		/*
7166 		 * Now can we merge this newly acked
7167 		 * block with either the previous or
7168 		 * next block?
7169 		 */
7170 		nrsm = TAILQ_NEXT(rsm, r_next);
7171 		if (nrsm &&
7172 		    (nrsm->r_flags & BBR_ACKED)) {
7173 			/* yep this and next can be merged */
7174 			rsm = bbr_merge_rsm(bbr, rsm, nrsm);
7175 		}
7176 		/* Now what about the previous? */
7177 		nrsm = TAILQ_PREV(rsm, bbr_head, r_next);
7178 		if (nrsm &&
7179 		    (nrsm->r_flags & BBR_ACKED)) {
7180 			/* yep the previous and this can be merged */
7181 			rsm = bbr_merge_rsm(bbr, nrsm, rsm);
7182 		}
7183 	}
7184 	if (used_ref == 0) {
7185 		BBR_STAT_INC(bbr_sack_proc_all);
7186 	} else {
7187 		BBR_STAT_INC(bbr_sack_proc_short);
7188 	}
7189 	if (went_fwd && went_back) {
7190 		BBR_STAT_INC(bbr_sack_search_both);
7191 	} else if (went_fwd) {
7192 		BBR_STAT_INC(bbr_sack_search_fwd);
7193 	} else if (went_back) {
7194 		BBR_STAT_INC(bbr_sack_search_back);
7195 	}
7196 	/* Save off where the next seq is */
7197 	if (rsm)
7198 		bbr->r_ctl.rc_sacklast = TAILQ_NEXT(rsm, r_next);
7199 	else
7200 		bbr->r_ctl.rc_sacklast = NULL;
7201 	*prsm = rsm;
7202 	return (changed);
7203 }
7204 
7205 static void inline
7206 bbr_peer_reneges(struct tcp_bbr *bbr, struct bbr_sendmap *rsm, tcp_seq th_ack)
7207 {
7208 	struct bbr_sendmap *tmap;
7209 
7210 	BBR_STAT_INC(bbr_reneges_seen);
7211 	tmap = NULL;
7212 	while (rsm && (rsm->r_flags & BBR_ACKED)) {
7213 		/* Its no longer sacked, mark it so */
7214 		uint32_t oflags;
7215 		bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7216 #ifdef BBR_INVARIANTS
7217 		if (rsm->r_in_tmap) {
7218 			panic("bbr:%p rsm:%p flags:0x%x in tmap?",
7219 			    bbr, rsm, rsm->r_flags);
7220 		}
7221 #endif
7222 		oflags = rsm->r_flags;
7223 		if (rsm->r_flags & BBR_MARKED_LOST) {
7224 			bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7225 			bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7226 			if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7227 				/* LT sampling also needs adjustment */
7228 				bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7229 		}
7230 		rsm->r_flags &= ~(BBR_ACKED | BBR_SACK_PASSED | BBR_WAS_SACKPASS | BBR_MARKED_LOST);
7231 		rsm->r_flags |= BBR_WAS_RENEGED;
7232 		rsm->r_flags |= BBR_RXT_CLEARED;
7233 		bbr_log_type_rsmclear(bbr, bbr->r_ctl.rc_rcvtime, rsm, oflags, __LINE__);
7234 		/* Rebuild it into our tmap */
7235 		if (tmap == NULL) {
7236 			TAILQ_INSERT_HEAD(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7237 			tmap = rsm;
7238 		} else {
7239 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, tmap, rsm, r_tnext);
7240 			tmap = rsm;
7241 		}
7242 		tmap->r_in_tmap = 1;
7243 		/*
7244 		 * XXXrrs Delivered? Should we do anything here?
7245 		 *
7246 		 * Of course we don't on a rxt timeout so maybe its ok that
7247 		 * we don't?
7248 		 *
7249 		 * For now lets not.
7250 		 */
7251 		rsm = TAILQ_NEXT(rsm, r_next);
7252 	}
7253 	/*
7254 	 * Now lets possibly clear the sack filter so we start recognizing
7255 	 * sacks that cover this area.
7256 	 */
7257 	sack_filter_clear(&bbr->r_ctl.bbr_sf, th_ack);
7258 }
7259 
7260 static void
7261 bbr_log_syn(struct tcpcb *tp, struct tcpopt *to)
7262 {
7263 	struct tcp_bbr *bbr;
7264 	struct bbr_sendmap *rsm;
7265 	uint32_t cts;
7266 
7267 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7268 	cts = bbr->r_ctl.rc_rcvtime;
7269 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7270 	if (rsm && (rsm->r_flags & BBR_HAS_SYN)) {
7271 		if ((rsm->r_end - rsm->r_start) <= 1) {
7272 			/* Log out the SYN completely */
7273 			bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7274 			rsm->r_rtr_bytes = 0;
7275 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7276 			if (rsm->r_in_tmap) {
7277 				TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7278 				rsm->r_in_tmap = 0;
7279 			}
7280 			if (bbr->r_ctl.rc_next == rsm) {
7281 				/* scoot along the marker */
7282 				bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7283 			}
7284 			if (to != NULL)
7285 				bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, 0);
7286 			bbr_free(bbr, rsm);
7287 		} else {
7288 			/* There is more (Fast open)? strip out SYN. */
7289 			rsm->r_flags &= ~BBR_HAS_SYN;
7290 			rsm->r_start++;
7291 		}
7292 	}
7293 }
7294 
7295 /*
7296  * Returns the number of bytes that were
7297  * acknowledged by SACK blocks.
7298  */
7299 
7300 static uint32_t
7301 bbr_log_ack(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th,
7302     uint32_t *prev_acked)
7303 {
7304 	uint32_t changed, last_seq, entered_recovery = 0;
7305 	struct tcp_bbr *bbr;
7306 	struct bbr_sendmap *rsm;
7307 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1];
7308 	register uint32_t th_ack;
7309 	int32_t i, j, k, new_sb, num_sack_blks = 0;
7310 	uint32_t cts, acked, ack_point, sack_changed = 0;
7311 	uint32_t p_maxseg, maxseg, p_acked = 0;
7312 
7313 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7314 	if (tcp_get_flags(th) & TH_RST) {
7315 		/* We don't log resets */
7316 		return (0);
7317 	}
7318 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7319 	cts = bbr->r_ctl.rc_rcvtime;
7320 
7321 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7322 	changed = 0;
7323 	maxseg = tp->t_maxseg - bbr->rc_last_options;
7324 	p_maxseg = min(bbr->r_ctl.rc_pace_max_segs, maxseg);
7325 	th_ack = th->th_ack;
7326 	if (SEQ_GT(th_ack, tp->snd_una)) {
7327 		acked = th_ack - tp->snd_una;
7328 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_UPDATE, __LINE__);
7329 		bbr->rc_tp->t_acktime = ticks;
7330 	} else
7331 		acked = 0;
7332 	if (SEQ_LEQ(th_ack, tp->snd_una)) {
7333 		/* Only sent here for sack processing */
7334 		goto proc_sack;
7335 	}
7336 	if (rsm && SEQ_GT(th_ack, rsm->r_start)) {
7337 		changed = th_ack - rsm->r_start;
7338 	} else if ((rsm == NULL) && ((th_ack - 1) == tp->iss)) {
7339 		/*
7340 		 * For the SYN incoming case we will not have called
7341 		 * tcp_output for the sending of the SYN, so there will be
7342 		 * no map. All other cases should probably be a panic.
7343 		 */
7344 		if ((to->to_flags & TOF_TS) && (to->to_tsecr != 0)) {
7345 			/*
7346 			 * We have a timestamp that can be used to generate
7347 			 * an initial RTT.
7348 			 */
7349 			uint32_t ts, now, rtt;
7350 
7351 			ts = bbr_ts_convert(to->to_tsecr);
7352 			now = bbr_ts_convert(tcp_tv_to_mssectick(&bbr->rc_tv));
7353 			rtt = now - ts;
7354 			if (rtt < 1)
7355 				rtt = 1;
7356 			bbr_log_type_bbrrttprop(bbr, rtt,
7357 						tp->iss, 0, cts,
7358 						BBR_RTT_BY_TIMESTAMP, tp->iss, 0);
7359 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
7360 			changed = 1;
7361 			bbr->r_wanted_output = 1;
7362 			goto out;
7363 		}
7364 		goto proc_sack;
7365 	} else if (rsm == NULL) {
7366 		goto out;
7367 	}
7368 	if (changed) {
7369 		/*
7370 		 * The ACK point is advancing to th_ack, we must drop off
7371 		 * the packets in the rack log and calculate any eligble
7372 		 * RTT's.
7373 		 */
7374 		bbr->r_wanted_output = 1;
7375 more:
7376 		if (rsm == NULL) {
7377 			if (tp->t_flags & TF_SENTFIN) {
7378 				/* if we send a FIN we will not hav a map */
7379 				goto proc_sack;
7380 			}
7381 #ifdef BBR_INVARIANTS
7382 			panic("No rack map tp:%p for th:%p state:%d bbr:%p snd_una:%u snd_max:%u chg:%d\n",
7383 			    tp,
7384 			    th, tp->t_state, bbr,
7385 			    tp->snd_una, tp->snd_max, changed);
7386 #endif
7387 			goto proc_sack;
7388 		}
7389 	}
7390 	if (SEQ_LT(th_ack, rsm->r_start)) {
7391 		/* Huh map is missing this */
7392 #ifdef BBR_INVARIANTS
7393 		printf("Rack map starts at r_start:%u for th_ack:%u huh? ts:%d rs:%d bbr:%p\n",
7394 		    rsm->r_start,
7395 		    th_ack, tp->t_state,
7396 		    bbr->r_state, bbr);
7397 		panic("th-ack is bad bbr:%p tp:%p", bbr, tp);
7398 #endif
7399 		goto proc_sack;
7400 	} else if (th_ack == rsm->r_start) {
7401 		/* None here to ack */
7402 		goto proc_sack;
7403 	}
7404 	/*
7405 	 * Clear the dup ack counter, it will
7406 	 * either be freed or if there is some
7407 	 * remaining we need to start it at zero.
7408 	 */
7409 	rsm->r_dupack = 0;
7410 	/* Now do we consume the whole thing? */
7411 	if (SEQ_GEQ(th_ack, rsm->r_end)) {
7412 		/* Its all consumed. */
7413 		uint32_t left;
7414 
7415 		if (rsm->r_flags & BBR_ACKED) {
7416 			/*
7417 			 * It was acked on the scoreboard -- remove it from
7418 			 * total
7419 			 */
7420 			p_acked += (rsm->r_end - rsm->r_start);
7421 			bbr->r_ctl.rc_sacked -= (rsm->r_end - rsm->r_start);
7422 			if (bbr->r_ctl.rc_sacked == 0)
7423 				bbr->r_ctl.rc_sacklast = NULL;
7424 		} else {
7425 			bbr_update_rtt(tp, bbr, rsm, to, cts, BBR_CUM_ACKED, th_ack);
7426 			if (rsm->r_flags & BBR_MARKED_LOST) {
7427 				bbr->r_ctl.rc_lost_bytes -= rsm->r_end - rsm->r_start;
7428 			}
7429 			if (rsm->r_flags & BBR_SACK_PASSED) {
7430 				/*
7431 				 * There are acked segments ACKED on the
7432 				 * scoreboard further up. We are seeing
7433 				 * reordering.
7434 				 */
7435 				BBR_STAT_INC(bbr_reorder_seen);
7436 				bbr->r_ctl.rc_reorder_ts = cts;
7437 				if (rsm->r_flags & BBR_MARKED_LOST) {
7438 					bbr->r_ctl.rc_lost -= rsm->r_end - rsm->r_start;
7439 					if (SEQ_GT(bbr->r_ctl.rc_lt_lost, bbr->r_ctl.rc_lost))
7440 						/* LT sampling also needs adjustment */
7441 						bbr->r_ctl.rc_lt_lost = bbr->r_ctl.rc_lost;
7442 				}
7443 			}
7444 			rsm->r_flags &= ~BBR_MARKED_LOST;
7445 		}
7446 		bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7447 		rsm->r_rtr_bytes = 0;
7448 		TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
7449 		if (rsm->r_in_tmap) {
7450 			TAILQ_REMOVE(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
7451 			rsm->r_in_tmap = 0;
7452 		}
7453 		if (bbr->r_ctl.rc_next == rsm) {
7454 			/* scoot along the marker */
7455 			bbr->r_ctl.rc_next = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7456 		}
7457 		bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7458 		/* Adjust the packet counts */
7459 		left = th_ack - rsm->r_end;
7460 		/* Free back to zone */
7461 		bbr_free(bbr, rsm);
7462 		if (left) {
7463 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7464 			goto more;
7465 		}
7466 		goto proc_sack;
7467 	}
7468 	if (rsm->r_flags & BBR_ACKED) {
7469 		/*
7470 		 * It was acked on the scoreboard -- remove it from total
7471 		 * for the part being cum-acked.
7472 		 */
7473 		p_acked += (rsm->r_end - rsm->r_start);
7474 		bbr->r_ctl.rc_sacked -= (th_ack - rsm->r_start);
7475 		if (bbr->r_ctl.rc_sacked == 0)
7476 			bbr->r_ctl.rc_sacklast = NULL;
7477 	} else {
7478 		/*
7479 		 * It was acked up to th_ack point for the first time
7480 		 */
7481 		struct bbr_sendmap lrsm;
7482 
7483 		memcpy(&lrsm, rsm, sizeof(struct bbr_sendmap));
7484 		lrsm.r_end = th_ack;
7485 		bbr_update_rtt(tp, bbr, &lrsm, to, cts, BBR_CUM_ACKED, th_ack);
7486 	}
7487 	if ((rsm->r_flags & BBR_MARKED_LOST) &&
7488 	    ((rsm->r_flags & BBR_ACKED) == 0)) {
7489 		/*
7490 		 * It was marked lost and partly ack'd now
7491 		 * for the first time. We lower the rc_lost_bytes
7492 		 * and still leave it MARKED.
7493 		 */
7494 		bbr->r_ctl.rc_lost_bytes -= th_ack - rsm->r_start;
7495 	}
7496 	bbr_isit_a_pkt_epoch(bbr, cts, rsm, __LINE__, BBR_CUM_ACKED);
7497 	bbr->r_ctl.rc_holes_rxt -= rsm->r_rtr_bytes;
7498 	rsm->r_rtr_bytes = 0;
7499 	/* adjust packet count */
7500 	rsm->r_start = th_ack;
7501 proc_sack:
7502 	/* Check for reneging */
7503 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
7504 	if (rsm && (rsm->r_flags & BBR_ACKED) && (th_ack == rsm->r_start)) {
7505 		/*
7506 		 * The peer has moved snd_una up to the edge of this send,
7507 		 * i.e. one that it had previously acked. The only way that
7508 		 * can be true if the peer threw away data (space issues)
7509 		 * that it had previously sacked (else it would have given
7510 		 * us snd_una up to (rsm->r_end). We need to undo the acked
7511 		 * markings here.
7512 		 *
7513 		 * Note we have to look to make sure th_ack is our
7514 		 * rsm->r_start in case we get an old ack where th_ack is
7515 		 * behind snd_una.
7516 		 */
7517 		bbr_peer_reneges(bbr, rsm, th->th_ack);
7518 	}
7519 	if ((to->to_flags & TOF_SACK) == 0) {
7520 		/* We are done nothing left to log */
7521 		goto out;
7522 	}
7523 	rsm = TAILQ_LAST_FAST(&bbr->r_ctl.rc_map, bbr_sendmap, r_next);
7524 	if (rsm) {
7525 		last_seq = rsm->r_end;
7526 	} else {
7527 		last_seq = tp->snd_max;
7528 	}
7529 	/* Sack block processing */
7530 	if (SEQ_GT(th_ack, tp->snd_una))
7531 		ack_point = th_ack;
7532 	else
7533 		ack_point = tp->snd_una;
7534 	for (i = 0; i < to->to_nsacks; i++) {
7535 		bcopy((to->to_sacks + i * TCPOLEN_SACK),
7536 		    &sack, sizeof(sack));
7537 		sack.start = ntohl(sack.start);
7538 		sack.end = ntohl(sack.end);
7539 		if (SEQ_GT(sack.end, sack.start) &&
7540 		    SEQ_GT(sack.start, ack_point) &&
7541 		    SEQ_LT(sack.start, tp->snd_max) &&
7542 		    SEQ_GT(sack.end, ack_point) &&
7543 		    SEQ_LEQ(sack.end, tp->snd_max)) {
7544 			if ((bbr->r_ctl.rc_num_small_maps_alloced > bbr_sack_block_limit) &&
7545 			    (SEQ_LT(sack.end, last_seq)) &&
7546 			    ((sack.end - sack.start) < (p_maxseg / 8))) {
7547 				/*
7548 				 * Not the last piece and its smaller than
7549 				 * 1/8th of a p_maxseg. We ignore this.
7550 				 */
7551 				BBR_STAT_INC(bbr_runt_sacks);
7552 				continue;
7553 			}
7554 			sack_blocks[num_sack_blks] = sack;
7555 			num_sack_blks++;
7556 		} else if (SEQ_LEQ(sack.start, th_ack) &&
7557 		    SEQ_LEQ(sack.end, th_ack)) {
7558 			/*
7559 			 * Its a D-SACK block.
7560 			 */
7561 			tcp_record_dsack(tp, sack.start, sack.end, 0);
7562 		}
7563 	}
7564 	if (num_sack_blks == 0)
7565 		goto out;
7566 	/*
7567 	 * Sort the SACK blocks so we can update the rack scoreboard with
7568 	 * just one pass.
7569 	 */
7570 	new_sb = sack_filter_blks(tp, &bbr->r_ctl.bbr_sf, sack_blocks,
7571 				  num_sack_blks, th->th_ack);
7572 	ctf_log_sack_filter(bbr->rc_tp, new_sb, sack_blocks);
7573 	BBR_STAT_ADD(bbr_sack_blocks, num_sack_blks);
7574 	BBR_STAT_ADD(bbr_sack_blocks_skip, (num_sack_blks - new_sb));
7575 	num_sack_blks = new_sb;
7576 	if (num_sack_blks < 2) {
7577 		goto do_sack_work;
7578 	}
7579 	/* Sort the sacks */
7580 	for (i = 0; i < num_sack_blks; i++) {
7581 		for (j = i + 1; j < num_sack_blks; j++) {
7582 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
7583 				sack = sack_blocks[i];
7584 				sack_blocks[i] = sack_blocks[j];
7585 				sack_blocks[j] = sack;
7586 			}
7587 		}
7588 	}
7589 	/*
7590 	 * Now are any of the sack block ends the same (yes some
7591 	 * implememtations send these)?
7592 	 */
7593 again:
7594 	if (num_sack_blks > 1) {
7595 		for (i = 0; i < num_sack_blks; i++) {
7596 			for (j = i + 1; j < num_sack_blks; j++) {
7597 				if (sack_blocks[i].end == sack_blocks[j].end) {
7598 					/*
7599 					 * Ok these two have the same end we
7600 					 * want the smallest end and then
7601 					 * throw away the larger and start
7602 					 * again.
7603 					 */
7604 					if (SEQ_LT(sack_blocks[j].start, sack_blocks[i].start)) {
7605 						/*
7606 						 * The second block covers
7607 						 * more area use that
7608 						 */
7609 						sack_blocks[i].start = sack_blocks[j].start;
7610 					}
7611 					/*
7612 					 * Now collapse out the dup-sack and
7613 					 * lower the count
7614 					 */
7615 					for (k = (j + 1); k < num_sack_blks; k++) {
7616 						sack_blocks[j].start = sack_blocks[k].start;
7617 						sack_blocks[j].end = sack_blocks[k].end;
7618 						j++;
7619 					}
7620 					num_sack_blks--;
7621 					goto again;
7622 				}
7623 			}
7624 		}
7625 	}
7626 do_sack_work:
7627 	rsm = bbr->r_ctl.rc_sacklast;
7628 	for (i = 0; i < num_sack_blks; i++) {
7629 		acked = bbr_proc_sack_blk(tp, bbr, &sack_blocks[i], to, &rsm, cts);
7630 		if (acked) {
7631 			bbr->r_wanted_output = 1;
7632 			changed += acked;
7633 			sack_changed += acked;
7634 		}
7635 	}
7636 out:
7637 	*prev_acked = p_acked;
7638 	if ((sack_changed) && (!IN_RECOVERY(tp->t_flags))) {
7639 		/*
7640 		 * Ok we have a high probability that we need to go in to
7641 		 * recovery since we have data sack'd
7642 		 */
7643 		struct bbr_sendmap *rsm;
7644 
7645 		rsm = bbr_check_recovery_mode(tp, bbr, cts);
7646 		if (rsm) {
7647 			/* Enter recovery */
7648 			entered_recovery = 1;
7649 			bbr->r_wanted_output = 1;
7650 			/*
7651 			 * When we enter recovery we need to assure we send
7652 			 * one packet.
7653 			 */
7654 			if (bbr->r_ctl.rc_resend == NULL) {
7655 				bbr->r_ctl.rc_resend = rsm;
7656 			}
7657 		}
7658 	}
7659 	if (IN_RECOVERY(tp->t_flags) && (entered_recovery == 0)) {
7660 		/*
7661 		 * See if we need to rack-retransmit anything if so set it
7662 		 * up as the thing to resend assuming something else is not
7663 		 * already in that position.
7664 		 */
7665 		if (bbr->r_ctl.rc_resend == NULL) {
7666 			bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts);
7667 		}
7668 	}
7669 	/*
7670 	 * We return the amount that changed via sack, this is used by the
7671 	 * ack-received code to augment what was changed between th_ack <->
7672 	 * snd_una.
7673 	 */
7674 	return (sack_changed);
7675 }
7676 
7677 static void
7678 bbr_strike_dupack(struct tcp_bbr *bbr)
7679 {
7680 	struct bbr_sendmap *rsm;
7681 
7682 	rsm = TAILQ_FIRST(&bbr->r_ctl.rc_tmap);
7683 	if (rsm && (rsm->r_dupack < 0xff)) {
7684 		rsm->r_dupack++;
7685 		if (rsm->r_dupack >= DUP_ACK_THRESHOLD)
7686 			bbr->r_wanted_output = 1;
7687 	}
7688 }
7689 
7690 /*
7691  * Return value of 1, we do not need to call bbr_process_data().
7692  * return value of 0, bbr_process_data can be called.
7693  * For ret_val if its 0 the TCB is locked and valid, if its non-zero
7694  * its unlocked and probably unsafe to touch the TCB.
7695  */
7696 static int
7697 bbr_process_ack(struct mbuf *m, struct tcphdr *th, struct socket *so,
7698     struct tcpcb *tp, struct tcpopt *to,
7699     uint32_t tiwin, int32_t tlen,
7700     int32_t * ofia, int32_t thflags, int32_t * ret_val)
7701 {
7702 	int32_t ourfinisacked = 0;
7703 	int32_t acked_amount;
7704 	uint16_t nsegs;
7705 	int32_t acked;
7706 	uint32_t lost, sack_changed = 0;
7707 	struct mbuf *mfree;
7708 	struct tcp_bbr *bbr;
7709 	uint32_t prev_acked = 0;
7710 
7711 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
7712 	lost = bbr->r_ctl.rc_lost;
7713 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
7714 	if (SEQ_GT(th->th_ack, tp->snd_max)) {
7715 		ctf_do_dropafterack(m, tp, th, thflags, tlen, ret_val);
7716 		bbr->r_wanted_output = 1;
7717 		return (1);
7718 	}
7719 	if (SEQ_GEQ(th->th_ack, tp->snd_una) || to->to_nsacks) {
7720 		/* Process the ack */
7721 		if (bbr->rc_in_persist)
7722 			tp->t_rxtshift = 0;
7723 		if ((th->th_ack == tp->snd_una) && (tiwin == tp->snd_wnd))
7724 			bbr_strike_dupack(bbr);
7725 		sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
7726 	}
7727 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, (bbr->r_ctl.rc_lost > lost));
7728 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
7729 		/*
7730 		 * Old ack, behind the last one rcv'd or a duplicate ack
7731 		 * with SACK info.
7732 		 */
7733 		if (th->th_ack == tp->snd_una) {
7734 			bbr_ack_received(tp, bbr, th, 0, sack_changed, prev_acked, __LINE__, 0);
7735 			if (bbr->r_state == TCPS_SYN_SENT) {
7736 				/*
7737 				 * Special case on where we sent SYN. When
7738 				 * the SYN-ACK is processed in syn_sent
7739 				 * state it bumps the snd_una. This causes
7740 				 * us to hit here even though we did ack 1
7741 				 * byte.
7742 				 *
7743 				 * Go through the nothing left case so we
7744 				 * send data.
7745 				 */
7746 				goto nothing_left;
7747 			}
7748 		}
7749 		return (0);
7750 	}
7751 	/*
7752 	 * If we reach this point, ACK is not a duplicate, i.e., it ACKs
7753 	 * something we sent.
7754 	 */
7755 	if (tp->t_flags & TF_NEEDSYN) {
7756 		/*
7757 		 * T/TCP: Connection was half-synchronized, and our SYN has
7758 		 * been ACK'd (so connection is now fully synchronized).  Go
7759 		 * to non-starred state, increment snd_una for ACK of SYN,
7760 		 * and check if we can do window scaling.
7761 		 */
7762 		tp->t_flags &= ~TF_NEEDSYN;
7763 		tp->snd_una++;
7764 		/* Do window scaling? */
7765 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
7766 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
7767 			tp->rcv_scale = tp->request_r_scale;
7768 			/* Send window already scaled. */
7769 		}
7770 	}
7771 	INP_WLOCK_ASSERT(tptoinpcb(tp));
7772 
7773 	acked = BYTES_THIS_ACK(tp, th);
7774 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
7775 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
7776 
7777 	/*
7778 	 * If we just performed our first retransmit, and the ACK arrives
7779 	 * within our recovery window, then it was a mistake to do the
7780 	 * retransmit in the first place.  Recover our original cwnd and
7781 	 * ssthresh, and proceed to transmit where we left off.
7782 	 */
7783 	if (tp->t_flags & TF_PREVVALID) {
7784 		tp->t_flags &= ~TF_PREVVALID;
7785 		if (tp->t_rxtshift == 1 &&
7786 		    (int)(ticks - tp->t_badrxtwin) < 0)
7787 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
7788 	}
7789 	SOCKBUF_LOCK(&so->so_snd);
7790 	acked_amount = min(acked, (int)sbavail(&so->so_snd));
7791 	tp->snd_wnd -= acked_amount;
7792 	mfree = sbcut_locked(&so->so_snd, acked_amount);
7793 	/* NB: sowwakeup_locked() does an implicit unlock. */
7794 	sowwakeup_locked(so);
7795 	m_freem(mfree);
7796 	if (SEQ_GT(th->th_ack, tp->snd_una)) {
7797 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
7798 	}
7799 	tp->snd_una = th->th_ack;
7800 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, (bbr->r_ctl.rc_lost - lost));
7801 	if (IN_RECOVERY(tp->t_flags)) {
7802 		if (SEQ_LT(th->th_ack, tp->snd_recover) &&
7803 		    (SEQ_LT(th->th_ack, tp->snd_max))) {
7804 			tcp_bbr_partialack(tp);
7805 		} else {
7806 			bbr_post_recovery(tp);
7807 		}
7808 	}
7809 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
7810 		tp->snd_recover = tp->snd_una;
7811 	}
7812 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
7813 		tp->snd_nxt = tp->snd_max;
7814 	}
7815 	if (tp->snd_una == tp->snd_max) {
7816 		/* Nothing left outstanding */
7817 nothing_left:
7818 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
7819 		if (sbavail(&so->so_snd) == 0)
7820 			bbr->rc_tp->t_acktime = 0;
7821 		if ((sbused(&so->so_snd) == 0) &&
7822 		    (tp->t_flags & TF_SENTFIN)) {
7823 			ourfinisacked = 1;
7824 		}
7825 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
7826 		if (bbr->rc_in_persist == 0) {
7827 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
7828 		}
7829 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
7830 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
7831 		/*
7832 		 * We invalidate the last ack here since we
7833 		 * don't want to transfer forward the time
7834 		 * for our sum's calculations.
7835 		 */
7836 		if ((tp->t_state >= TCPS_FIN_WAIT_1) &&
7837 		    (sbavail(&so->so_snd) == 0) &&
7838 		    (tp->t_flags2 & TF2_DROP_AF_DATA)) {
7839 			/*
7840 			 * The socket was gone and the peer sent data, time
7841 			 * to reset him.
7842 			 */
7843 			*ret_val = 1;
7844 			tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
7845 			/* tcp_close will kill the inp pre-log the Reset */
7846 			tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
7847 			tp = tcp_close(tp);
7848 			ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, tlen);
7849 			BBR_STAT_INC(bbr_dropped_af_data);
7850 			return (1);
7851 		}
7852 		/* Set need output so persist might get set */
7853 		bbr->r_wanted_output = 1;
7854 	}
7855 	if (ofia)
7856 		*ofia = ourfinisacked;
7857 	return (0);
7858 }
7859 
7860 static void
7861 bbr_enter_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7862 {
7863 	if (bbr->rc_in_persist == 0) {
7864 		bbr_timer_cancel(bbr, __LINE__, cts);
7865 		bbr->r_ctl.rc_last_delay_val = 0;
7866 		tp->t_rxtshift = 0;
7867 		bbr->rc_in_persist = 1;
7868 		bbr->r_ctl.rc_went_idle_time = cts;
7869 		/* We should be capped when rw went to 0 but just in case */
7870 		bbr_log_type_pesist(bbr, cts, 0, line, 1);
7871 		/* Time freezes for the state, so do the accounting now */
7872 		if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
7873 			uint32_t time_in;
7874 
7875 			time_in = cts - bbr->r_ctl.rc_bbr_state_time;
7876 			if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7877 				int32_t idx;
7878 
7879 				idx = bbr_state_val(bbr);
7880 				counter_u64_add(bbr_state_time[(idx + 5)], time_in);
7881 			} else {
7882 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
7883 			}
7884 		}
7885 		bbr->r_ctl.rc_bbr_state_time = cts;
7886 	}
7887 }
7888 
7889 static void
7890 bbr_restart_after_idle(struct tcp_bbr *bbr, uint32_t cts, uint32_t idle_time)
7891 {
7892 	/*
7893 	 * Note that if idle time does not exceed our
7894 	 * threshold, we do nothing continuing the state
7895 	 * transitions we were last walking through.
7896 	 */
7897 	if (idle_time >= bbr_idle_restart_threshold) {
7898 		if (bbr->rc_use_idle_restart) {
7899 			bbr->rc_bbr_state = BBR_STATE_IDLE_EXIT;
7900 			/*
7901 			 * Set our target using BBR_UNIT, so
7902 			 * we increase at a dramatic rate but
7903 			 * we stop when we get the pipe
7904 			 * full again for our current b/w estimate.
7905 			 */
7906 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
7907 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
7908 			bbr_set_state_target(bbr, __LINE__);
7909 			/* Now setup our gains to ramp up */
7910 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
7911 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
7912 			bbr_log_type_statechange(bbr, cts, __LINE__);
7913 		} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
7914 			bbr_substate_change(bbr, cts, __LINE__, 1);
7915 		}
7916 	}
7917 }
7918 
7919 static void
7920 bbr_exit_persist(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts, int32_t line)
7921 {
7922 	uint32_t idle_time;
7923 
7924 	if (bbr->rc_in_persist == 0)
7925 		return;
7926 	idle_time = bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time);
7927 	bbr->rc_in_persist = 0;
7928 	bbr->rc_hit_state_1 = 0;
7929 	bbr->r_ctl.rc_del_time = cts;
7930 	/*
7931 	 * We invalidate the last ack here since we
7932 	 * don't want to transfer forward the time
7933 	 * for our sum's calculations.
7934 	 */
7935 	if (tcp_in_hpts(bbr->rc_tp)) {
7936 		tcp_hpts_remove(bbr->rc_tp);
7937 		bbr->rc_timer_first = 0;
7938 		bbr->r_ctl.rc_hpts_flags = 0;
7939 		bbr->r_ctl.rc_last_delay_val = 0;
7940 		bbr->r_ctl.rc_hptsi_agg_delay = 0;
7941 		bbr->r_agg_early_set = 0;
7942 		bbr->r_ctl.rc_agg_early = 0;
7943 	}
7944 	bbr_log_type_pesist(bbr, cts, idle_time, line, 0);
7945 	if (idle_time >= bbr_rtt_probe_time) {
7946 		/*
7947 		 * This qualifies as a RTT_PROBE session since we drop the
7948 		 * data outstanding to nothing and waited more than
7949 		 * bbr_rtt_probe_time.
7950 		 */
7951 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_PERSIST, 0);
7952 		bbr->r_ctl.last_in_probertt = bbr->r_ctl.rc_rtt_shrinks = cts;
7953 	}
7954 	tp->t_rxtshift = 0;
7955 	/*
7956 	 * If in probeBW and we have persisted more than an RTT lets do
7957 	 * special handling.
7958 	 */
7959 	/* Force a time based epoch */
7960 	bbr_set_epoch(bbr, cts, __LINE__);
7961 	/*
7962 	 * Setup the lost so we don't count anything against the guy
7963 	 * we have been stuck with during persists.
7964 	 */
7965 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
7966 	/* Time un-freezes for the state */
7967 	bbr->r_ctl.rc_bbr_state_time = cts;
7968 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) ||
7969 	    (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT)) {
7970 		/*
7971 		 * If we are going back to probe-bw
7972 		 * or probe_rtt, we may need to possibly
7973 		 * do a fast restart.
7974 		 */
7975 		bbr_restart_after_idle(bbr, cts, idle_time);
7976 	}
7977 }
7978 
7979 static void
7980 bbr_collapsed_window(struct tcp_bbr *bbr)
7981 {
7982 	/*
7983 	 * Now we must walk the
7984 	 * send map and divide the
7985 	 * ones left stranded. These
7986 	 * guys can't cause us to abort
7987 	 * the connection and are really
7988 	 * "unsent". However if a buggy
7989 	 * client actually did keep some
7990 	 * of the data i.e. collapsed the win
7991 	 * and refused to ack and then opened
7992 	 * the win and acked that data. We would
7993 	 * get into an ack war, the simplier
7994 	 * method then of just pretending we
7995 	 * did not send those segments something
7996 	 * won't work.
7997 	 */
7998 	struct bbr_sendmap *rsm, *nrsm;
7999 	tcp_seq max_seq;
8000 	uint32_t maxseg;
8001 	int can_split = 0;
8002 	int fnd = 0;
8003 
8004 	maxseg = bbr->rc_tp->t_maxseg - bbr->rc_last_options;
8005 	max_seq = bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd;
8006 	bbr_log_type_rwnd_collapse(bbr, max_seq, 1, 0);
8007 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
8008 		/* Find the first seq past or at maxseq */
8009 		if (rsm->r_flags & BBR_RWND_COLLAPSED)
8010 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8011 		if (SEQ_GEQ(max_seq, rsm->r_start) &&
8012 		    SEQ_GEQ(rsm->r_end, max_seq)) {
8013 			fnd = 1;
8014 			break;
8015 		}
8016 	}
8017 	bbr->rc_has_collapsed = 0;
8018 	if (!fnd) {
8019 		/* Nothing to do strange */
8020 		return;
8021 	}
8022 	/*
8023 	 * Now can we split?
8024 	 *
8025 	 * We don't want to split if splitting
8026 	 * would generate too many small segments
8027 	 * less we let an attacker fragment our
8028 	 * send_map and leave us out of memory.
8029 	 */
8030 	if ((max_seq != rsm->r_start) &&
8031 	    (max_seq != rsm->r_end)){
8032 		/* can we split? */
8033 		int res1, res2;
8034 
8035 		res1 = max_seq - rsm->r_start;
8036 		res2 = rsm->r_end - max_seq;
8037 		if ((res1 >= (maxseg/8)) &&
8038 		    (res2 >= (maxseg/8))) {
8039 			/* No small pieces here */
8040 			can_split = 1;
8041 		} else if (bbr->r_ctl.rc_num_small_maps_alloced < bbr_sack_block_limit) {
8042 			/* We are under the limit */
8043 			can_split = 1;
8044 		}
8045 	}
8046 	/* Ok do we need to split this rsm? */
8047 	if (max_seq == rsm->r_start) {
8048 		/* It's this guy no split required */
8049 		nrsm = rsm;
8050 	} else if (max_seq == rsm->r_end) {
8051 		/* It's the next one no split required. */
8052 		nrsm = TAILQ_NEXT(rsm, r_next);
8053 		if (nrsm == NULL) {
8054 			/* Huh? */
8055 			return;
8056 		}
8057 	} else if (can_split && SEQ_LT(max_seq, rsm->r_end)) {
8058 		/* yep we need to split it */
8059 		nrsm = bbr_alloc_limit(bbr, BBR_LIMIT_TYPE_SPLIT);
8060 		if (nrsm == NULL) {
8061 			/* failed XXXrrs what can we do mark the whole? */
8062 			nrsm = rsm;
8063 			goto no_split;
8064 		}
8065 		/* Clone it */
8066 		bbr_log_type_rwnd_collapse(bbr, max_seq, 3, 0);
8067 		bbr_clone_rsm(bbr, nrsm, rsm, max_seq);
8068 		TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_map, rsm, nrsm, r_next);
8069 		if (rsm->r_in_tmap) {
8070 			TAILQ_INSERT_AFTER(&bbr->r_ctl.rc_tmap, rsm, nrsm, r_tnext);
8071 			nrsm->r_in_tmap = 1;
8072 		}
8073 	} else {
8074 		/*
8075 		 * Split not allowed just start here just
8076 		 * use this guy.
8077 		 */
8078 		nrsm = rsm;
8079 	}
8080 no_split:
8081 	BBR_STAT_INC(bbr_collapsed_win);
8082 	/* reuse fnd as a count */
8083 	fnd = 0;
8084 	TAILQ_FOREACH_FROM(nrsm, &bbr->r_ctl.rc_map, r_next) {
8085 		nrsm->r_flags |= BBR_RWND_COLLAPSED;
8086 		fnd++;
8087 		bbr->rc_has_collapsed = 1;
8088 	}
8089 	bbr_log_type_rwnd_collapse(bbr, max_seq, 4, fnd);
8090 }
8091 
8092 static void
8093 bbr_un_collapse_window(struct tcp_bbr *bbr)
8094 {
8095 	struct bbr_sendmap *rsm;
8096 	int cleared = 0;
8097 
8098 	TAILQ_FOREACH_REVERSE(rsm, &bbr->r_ctl.rc_map, bbr_head, r_next) {
8099 		if (rsm->r_flags & BBR_RWND_COLLAPSED) {
8100 			/* Clear the flag */
8101 			rsm->r_flags &= ~BBR_RWND_COLLAPSED;
8102 			cleared++;
8103 		} else
8104 			break;
8105 	}
8106 	bbr_log_type_rwnd_collapse(bbr,
8107 				   (bbr->rc_tp->snd_una + bbr->rc_tp->snd_wnd), 0, cleared);
8108 	bbr->rc_has_collapsed = 0;
8109 }
8110 
8111 /*
8112  * Return value of 1, the TCB is unlocked and most
8113  * likely gone, return value of 0, the TCB is still
8114  * locked.
8115  */
8116 static int
8117 bbr_process_data(struct mbuf *m, struct tcphdr *th, struct socket *so,
8118     struct tcpcb *tp, int32_t drop_hdrlen, int32_t tlen,
8119     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt)
8120 {
8121 	/*
8122 	 * Update window information. Don't look at window if no ACK: TAC's
8123 	 * send garbage on first SYN.
8124 	 */
8125 	uint16_t nsegs;
8126 	int32_t tfo_syn;
8127 	struct tcp_bbr *bbr;
8128 
8129 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8130 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8131 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8132 	if ((thflags & TH_ACK) &&
8133 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
8134 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
8135 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
8136 		/* keep track of pure window updates */
8137 		if (tlen == 0 &&
8138 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
8139 			KMOD_TCPSTAT_INC(tcps_rcvwinupd);
8140 		tp->snd_wnd = tiwin;
8141 		tp->snd_wl1 = th->th_seq;
8142 		tp->snd_wl2 = th->th_ack;
8143 		if (tp->snd_wnd > tp->max_sndwnd)
8144 			tp->max_sndwnd = tp->snd_wnd;
8145 		bbr->r_wanted_output = 1;
8146 	} else if (thflags & TH_ACK) {
8147 		if ((tp->snd_wl2 == th->th_ack) && (tiwin < tp->snd_wnd)) {
8148 			tp->snd_wnd = tiwin;
8149 			tp->snd_wl1 = th->th_seq;
8150 			tp->snd_wl2 = th->th_ack;
8151 		}
8152 	}
8153 	if (tp->snd_wnd < ctf_outstanding(tp))
8154 		/* The peer collapsed its window on us */
8155 		bbr_collapsed_window(bbr);
8156  	else if (bbr->rc_has_collapsed)
8157 		bbr_un_collapse_window(bbr);
8158 	/* Was persist timer active and now we have window space? */
8159 	if ((bbr->rc_in_persist != 0) &&
8160 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8161 				bbr_minseg(bbr)))) {
8162 		/*
8163 		 * Make the rate persist at end of persist mode if idle long
8164 		 * enough
8165 		 */
8166 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8167 
8168 		/* Make sure we output to start the timer */
8169 		bbr->r_wanted_output = 1;
8170 	}
8171 	/* Do we need to enter persist? */
8172 	if ((bbr->rc_in_persist == 0) &&
8173 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8174 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8175 	    (tp->snd_max == tp->snd_una) &&
8176 	    sbavail(&so->so_snd) &&
8177 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8178 		/* No send window.. we must enter persist */
8179 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8180 	}
8181 	if (tp->t_flags2 & TF2_DROP_AF_DATA) {
8182 		m_freem(m);
8183 		return (0);
8184 	}
8185 	/*
8186 	 * We don't support urgent data but
8187 	 * drag along the up just to make sure
8188 	 * if there is a stack switch no one
8189 	 * is surprised.
8190 	 */
8191 	tp->rcv_up = tp->rcv_nxt;
8192 
8193 	/*
8194 	 * Process the segment text, merging it into the TCP sequencing
8195 	 * queue, and arranging for acknowledgment of receipt if necessary.
8196 	 * This process logically involves adjusting tp->rcv_wnd as data is
8197 	 * presented to the user (this happens in tcp_usrreq.c, case
8198 	 * PRU_RCVD).  If a FIN has already been received on this connection
8199 	 * then we just ignore the text.
8200 	 */
8201 	tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
8202 	    (tp->t_flags & TF_FASTOPEN));
8203 	if ((tlen || (thflags & TH_FIN) || (tfo_syn && tlen > 0)) &&
8204 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8205 		tcp_seq save_start = th->th_seq;
8206 		tcp_seq save_rnxt  = tp->rcv_nxt;
8207 		int     save_tlen  = tlen;
8208 
8209 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8210 		/*
8211 		 * Insert segment which includes th into TCP reassembly
8212 		 * queue with control block tp.  Set thflags to whether
8213 		 * reassembly now includes a segment with FIN.  This handles
8214 		 * the common case inline (segment is the next to be
8215 		 * received on an established connection, and the queue is
8216 		 * empty), avoiding linkage into and removal from the queue
8217 		 * and repetition of various conversions. Set DELACK for
8218 		 * segments received in order, but ack immediately when
8219 		 * segments are out of order (so fast retransmit can work).
8220 		 */
8221 		if (th->th_seq == tp->rcv_nxt &&
8222 		    SEGQ_EMPTY(tp) &&
8223 		    (TCPS_HAVEESTABLISHED(tp->t_state) ||
8224 		    tfo_syn)) {
8225 #ifdef NETFLIX_SB_LIMITS
8226 			u_int mcnt, appended;
8227 
8228 			if (so->so_rcv.sb_shlim) {
8229 				mcnt = m_memcnt(m);
8230 				appended = 0;
8231 				if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8232 				    CFO_NOSLEEP, NULL) == false) {
8233 					counter_u64_add(tcp_sb_shlim_fails, 1);
8234 					m_freem(m);
8235 					return (0);
8236 				}
8237 			}
8238 
8239 #endif
8240 			if (DELAY_ACK(tp, bbr, nsegs) || tfo_syn) {
8241 				bbr->bbr_segs_rcvd += max(1, nsegs);
8242 				tp->t_flags |= TF_DELACK;
8243 				bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8244 			} else {
8245 				bbr->r_wanted_output = 1;
8246 				tp->t_flags |= TF_ACKNOW;
8247 			}
8248 			tp->rcv_nxt += tlen;
8249 			if (tlen &&
8250 			    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8251 			    (tp->t_fbyte_in == 0)) {
8252 				tp->t_fbyte_in = ticks;
8253 				if (tp->t_fbyte_in == 0)
8254 					tp->t_fbyte_in = 1;
8255 				if (tp->t_fbyte_out && tp->t_fbyte_in)
8256 					tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8257 			}
8258 			thflags = tcp_get_flags(th) & TH_FIN;
8259 			KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8260 			KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8261 			SOCKBUF_LOCK(&so->so_rcv);
8262 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
8263 				m_freem(m);
8264 			else
8265 #ifdef NETFLIX_SB_LIMITS
8266 				appended =
8267 #endif
8268 					sbappendstream_locked(&so->so_rcv, m, 0);
8269 			/* NB: sorwakeup_locked() does an implicit unlock. */
8270 			sorwakeup_locked(so);
8271 #ifdef NETFLIX_SB_LIMITS
8272 			if (so->so_rcv.sb_shlim && appended != mcnt)
8273 				counter_fo_release(so->so_rcv.sb_shlim,
8274 				    mcnt - appended);
8275 #endif
8276 
8277 		} else {
8278 			/*
8279 			 * XXX: Due to the header drop above "th" is
8280 			 * theoretically invalid by now.  Fortunately
8281 			 * m_adj() doesn't actually frees any mbufs when
8282 			 * trimming from the head.
8283 			 */
8284 			tcp_seq temp = save_start;
8285 
8286 			thflags = tcp_reass(tp, th, &temp, &tlen, m);
8287 			tp->t_flags |= TF_ACKNOW;
8288 			if (tp->t_flags & TF_WAKESOR) {
8289 				tp->t_flags &= ~TF_WAKESOR;
8290 				/* NB: sorwakeup_locked() does an implicit unlock. */
8291 				sorwakeup_locked(so);
8292 			}
8293 		}
8294 		if ((tp->t_flags & TF_SACK_PERMIT) &&
8295 		    (save_tlen > 0) &&
8296 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
8297 			if ((tlen == 0) && (SEQ_LT(save_start, save_rnxt))) {
8298 				/*
8299 				 * DSACK actually handled in the fastpath
8300 				 * above.
8301 				 */
8302 				tcp_update_sack_list(tp, save_start,
8303 				    save_start + save_tlen);
8304 			} else if ((tlen > 0) && SEQ_GT(tp->rcv_nxt, save_rnxt)) {
8305 				if ((tp->rcv_numsacks >= 1) &&
8306 				    (tp->sackblks[0].end == save_start)) {
8307 					/*
8308 					 * Partial overlap, recorded at todrop
8309 					 * above.
8310 					 */
8311 					tcp_update_sack_list(tp,
8312 					    tp->sackblks[0].start,
8313 					    tp->sackblks[0].end);
8314 				} else {
8315 					tcp_update_dsack_list(tp, save_start,
8316 					    save_start + save_tlen);
8317 				}
8318 			} else if (tlen >= save_tlen) {
8319 				/* Update of sackblks. */
8320 				tcp_update_dsack_list(tp, save_start,
8321 				    save_start + save_tlen);
8322 			} else if (tlen > 0) {
8323 				tcp_update_dsack_list(tp, save_start,
8324 				    save_start + tlen);
8325 			}
8326 		}
8327 	} else {
8328 		m_freem(m);
8329 		thflags &= ~TH_FIN;
8330 	}
8331 
8332 	/*
8333 	 * If FIN is received ACK the FIN and let the user know that the
8334 	 * connection is closing.
8335 	 */
8336 	if (thflags & TH_FIN) {
8337 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
8338 			/* The socket upcall is handled by socantrcvmore. */
8339 			socantrcvmore(so);
8340 			/*
8341 			 * If connection is half-synchronized (ie NEEDSYN
8342 			 * flag on) then delay ACK, so it may be piggybacked
8343 			 * when SYN is sent. Otherwise, since we received a
8344 			 * FIN then no more input can be expected, send ACK
8345 			 * now.
8346 			 */
8347 			if (tp->t_flags & TF_NEEDSYN) {
8348 				tp->t_flags |= TF_DELACK;
8349 				bbr_timer_cancel(bbr,
8350 				    __LINE__, bbr->r_ctl.rc_rcvtime);
8351 			} else {
8352 				tp->t_flags |= TF_ACKNOW;
8353 			}
8354 			tp->rcv_nxt++;
8355 		}
8356 		switch (tp->t_state) {
8357 			/*
8358 			 * In SYN_RECEIVED and ESTABLISHED STATES enter the
8359 			 * CLOSE_WAIT state.
8360 			 */
8361 		case TCPS_SYN_RECEIVED:
8362 			tp->t_starttime = ticks;
8363 			/* FALLTHROUGH */
8364 		case TCPS_ESTABLISHED:
8365 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
8366 			break;
8367 
8368 			/*
8369 			 * If still in FIN_WAIT_1 STATE FIN has not been
8370 			 * acked so enter the CLOSING state.
8371 			 */
8372 		case TCPS_FIN_WAIT_1:
8373 			tcp_state_change(tp, TCPS_CLOSING);
8374 			break;
8375 
8376 			/*
8377 			 * In FIN_WAIT_2 state enter the TIME_WAIT state,
8378 			 * starting the time-wait timer, turning off the
8379 			 * other standard timers.
8380 			 */
8381 		case TCPS_FIN_WAIT_2:
8382 			bbr->rc_timer_first = 1;
8383 			bbr_timer_cancel(bbr,
8384 			    __LINE__, bbr->r_ctl.rc_rcvtime);
8385 			tcp_twstart(tp);
8386 			return (1);
8387 		}
8388 	}
8389 	/*
8390 	 * Return any desired output.
8391 	 */
8392 	if ((tp->t_flags & TF_ACKNOW) ||
8393 	    (sbavail(&so->so_snd) > ctf_outstanding(tp))) {
8394 		bbr->r_wanted_output = 1;
8395 	}
8396 	return (0);
8397 }
8398 
8399 /*
8400  * Here nothing is really faster, its just that we
8401  * have broken out the fast-data path also just like
8402  * the fast-ack. Return 1 if we processed the packet
8403  * return 0 if you need to take the "slow-path".
8404  */
8405 static int
8406 bbr_do_fastnewdata(struct mbuf *m, struct tcphdr *th, struct socket *so,
8407     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8408     uint32_t tiwin, int32_t nxt_pkt)
8409 {
8410 	uint16_t nsegs;
8411 	int32_t newsize = 0;	/* automatic sockbuf scaling */
8412 	struct tcp_bbr *bbr;
8413 #ifdef NETFLIX_SB_LIMITS
8414 	u_int mcnt, appended;
8415 #endif
8416 
8417 	/* On the hpts and we would have called output */
8418 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8419 
8420 	/*
8421 	 * If last ACK falls within this segment's sequence numbers, record
8422 	 * the timestamp. NOTE that the test is modified according to the
8423 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8424 	 */
8425 	if (bbr->r_ctl.rc_resend != NULL) {
8426 		return (0);
8427 	}
8428 	if (tiwin && tiwin != tp->snd_wnd) {
8429 		return (0);
8430 	}
8431 	if (__predict_false((tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)))) {
8432 		return (0);
8433 	}
8434 	if (__predict_false((to->to_flags & TOF_TS) &&
8435 	    (TSTMP_LT(to->to_tsval, tp->ts_recent)))) {
8436 		return (0);
8437 	}
8438 	if (__predict_false((th->th_ack != tp->snd_una))) {
8439 		return (0);
8440 	}
8441 	if (__predict_false(tlen > sbspace(&so->so_rcv))) {
8442 		return (0);
8443 	}
8444 	if ((to->to_flags & TOF_TS) != 0 &&
8445 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8446 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
8447 		tp->ts_recent = to->to_tsval;
8448 	}
8449 	/*
8450 	 * This is a pure, in-sequence data packet with nothing on the
8451 	 * reassembly queue and we have enough buffer space to take it.
8452 	 */
8453 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8454 
8455 #ifdef NETFLIX_SB_LIMITS
8456 	if (so->so_rcv.sb_shlim) {
8457 		mcnt = m_memcnt(m);
8458 		appended = 0;
8459 		if (counter_fo_get(so->so_rcv.sb_shlim, mcnt,
8460 		    CFO_NOSLEEP, NULL) == false) {
8461 			counter_u64_add(tcp_sb_shlim_fails, 1);
8462 			m_freem(m);
8463 			return (1);
8464 		}
8465 	}
8466 #endif
8467 	/* Clean receiver SACK report if present */
8468 	if (tp->rcv_numsacks)
8469 		tcp_clean_sackreport(tp);
8470 	KMOD_TCPSTAT_INC(tcps_preddat);
8471 	tp->rcv_nxt += tlen;
8472 	if (tlen &&
8473 	    ((tp->t_flags2 & TF2_FBYTES_COMPLETE) == 0) &&
8474 	    (tp->t_fbyte_in == 0)) {
8475 		tp->t_fbyte_in = ticks;
8476 		if (tp->t_fbyte_in == 0)
8477 			tp->t_fbyte_in = 1;
8478 		if (tp->t_fbyte_out && tp->t_fbyte_in)
8479 			tp->t_flags2 |= TF2_FBYTES_COMPLETE;
8480 	}
8481 	/*
8482 	 * Pull snd_wl1 up to prevent seq wrap relative to th_seq.
8483 	 */
8484 	tp->snd_wl1 = th->th_seq;
8485 	/*
8486 	 * Pull rcv_up up to prevent seq wrap relative to rcv_nxt.
8487 	 */
8488 	tp->rcv_up = tp->rcv_nxt;
8489 	KMOD_TCPSTAT_ADD(tcps_rcvpack, (int)nsegs);
8490 	KMOD_TCPSTAT_ADD(tcps_rcvbyte, tlen);
8491 	newsize = tcp_autorcvbuf(m, th, so, tp, tlen);
8492 
8493 	/* Add data to socket buffer. */
8494 	SOCKBUF_LOCK(&so->so_rcv);
8495 	if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8496 		m_freem(m);
8497 	} else {
8498 		/*
8499 		 * Set new socket buffer size. Give up when limit is
8500 		 * reached.
8501 		 */
8502 		if (newsize)
8503 			if (!sbreserve_locked(so, SO_RCV, newsize, NULL))
8504 				so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
8505 		m_adj(m, drop_hdrlen);	/* delayed header drop */
8506 
8507 #ifdef NETFLIX_SB_LIMITS
8508 		appended =
8509 #endif
8510 			sbappendstream_locked(&so->so_rcv, m, 0);
8511 		ctf_calc_rwin(so, tp);
8512 	}
8513 	/* NB: sorwakeup_locked() does an implicit unlock. */
8514 	sorwakeup_locked(so);
8515 #ifdef NETFLIX_SB_LIMITS
8516 	if (so->so_rcv.sb_shlim && mcnt != appended)
8517 		counter_fo_release(so->so_rcv.sb_shlim, mcnt - appended);
8518 #endif
8519 	if (DELAY_ACK(tp, bbr, nsegs)) {
8520 		bbr->bbr_segs_rcvd += max(1, nsegs);
8521 		tp->t_flags |= TF_DELACK;
8522 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8523 	} else {
8524 		bbr->r_wanted_output = 1;
8525 		tp->t_flags |= TF_ACKNOW;
8526 	}
8527 	return (1);
8528 }
8529 
8530 /*
8531  * This subfunction is used to try to highly optimize the
8532  * fast path. We again allow window updates that are
8533  * in sequence to remain in the fast-path. We also add
8534  * in the __predict's to attempt to help the compiler.
8535  * Note that if we return a 0, then we can *not* process
8536  * it and the caller should push the packet into the
8537  * slow-path. If we return 1, then all is well and
8538  * the packet is fully processed.
8539  */
8540 static int
8541 bbr_fastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
8542     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8543     uint32_t tiwin, int32_t nxt_pkt, uint8_t iptos)
8544 {
8545 	int32_t acked;
8546 	uint16_t nsegs;
8547 	uint32_t sack_changed;
8548 	uint32_t prev_acked = 0;
8549 	struct tcp_bbr *bbr;
8550 
8551 	if (__predict_false(SEQ_LEQ(th->th_ack, tp->snd_una))) {
8552 		/* Old ack, behind (or duplicate to) the last one rcv'd */
8553 		return (0);
8554 	}
8555 	if (__predict_false(SEQ_GT(th->th_ack, tp->snd_max))) {
8556 		/* Above what we have sent? */
8557 		return (0);
8558 	}
8559 	if (__predict_false(tiwin == 0)) {
8560 		/* zero window */
8561 		return (0);
8562 	}
8563 	if (__predict_false(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN))) {
8564 		/* We need a SYN or a FIN, unlikely.. */
8565 		return (0);
8566 	}
8567 	if ((to->to_flags & TOF_TS) && __predict_false(TSTMP_LT(to->to_tsval, tp->ts_recent))) {
8568 		/* Timestamp is behind .. old ack with seq wrap? */
8569 		return (0);
8570 	}
8571 	if (__predict_false(IN_RECOVERY(tp->t_flags))) {
8572 		/* Still recovering */
8573 		return (0);
8574 	}
8575 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8576 	if (__predict_false(bbr->r_ctl.rc_resend != NULL)) {
8577 		/* We are retransmitting */
8578 		return (0);
8579 	}
8580 	if (__predict_false(bbr->rc_in_persist != 0)) {
8581 		/* In persist mode */
8582 		return (0);
8583 	}
8584 	if (bbr->r_ctl.rc_sacked) {
8585 		/* We have sack holes on our scoreboard */
8586 		return (0);
8587 	}
8588 	/* Ok if we reach here, we can process a fast-ack */
8589 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
8590 	sack_changed = bbr_log_ack(tp, to, th, &prev_acked);
8591 	/*
8592 	 * We never detect loss in fast ack [we can't
8593 	 * have a sack and can't be in recovery so
8594 	 * we always pass 0 (nothing detected)].
8595 	 */
8596 	bbr_lt_bw_sampling(bbr, bbr->r_ctl.rc_rcvtime, 0);
8597 	/* Did the window get updated? */
8598 	if (tiwin != tp->snd_wnd) {
8599 		tp->snd_wnd = tiwin;
8600 		tp->snd_wl1 = th->th_seq;
8601 		if (tp->snd_wnd > tp->max_sndwnd)
8602 			tp->max_sndwnd = tp->snd_wnd;
8603 	}
8604 	/* Do we need to exit persists? */
8605 	if ((bbr->rc_in_persist != 0) &&
8606 	    (tp->snd_wnd >= min((bbr->r_ctl.rc_high_rwnd/2),
8607 			       bbr_minseg(bbr)))) {
8608 		bbr_exit_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8609 		bbr->r_wanted_output = 1;
8610 	}
8611 	/* Do we need to enter persists? */
8612 	if ((bbr->rc_in_persist == 0) &&
8613 	    (tp->snd_wnd < min((bbr->r_ctl.rc_high_rwnd/2), bbr_minseg(bbr))) &&
8614 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
8615 	    (tp->snd_max == tp->snd_una) &&
8616 	    sbavail(&so->so_snd) &&
8617 	    (sbavail(&so->so_snd) > tp->snd_wnd)) {
8618 		/* No send window.. we must enter persist */
8619 		bbr_enter_persist(tp, bbr, bbr->r_ctl.rc_rcvtime, __LINE__);
8620 	}
8621 	/*
8622 	 * If last ACK falls within this segment's sequence numbers, record
8623 	 * the timestamp. NOTE that the test is modified according to the
8624 	 * latest proposal of the tcplw@cray.com list (Braden 1993/04/26).
8625 	 */
8626 	if ((to->to_flags & TOF_TS) != 0 &&
8627 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
8628 		tp->ts_recent_age = bbr->r_ctl.rc_rcvtime;
8629 		tp->ts_recent = to->to_tsval;
8630 	}
8631 	/*
8632 	 * This is a pure ack for outstanding data.
8633 	 */
8634 	KMOD_TCPSTAT_INC(tcps_predack);
8635 
8636 	/*
8637 	 * "bad retransmit" recovery.
8638 	 */
8639 	if (tp->t_flags & TF_PREVVALID) {
8640 		tp->t_flags &= ~TF_PREVVALID;
8641 		if (tp->t_rxtshift == 1 &&
8642 		    (int)(ticks - tp->t_badrxtwin) < 0)
8643 			bbr_cong_signal(tp, th, CC_RTO_ERR, NULL);
8644 	}
8645 	/*
8646 	 * Recalculate the transmit timer / rtt.
8647 	 *
8648 	 * Some boxes send broken timestamp replies during the SYN+ACK
8649 	 * phase, ignore timestamps of 0 or we could calculate a huge RTT
8650 	 * and blow up the retransmit timer.
8651 	 */
8652 	acked = BYTES_THIS_ACK(tp, th);
8653 
8654 #ifdef TCP_HHOOK
8655 	/* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
8656 	hhook_run_tcp_est_in(tp, th, to);
8657 #endif
8658 
8659 	KMOD_TCPSTAT_ADD(tcps_rcvackpack, (int)nsegs);
8660 	KMOD_TCPSTAT_ADD(tcps_rcvackbyte, acked);
8661 	sbdrop(&so->so_snd, acked);
8662 
8663 	if (SEQ_GT(th->th_ack, tp->snd_una))
8664 		bbr_collapse_rtt(tp, bbr, TCP_REXMTVAL(tp));
8665 	tp->snd_una = th->th_ack;
8666 	if (tp->snd_wnd < ctf_outstanding(tp))
8667 		/* The peer collapsed its window on us */
8668 		bbr_collapsed_window(bbr);
8669 	else if (bbr->rc_has_collapsed)
8670 		bbr_un_collapse_window(bbr);
8671 
8672 	if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
8673 		tp->snd_recover = tp->snd_una;
8674 	}
8675 	bbr_ack_received(tp, bbr, th, acked, sack_changed, prev_acked, __LINE__, 0);
8676 	/*
8677 	 * Pull snd_wl2 up to prevent seq wrap relative to th_ack.
8678 	 */
8679 	tp->snd_wl2 = th->th_ack;
8680 	m_freem(m);
8681 	/*
8682 	 * If all outstanding data are acked, stop retransmit timer,
8683 	 * otherwise restart timer using current (possibly backed-off)
8684 	 * value. If process is waiting for space, wakeup/selwakeup/signal.
8685 	 * If data are ready to send, let tcp_output decide between more
8686 	 * output or persist.
8687 	 * Wake up the socket if we have room to write more.
8688 	 */
8689 	sowwakeup(so);
8690 	if (tp->snd_una == tp->snd_max) {
8691 		/* Nothing left outstanding */
8692 		bbr_log_progress_event(bbr, tp, ticks, PROGRESS_CLEAR, __LINE__);
8693 		if (sbavail(&so->so_snd) == 0)
8694 			bbr->rc_tp->t_acktime = 0;
8695 		bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8696 		if (bbr->rc_in_persist == 0) {
8697 			bbr->r_ctl.rc_went_idle_time = bbr->r_ctl.rc_rcvtime;
8698 		}
8699 		sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
8700 		bbr_log_ack_clear(bbr, bbr->r_ctl.rc_rcvtime);
8701 		/*
8702 		 * We invalidate the last ack here since we
8703 		 * don't want to transfer forward the time
8704 		 * for our sum's calculations.
8705 		 */
8706 		bbr->r_wanted_output = 1;
8707 	}
8708 	if (sbavail(&so->so_snd)) {
8709 		bbr->r_wanted_output = 1;
8710 	}
8711 	return (1);
8712 }
8713 
8714 /*
8715  * Return value of 1, the TCB is unlocked and most
8716  * likely gone, return value of 0, the TCB is still
8717  * locked.
8718  */
8719 static int
8720 bbr_do_syn_sent(struct mbuf *m, struct tcphdr *th, struct socket *so,
8721     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8722     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8723 {
8724 	int32_t todrop;
8725 	int32_t ourfinisacked = 0;
8726 	struct tcp_bbr *bbr;
8727 	int32_t ret_val = 0;
8728 
8729 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8730 
8731 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8732 	ctf_calc_rwin(so, tp);
8733 	/*
8734 	 * If the state is SYN_SENT: if seg contains an ACK, but not for our
8735 	 * SYN, drop the input. if seg contains a RST, then drop the
8736 	 * connection. if seg does not contain SYN, then drop it. Otherwise
8737 	 * this is an acceptable SYN segment initialize tp->rcv_nxt and
8738 	 * tp->irs if seg contains ack then advance tp->snd_una. BRR does
8739 	 * not support ECN so we will not say we are capable. if SYN has
8740 	 * been acked change to ESTABLISHED else SYN_RCVD state arrange for
8741 	 * segment to be acked (eventually) continue processing rest of
8742 	 * data/controls, beginning with URG
8743 	 */
8744 	if ((thflags & TH_ACK) &&
8745 	    (SEQ_LEQ(th->th_ack, tp->iss) ||
8746 	    SEQ_GT(th->th_ack, tp->snd_max))) {
8747 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8748 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8749 		return (1);
8750 	}
8751 	if ((thflags & (TH_ACK | TH_RST)) == (TH_ACK | TH_RST)) {
8752 		TCP_PROBE5(connect__refused, NULL, tp,
8753 		    mtod(m, const char *), tp, th);
8754 		tp = tcp_drop(tp, ECONNREFUSED);
8755 		ctf_do_drop(m, tp);
8756 		return (1);
8757 	}
8758 	if (thflags & TH_RST) {
8759 		ctf_do_drop(m, tp);
8760 		return (1);
8761 	}
8762 	if (!(thflags & TH_SYN)) {
8763 		ctf_do_drop(m, tp);
8764 		return (1);
8765 	}
8766 	tp->irs = th->th_seq;
8767 	tcp_rcvseqinit(tp);
8768 	if (thflags & TH_ACK) {
8769 		int tfo_partial = 0;
8770 
8771 		KMOD_TCPSTAT_INC(tcps_connects);
8772 		soisconnected(so);
8773 #ifdef MAC
8774 		mac_socketpeer_set_from_mbuf(m, so);
8775 #endif
8776 		/* Do window scaling on this connection? */
8777 		if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
8778 		    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
8779 			tp->rcv_scale = tp->request_r_scale;
8780 		}
8781 		tp->rcv_adv += min(tp->rcv_wnd,
8782 		    TCP_MAXWIN << tp->rcv_scale);
8783 		/*
8784 		 * If not all the data that was sent in the TFO SYN
8785 		 * has been acked, resend the remainder right away.
8786 		 */
8787 		if ((tp->t_flags & TF_FASTOPEN) &&
8788 		    (tp->snd_una != tp->snd_max)) {
8789 			tp->snd_nxt = th->th_ack;
8790 			tfo_partial = 1;
8791 		}
8792 		/*
8793 		 * If there's data, delay ACK; if there's also a FIN ACKNOW
8794 		 * will be turned on later.
8795 		 */
8796 		if (DELAY_ACK(tp, bbr, 1) && tlen != 0 && !tfo_partial) {
8797 			bbr->bbr_segs_rcvd += 1;
8798 			tp->t_flags |= TF_DELACK;
8799 			bbr_timer_cancel(bbr, __LINE__, bbr->r_ctl.rc_rcvtime);
8800 		} else {
8801 			bbr->r_wanted_output = 1;
8802 			tp->t_flags |= TF_ACKNOW;
8803 		}
8804 		if (SEQ_GT(th->th_ack, tp->iss)) {
8805 			/*
8806 			 * The SYN is acked
8807 			 * handle it specially.
8808 			 */
8809 			bbr_log_syn(tp, to);
8810 		}
8811 		if (SEQ_GT(th->th_ack, tp->snd_una)) {
8812 			/*
8813 			 * We advance snd_una for the
8814 			 * fast open case. If th_ack is
8815 			 * acknowledging data beyond
8816 			 * snd_una we can't just call
8817 			 * ack-processing since the
8818 			 * data stream in our send-map
8819 			 * will start at snd_una + 1 (one
8820 			 * beyond the SYN). If its just
8821 			 * equal we don't need to do that
8822 			 * and there is no send_map.
8823 			 */
8824 			tp->snd_una++;
8825 		}
8826 		/*
8827 		 * Received <SYN,ACK> in SYN_SENT[*] state. Transitions:
8828 		 * SYN_SENT  --> ESTABLISHED SYN_SENT* --> FIN_WAIT_1
8829 		 */
8830 		tp->t_starttime = ticks;
8831 		if (tp->t_flags & TF_NEEDFIN) {
8832 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
8833 			tp->t_flags &= ~TF_NEEDFIN;
8834 			thflags &= ~TH_SYN;
8835 		} else {
8836 			tcp_state_change(tp, TCPS_ESTABLISHED);
8837 			TCP_PROBE5(connect__established, NULL, tp,
8838 			    mtod(m, const char *), tp, th);
8839 			cc_conn_init(tp);
8840 		}
8841 	} else {
8842 		/*
8843 		 * Received initial SYN in SYN-SENT[*] state => simultaneous
8844 		 * open.  If segment contains CC option and there is a
8845 		 * cached CC, apply TAO test. If it succeeds, connection is *
8846 		 * half-synchronized. Otherwise, do 3-way handshake:
8847 		 * SYN-SENT -> SYN-RECEIVED SYN-SENT* -> SYN-RECEIVED* If
8848 		 * there was no CC option, clear cached CC value.
8849 		 */
8850 		tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN | TF_SONOTCONN);
8851 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
8852 	}
8853 	/*
8854 	 * Advance th->th_seq to correspond to first data byte. If data,
8855 	 * trim to stay within window, dropping FIN if necessary.
8856 	 */
8857 	th->th_seq++;
8858 	if (tlen > tp->rcv_wnd) {
8859 		todrop = tlen - tp->rcv_wnd;
8860 		m_adj(m, -todrop);
8861 		tlen = tp->rcv_wnd;
8862 		thflags &= ~TH_FIN;
8863 		KMOD_TCPSTAT_INC(tcps_rcvpackafterwin);
8864 		KMOD_TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
8865 	}
8866 	tp->snd_wl1 = th->th_seq - 1;
8867 	tp->rcv_up = th->th_seq;
8868 	/*
8869 	 * Client side of transaction: already sent SYN and data. If the
8870 	 * remote host used T/TCP to validate the SYN, our data will be
8871 	 * ACK'd; if so, enter normal data segment processing in the middle
8872 	 * of step 5, ack processing. Otherwise, goto step 6.
8873 	 */
8874 	if (thflags & TH_ACK) {
8875 		if ((to->to_flags & TOF_TS) != 0) {
8876 			uint32_t t, rtt;
8877 
8878 			t = tcp_tv_to_mssectick(&bbr->rc_tv);
8879 			if (TSTMP_GEQ(t, to->to_tsecr)) {
8880 				rtt = t - to->to_tsecr;
8881 				if (rtt == 0) {
8882 					rtt = 1;
8883 				}
8884 				rtt *= MS_IN_USEC;
8885 				tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
8886 				apply_filter_min_small(&bbr->r_ctl.rc_rttprop,
8887 						       rtt, bbr->r_ctl.rc_rcvtime);
8888 			}
8889 		}
8890 		if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val))
8891 			return (ret_val);
8892 		/* We may have changed to FIN_WAIT_1 above */
8893 		if (tp->t_state == TCPS_FIN_WAIT_1) {
8894 			/*
8895 			 * In FIN_WAIT_1 STATE in addition to the processing
8896 			 * for the ESTABLISHED state if our FIN is now
8897 			 * acknowledged then enter FIN_WAIT_2.
8898 			 */
8899 			if (ourfinisacked) {
8900 				/*
8901 				 * If we can't receive any more data, then
8902 				 * closing user can proceed. Starting the
8903 				 * timer is contrary to the specification,
8904 				 * but if we don't get a FIN we'll hang
8905 				 * forever.
8906 				 *
8907 				 * XXXjl: we should release the tp also, and
8908 				 * use a compressed state.
8909 				 */
8910 				if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
8911 					soisdisconnected(so);
8912 					tcp_timer_activate(tp, TT_2MSL,
8913 					    (tcp_fast_finwait2_recycle ?
8914 					    tcp_finwait2_timeout :
8915 					    TP_MAXIDLE(tp)));
8916 				}
8917 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
8918 			}
8919 		}
8920 	}
8921 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
8922 	    tiwin, thflags, nxt_pkt));
8923 }
8924 
8925 /*
8926  * Return value of 1, the TCB is unlocked and most
8927  * likely gone, return value of 0, the TCB is still
8928  * locked.
8929  */
8930 static int
8931 bbr_do_syn_recv(struct mbuf *m, struct tcphdr *th, struct socket *so,
8932 		struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
8933 		uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
8934 {
8935 	int32_t ourfinisacked = 0;
8936 	int32_t ret_val;
8937 	struct tcp_bbr *bbr;
8938 
8939 	INP_WLOCK_ASSERT(tptoinpcb(tp));
8940 
8941 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
8942 	ctf_calc_rwin(so, tp);
8943 	if ((thflags & TH_RST) ||
8944 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
8945 		return (ctf_process_rst(m, th, so, tp));
8946 	if ((thflags & TH_ACK) &&
8947 	    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
8948 	     SEQ_GT(th->th_ack, tp->snd_max))) {
8949 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8950 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8951 		return (1);
8952 	}
8953 	if (tp->t_flags & TF_FASTOPEN) {
8954 		/*
8955 		 * When a TFO connection is in SYN_RECEIVED, the only valid
8956 		 * packets are the initial SYN, a retransmit/copy of the
8957 		 * initial SYN (possibly with a subset of the original
8958 		 * data), a valid ACK, a FIN, or a RST.
8959 		 */
8960 		if ((thflags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) {
8961 			tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8962 			ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8963 			return (1);
8964 		} else if (thflags & TH_SYN) {
8965 			/* non-initial SYN is ignored */
8966 			if ((bbr->r_ctl.rc_hpts_flags & PACE_TMR_RXT) ||
8967 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_TLP) ||
8968 			    (bbr->r_ctl.rc_hpts_flags & PACE_TMR_RACK)) {
8969 				ctf_do_drop(m, NULL);
8970 				return (0);
8971 			}
8972 		} else if (!(thflags & (TH_ACK | TH_FIN | TH_RST))) {
8973 			ctf_do_drop(m, NULL);
8974 			return (0);
8975 		}
8976 	}
8977 	/*
8978 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
8979 	 * it's less than ts_recent, drop it.
8980 	 */
8981 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
8982 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
8983 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
8984 			return (ret_val);
8985 	}
8986 	/*
8987 	 * In the SYN-RECEIVED state, validate that the packet belongs to
8988 	 * this connection before trimming the data to fit the receive
8989 	 * window.  Check the sequence number versus IRS since we know the
8990 	 * sequence numbers haven't wrapped.  This is a partial fix for the
8991 	 * "LAND" DoS attack.
8992 	 */
8993 	if (SEQ_LT(th->th_seq, tp->irs)) {
8994 		tcp_log_end_status(tp, TCP_EI_STATUS_RST_IN_FRONT);
8995 		ctf_do_dropwithreset(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
8996 		return (1);
8997 	}
8998 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
8999 		return (ret_val);
9000 	}
9001 	/*
9002 	 * If last ACK falls within this segment's sequence numbers, record
9003 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9004 	 * from the latest proposal of the tcplw@cray.com list (Braden
9005 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9006 	 * with our earlier PAWS tests, so this check should be solely
9007 	 * predicated on the sequence space of this segment. 3) That we
9008 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9009 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9010 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9011 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9012 	 * p.869. In such cases, we can still calculate the RTT correctly
9013 	 * when RCV.NXT == Last.ACK.Sent.
9014 	 */
9015 	if ((to->to_flags & TOF_TS) != 0 &&
9016 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9017 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9018 		    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9019 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9020 		tp->ts_recent = to->to_tsval;
9021 	}
9022 	tp->snd_wnd = tiwin;
9023 	/*
9024 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9025 	 * is on (half-synchronized state), then queue data for later
9026 	 * processing; else drop segment and return.
9027 	 */
9028 	if ((thflags & TH_ACK) == 0) {
9029 		if (tp->t_flags & TF_FASTOPEN) {
9030 			cc_conn_init(tp);
9031 		}
9032 		return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9033 					 tiwin, thflags, nxt_pkt));
9034 	}
9035 	KMOD_TCPSTAT_INC(tcps_connects);
9036 	if (tp->t_flags & TF_SONOTCONN) {
9037 		tp->t_flags &= ~TF_SONOTCONN;
9038 		soisconnected(so);
9039 	}
9040 	/* Do window scaling? */
9041 	if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
9042 	    (TF_RCVD_SCALE | TF_REQ_SCALE)) {
9043 		tp->rcv_scale = tp->request_r_scale;
9044 	}
9045 	/*
9046 	 * ok for the first time in lets see if we can use the ts to figure
9047 	 * out what the initial RTT was.
9048 	 */
9049 	if ((to->to_flags & TOF_TS) != 0) {
9050 		uint32_t t, rtt;
9051 
9052 		t = tcp_tv_to_mssectick(&bbr->rc_tv);
9053 		if (TSTMP_GEQ(t, to->to_tsecr)) {
9054 			rtt = t - to->to_tsecr;
9055 			if (rtt == 0) {
9056 				rtt = 1;
9057 			}
9058 			rtt *= MS_IN_USEC;
9059 			tcp_bbr_xmit_timer(bbr, rtt, 0, 0, 0);
9060 			apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, bbr->r_ctl.rc_rcvtime);
9061 		}
9062 	}
9063 	/* Drop off any SYN in the send map (probably not there)  */
9064 	if (thflags & TH_ACK)
9065 		bbr_log_syn(tp, to);
9066 	if ((tp->t_flags & TF_FASTOPEN) && tp->t_tfo_pending) {
9067 		tcp_fastopen_decrement_counter(tp->t_tfo_pending);
9068 		tp->t_tfo_pending = NULL;
9069 	}
9070 	/*
9071 	 * Make transitions: SYN-RECEIVED  -> ESTABLISHED SYN-RECEIVED* ->
9072 	 * FIN-WAIT-1
9073 	 */
9074 	tp->t_starttime = ticks;
9075 	if (tp->t_flags & TF_NEEDFIN) {
9076 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
9077 		tp->t_flags &= ~TF_NEEDFIN;
9078 	} else {
9079 		tcp_state_change(tp, TCPS_ESTABLISHED);
9080 		TCP_PROBE5(accept__established, NULL, tp,
9081 			   mtod(m, const char *), tp, th);
9082 		/*
9083 		 * TFO connections call cc_conn_init() during SYN
9084 		 * processing.  Calling it again here for such connections
9085 		 * is not harmless as it would undo the snd_cwnd reduction
9086 		 * that occurs when a TFO SYN|ACK is retransmitted.
9087 		 */
9088 		if (!(tp->t_flags & TF_FASTOPEN))
9089 			cc_conn_init(tp);
9090 	}
9091 	/*
9092 	 * Account for the ACK of our SYN prior to
9093 	 * regular ACK processing below, except for
9094 	 * simultaneous SYN, which is handled later.
9095 	 */
9096 	if (SEQ_GT(th->th_ack, tp->snd_una) && !(tp->t_flags & TF_NEEDSYN))
9097 		tp->snd_una++;
9098 	/*
9099 	 * If segment contains data or ACK, will call tcp_reass() later; if
9100 	 * not, do so now to pass queued data to user.
9101 	 */
9102 	if (tlen == 0 && (thflags & TH_FIN) == 0) {
9103 		(void)tcp_reass(tp, (struct tcphdr *)0, NULL, 0,
9104 			(struct mbuf *)0);
9105 		if (tp->t_flags & TF_WAKESOR) {
9106 			tp->t_flags &= ~TF_WAKESOR;
9107 			/* NB: sorwakeup_locked() does an implicit unlock. */
9108 			sorwakeup_locked(so);
9109 		}
9110 	}
9111 	tp->snd_wl1 = th->th_seq - 1;
9112 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9113 		return (ret_val);
9114 	}
9115 	if (tp->t_state == TCPS_FIN_WAIT_1) {
9116 		/* We could have went to FIN_WAIT_1 (or EST) above */
9117 		/*
9118 		 * In FIN_WAIT_1 STATE in addition to the processing for the
9119 		 * ESTABLISHED state if our FIN is now acknowledged then
9120 		 * enter FIN_WAIT_2.
9121 		 */
9122 		if (ourfinisacked) {
9123 			/*
9124 			 * If we can't receive any more data, then closing
9125 			 * user can proceed. Starting the timer is contrary
9126 			 * to the specification, but if we don't get a FIN
9127 			 * we'll hang forever.
9128 			 *
9129 			 * XXXjl: we should release the tp also, and use a
9130 			 * compressed state.
9131 			 */
9132 			if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9133 				soisdisconnected(so);
9134 				tcp_timer_activate(tp, TT_2MSL,
9135 						   (tcp_fast_finwait2_recycle ?
9136 						    tcp_finwait2_timeout :
9137 						    TP_MAXIDLE(tp)));
9138 			}
9139 			tcp_state_change(tp, TCPS_FIN_WAIT_2);
9140 		}
9141 	}
9142 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9143 				 tiwin, thflags, nxt_pkt));
9144 }
9145 
9146 /*
9147  * Return value of 1, the TCB is unlocked and most
9148  * likely gone, return value of 0, the TCB is still
9149  * locked.
9150  */
9151 static int
9152 bbr_do_established(struct mbuf *m, struct tcphdr *th, struct socket *so,
9153     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9154     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9155 {
9156 	struct tcp_bbr *bbr;
9157 	int32_t ret_val;
9158 
9159 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9160 
9161 	/*
9162 	 * Header prediction: check for the two common cases of a
9163 	 * uni-directional data xfer.  If the packet has no control flags,
9164 	 * is in-sequence, the window didn't change and we're not
9165 	 * retransmitting, it's a candidate.  If the length is zero and the
9166 	 * ack moved forward, we're the sender side of the xfer.  Just free
9167 	 * the data acked & wake any higher level process that was blocked
9168 	 * waiting for space.  If the length is non-zero and the ack didn't
9169 	 * move, we're the receiver side.  If we're getting packets in-order
9170 	 * (the reassembly queue is empty), add the data toc The socket
9171 	 * buffer and note that we need a delayed ack. Make sure that the
9172 	 * hidden state-flags are also off. Since we check for
9173 	 * TCPS_ESTABLISHED first, it can only be TH_NEEDSYN.
9174 	 */
9175 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9176 	if (bbr->r_ctl.rc_delivered < (4 * tp->t_maxseg)) {
9177 		/*
9178 		 * If we have delived under 4 segments increase the initial
9179 		 * window if raised by the peer. We use this to determine
9180 		 * dynamic and static rwnd's at the end of a connection.
9181 		 */
9182 		bbr->r_ctl.rc_init_rwnd = max(tiwin, tp->snd_wnd);
9183 	}
9184 	if (__predict_true(((to->to_flags & TOF_SACK) == 0)) &&
9185 	    __predict_true((thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK)) == TH_ACK) &&
9186 	    __predict_true(SEGQ_EMPTY(tp)) &&
9187 	    __predict_true(th->th_seq == tp->rcv_nxt)) {
9188 		if (tlen == 0) {
9189 			if (bbr_fastack(m, th, so, tp, to, drop_hdrlen, tlen,
9190 			    tiwin, nxt_pkt, iptos)) {
9191 				return (0);
9192 			}
9193 		} else {
9194 			if (bbr_do_fastnewdata(m, th, so, tp, to, drop_hdrlen, tlen,
9195 			    tiwin, nxt_pkt)) {
9196 				return (0);
9197 			}
9198 		}
9199 	}
9200 	ctf_calc_rwin(so, tp);
9201 
9202 	if ((thflags & TH_RST) ||
9203 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9204 		return (ctf_process_rst(m, th, so, tp));
9205 	/*
9206 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9207 	 * synchronized state.
9208 	 */
9209 	if (thflags & TH_SYN) {
9210 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9211 		return (ret_val);
9212 	}
9213 	/*
9214 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9215 	 * it's less than ts_recent, drop it.
9216 	 */
9217 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9218 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9219 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9220 			return (ret_val);
9221 	}
9222 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9223 		return (ret_val);
9224 	}
9225 	/*
9226 	 * If last ACK falls within this segment's sequence numbers, record
9227 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9228 	 * from the latest proposal of the tcplw@cray.com list (Braden
9229 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9230 	 * with our earlier PAWS tests, so this check should be solely
9231 	 * predicated on the sequence space of this segment. 3) That we
9232 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9233 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9234 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9235 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9236 	 * p.869. In such cases, we can still calculate the RTT correctly
9237 	 * when RCV.NXT == Last.ACK.Sent.
9238 	 */
9239 	if ((to->to_flags & TOF_TS) != 0 &&
9240 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9241 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9242 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9243 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9244 		tp->ts_recent = to->to_tsval;
9245 	}
9246 	/*
9247 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9248 	 * is on (half-synchronized state), then queue data for later
9249 	 * processing; else drop segment and return.
9250 	 */
9251 	if ((thflags & TH_ACK) == 0) {
9252 		if (tp->t_flags & TF_NEEDSYN) {
9253 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9254 			    tiwin, thflags, nxt_pkt));
9255 		} else if (tp->t_flags & TF_ACKNOW) {
9256 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9257 			bbr->r_wanted_output = 1;
9258 			return (ret_val);
9259 		} else {
9260 			ctf_do_drop(m, NULL);
9261 			return (0);
9262 		}
9263 	}
9264 	/*
9265 	 * Ack processing.
9266 	 */
9267 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9268 		return (ret_val);
9269 	}
9270 	if (sbavail(&so->so_snd)) {
9271 		if (ctf_progress_timeout_check(tp, true)) {
9272 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9273 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9274 			return (1);
9275 		}
9276 	}
9277 	/* State changes only happen in bbr_process_data() */
9278 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9279 	    tiwin, thflags, nxt_pkt));
9280 }
9281 
9282 /*
9283  * Return value of 1, the TCB is unlocked and most
9284  * likely gone, return value of 0, the TCB is still
9285  * locked.
9286  */
9287 static int
9288 bbr_do_close_wait(struct mbuf *m, struct tcphdr *th, struct socket *so,
9289     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9290     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9291 {
9292 	struct tcp_bbr *bbr;
9293 	int32_t ret_val;
9294 
9295 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9296 
9297 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9298 	ctf_calc_rwin(so, tp);
9299 	if ((thflags & TH_RST) ||
9300 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9301 		return (ctf_process_rst(m, th, so, tp));
9302 	/*
9303 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9304 	 * synchronized state.
9305 	 */
9306 	if (thflags & TH_SYN) {
9307 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9308 		return (ret_val);
9309 	}
9310 	/*
9311 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9312 	 * it's less than ts_recent, drop it.
9313 	 */
9314 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9315 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9316 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9317 			return (ret_val);
9318 	}
9319 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9320 		return (ret_val);
9321 	}
9322 	/*
9323 	 * If last ACK falls within this segment's sequence numbers, record
9324 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9325 	 * from the latest proposal of the tcplw@cray.com list (Braden
9326 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9327 	 * with our earlier PAWS tests, so this check should be solely
9328 	 * predicated on the sequence space of this segment. 3) That we
9329 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9330 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9331 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9332 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9333 	 * p.869. In such cases, we can still calculate the RTT correctly
9334 	 * when RCV.NXT == Last.ACK.Sent.
9335 	 */
9336 	if ((to->to_flags & TOF_TS) != 0 &&
9337 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9338 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9339 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9340 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9341 		tp->ts_recent = to->to_tsval;
9342 	}
9343 	/*
9344 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9345 	 * is on (half-synchronized state), then queue data for later
9346 	 * processing; else drop segment and return.
9347 	 */
9348 	if ((thflags & TH_ACK) == 0) {
9349 		if (tp->t_flags & TF_NEEDSYN) {
9350 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9351 			    tiwin, thflags, nxt_pkt));
9352 		} else if (tp->t_flags & TF_ACKNOW) {
9353 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9354 			bbr->r_wanted_output = 1;
9355 			return (ret_val);
9356 		} else {
9357 			ctf_do_drop(m, NULL);
9358 			return (0);
9359 		}
9360 	}
9361 	/*
9362 	 * Ack processing.
9363 	 */
9364 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, NULL, thflags, &ret_val)) {
9365 		return (ret_val);
9366 	}
9367 	if (sbavail(&so->so_snd)) {
9368 		if (ctf_progress_timeout_check(tp, true)) {
9369 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9370 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9371 			return (1);
9372 		}
9373 	}
9374 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9375 	    tiwin, thflags, nxt_pkt));
9376 }
9377 
9378 static int
9379 bbr_check_data_after_close(struct mbuf *m, struct tcp_bbr *bbr,
9380     struct tcpcb *tp, int32_t * tlen, struct tcphdr *th, struct socket *so)
9381 {
9382 
9383 	if (bbr->rc_allow_data_af_clo == 0) {
9384 close_now:
9385 		tcp_log_end_status(tp, TCP_EI_STATUS_DATA_A_CLOSE);
9386 		/* tcp_close will kill the inp pre-log the Reset */
9387 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
9388 		tp = tcp_close(tp);
9389 		KMOD_TCPSTAT_INC(tcps_rcvafterclose);
9390 		ctf_do_dropwithreset(m, tp, th, BANDLIM_UNLIMITED, (*tlen));
9391 		return (1);
9392 	}
9393 	if (sbavail(&so->so_snd) == 0)
9394 		goto close_now;
9395 	/* Ok we allow data that is ignored and a followup reset */
9396 	tp->rcv_nxt = th->th_seq + *tlen;
9397 	tp->t_flags2 |= TF2_DROP_AF_DATA;
9398 	bbr->r_wanted_output = 1;
9399 	*tlen = 0;
9400 	return (0);
9401 }
9402 
9403 /*
9404  * Return value of 1, the TCB is unlocked and most
9405  * likely gone, return value of 0, the TCB is still
9406  * locked.
9407  */
9408 static int
9409 bbr_do_fin_wait_1(struct mbuf *m, struct tcphdr *th, struct socket *so,
9410     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9411     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9412 {
9413 	int32_t ourfinisacked = 0;
9414 	int32_t ret_val;
9415 	struct tcp_bbr *bbr;
9416 
9417 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9418 
9419 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9420 	ctf_calc_rwin(so, tp);
9421 	if ((thflags & TH_RST) ||
9422 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9423 		return (ctf_process_rst(m, th, so, tp));
9424 	/*
9425 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9426 	 * synchronized state.
9427 	 */
9428 	if (thflags & TH_SYN) {
9429 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9430 		return (ret_val);
9431 	}
9432 	/*
9433 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9434 	 * it's less than ts_recent, drop it.
9435 	 */
9436 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9437 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9438 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9439 			return (ret_val);
9440 	}
9441 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9442 		return (ret_val);
9443 	}
9444 	/*
9445 	 * If new data are received on a connection after the user processes
9446 	 * are gone, then RST the other end.
9447 	 * We call a new function now so we might continue and setup
9448 	 * to reset at all data being ack'd.
9449 	 */
9450 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9451 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9452 		return (1);
9453 	/*
9454 	 * If last ACK falls within this segment's sequence numbers, record
9455 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9456 	 * from the latest proposal of the tcplw@cray.com list (Braden
9457 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9458 	 * with our earlier PAWS tests, so this check should be solely
9459 	 * predicated on the sequence space of this segment. 3) That we
9460 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9461 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9462 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9463 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9464 	 * p.869. In such cases, we can still calculate the RTT correctly
9465 	 * when RCV.NXT == Last.ACK.Sent.
9466 	 */
9467 	if ((to->to_flags & TOF_TS) != 0 &&
9468 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9469 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9470 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9471 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9472 		tp->ts_recent = to->to_tsval;
9473 	}
9474 	/*
9475 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9476 	 * is on (half-synchronized state), then queue data for later
9477 	 * processing; else drop segment and return.
9478 	 */
9479 	if ((thflags & TH_ACK) == 0) {
9480 		if (tp->t_flags & TF_NEEDSYN) {
9481 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9482 			    tiwin, thflags, nxt_pkt));
9483 		} else if (tp->t_flags & TF_ACKNOW) {
9484 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9485 			bbr->r_wanted_output = 1;
9486 			return (ret_val);
9487 		} else {
9488 			ctf_do_drop(m, NULL);
9489 			return (0);
9490 		}
9491 	}
9492 	/*
9493 	 * Ack processing.
9494 	 */
9495 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9496 		return (ret_val);
9497 	}
9498 	if (ourfinisacked) {
9499 		/*
9500 		 * If we can't receive any more data, then closing user can
9501 		 * proceed. Starting the timer is contrary to the
9502 		 * specification, but if we don't get a FIN we'll hang
9503 		 * forever.
9504 		 *
9505 		 * XXXjl: we should release the tp also, and use a
9506 		 * compressed state.
9507 		 */
9508 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
9509 			soisdisconnected(so);
9510 			tcp_timer_activate(tp, TT_2MSL,
9511 			    (tcp_fast_finwait2_recycle ?
9512 			    tcp_finwait2_timeout :
9513 			    TP_MAXIDLE(tp)));
9514 		}
9515 		tcp_state_change(tp, TCPS_FIN_WAIT_2);
9516 	}
9517 	if (sbavail(&so->so_snd)) {
9518 		if (ctf_progress_timeout_check(tp, true)) {
9519 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9520 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9521 			return (1);
9522 		}
9523 	}
9524 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9525 	    tiwin, thflags, nxt_pkt));
9526 }
9527 
9528 /*
9529  * Return value of 1, the TCB is unlocked and most
9530  * likely gone, return value of 0, the TCB is still
9531  * locked.
9532  */
9533 static int
9534 bbr_do_closing(struct mbuf *m, struct tcphdr *th, struct socket *so,
9535     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9536     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9537 {
9538 	int32_t ourfinisacked = 0;
9539 	int32_t ret_val;
9540 	struct tcp_bbr *bbr;
9541 
9542 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9543 
9544 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9545 	ctf_calc_rwin(so, tp);
9546 	if ((thflags & TH_RST) ||
9547 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9548 		return (ctf_process_rst(m, th, so, tp));
9549 	/*
9550 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9551 	 * synchronized state.
9552 	 */
9553 	if (thflags & TH_SYN) {
9554 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9555 		return (ret_val);
9556 	}
9557 	/*
9558 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9559 	 * it's less than ts_recent, drop it.
9560 	 */
9561 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9562 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9563 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9564 			return (ret_val);
9565 	}
9566 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9567 		return (ret_val);
9568 	}
9569 	/*
9570 	 * If last ACK falls within this segment's sequence numbers, record
9571 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9572 	 * from the latest proposal of the tcplw@cray.com list (Braden
9573 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9574 	 * with our earlier PAWS tests, so this check should be solely
9575 	 * predicated on the sequence space of this segment. 3) That we
9576 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9577 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9578 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9579 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9580 	 * p.869. In such cases, we can still calculate the RTT correctly
9581 	 * when RCV.NXT == Last.ACK.Sent.
9582 	 */
9583 	if ((to->to_flags & TOF_TS) != 0 &&
9584 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9585 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9586 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9587 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9588 		tp->ts_recent = to->to_tsval;
9589 	}
9590 	/*
9591 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9592 	 * is on (half-synchronized state), then queue data for later
9593 	 * processing; else drop segment and return.
9594 	 */
9595 	if ((thflags & TH_ACK) == 0) {
9596 		if (tp->t_flags & TF_NEEDSYN) {
9597 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9598 			    tiwin, thflags, nxt_pkt));
9599 		} else if (tp->t_flags & TF_ACKNOW) {
9600 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9601 			bbr->r_wanted_output = 1;
9602 			return (ret_val);
9603 		} else {
9604 			ctf_do_drop(m, NULL);
9605 			return (0);
9606 		}
9607 	}
9608 	/*
9609 	 * Ack processing.
9610 	 */
9611 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9612 		return (ret_val);
9613 	}
9614 	if (ourfinisacked) {
9615 		tcp_twstart(tp);
9616 		m_freem(m);
9617 		return (1);
9618 	}
9619 	if (sbavail(&so->so_snd)) {
9620 		if (ctf_progress_timeout_check(tp, true)) {
9621 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9622 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9623 			return (1);
9624 		}
9625 	}
9626 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9627 	    tiwin, thflags, nxt_pkt));
9628 }
9629 
9630 /*
9631  * Return value of 1, the TCB is unlocked and most
9632  * likely gone, return value of 0, the TCB is still
9633  * locked.
9634  */
9635 static int
9636 bbr_do_lastack(struct mbuf *m, struct tcphdr *th, struct socket *so,
9637     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9638     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9639 {
9640 	int32_t ourfinisacked = 0;
9641 	int32_t ret_val;
9642 	struct tcp_bbr *bbr;
9643 
9644 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9645 
9646 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9647 	ctf_calc_rwin(so, tp);
9648 	if ((thflags & TH_RST) ||
9649 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9650 		return (ctf_process_rst(m, th, so, tp));
9651 	/*
9652 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9653 	 * synchronized state.
9654 	 */
9655 	if (thflags & TH_SYN) {
9656 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9657 		return (ret_val);
9658 	}
9659 	/*
9660 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9661 	 * it's less than ts_recent, drop it.
9662 	 */
9663 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9664 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9665 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9666 			return (ret_val);
9667 	}
9668 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9669 		return (ret_val);
9670 	}
9671 	/*
9672 	 * If last ACK falls within this segment's sequence numbers, record
9673 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9674 	 * from the latest proposal of the tcplw@cray.com list (Braden
9675 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9676 	 * with our earlier PAWS tests, so this check should be solely
9677 	 * predicated on the sequence space of this segment. 3) That we
9678 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9679 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9680 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9681 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9682 	 * p.869. In such cases, we can still calculate the RTT correctly
9683 	 * when RCV.NXT == Last.ACK.Sent.
9684 	 */
9685 	if ((to->to_flags & TOF_TS) != 0 &&
9686 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9687 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9688 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9689 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9690 		tp->ts_recent = to->to_tsval;
9691 	}
9692 	/*
9693 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9694 	 * is on (half-synchronized state), then queue data for later
9695 	 * processing; else drop segment and return.
9696 	 */
9697 	if ((thflags & TH_ACK) == 0) {
9698 		if (tp->t_flags & TF_NEEDSYN) {
9699 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9700 			    tiwin, thflags, nxt_pkt));
9701 		} else if (tp->t_flags & TF_ACKNOW) {
9702 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9703 			bbr->r_wanted_output = 1;
9704 			return (ret_val);
9705 		} else {
9706 			ctf_do_drop(m, NULL);
9707 			return (0);
9708 		}
9709 	}
9710 	/*
9711 	 * case TCPS_LAST_ACK: Ack processing.
9712 	 */
9713 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9714 		return (ret_val);
9715 	}
9716 	if (ourfinisacked) {
9717 		tp = tcp_close(tp);
9718 		ctf_do_drop(m, tp);
9719 		return (1);
9720 	}
9721 	if (sbavail(&so->so_snd)) {
9722 		if (ctf_progress_timeout_check(tp, true)) {
9723 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9724 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9725 			return (1);
9726 		}
9727 	}
9728 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9729 	    tiwin, thflags, nxt_pkt));
9730 }
9731 
9732 /*
9733  * Return value of 1, the TCB is unlocked and most
9734  * likely gone, return value of 0, the TCB is still
9735  * locked.
9736  */
9737 static int
9738 bbr_do_fin_wait_2(struct mbuf *m, struct tcphdr *th, struct socket *so,
9739     struct tcpcb *tp, struct tcpopt *to, int32_t drop_hdrlen, int32_t tlen,
9740     uint32_t tiwin, int32_t thflags, int32_t nxt_pkt, uint8_t iptos)
9741 {
9742 	int32_t ourfinisacked = 0;
9743 	int32_t ret_val;
9744 	struct tcp_bbr *bbr;
9745 
9746 	INP_WLOCK_ASSERT(tptoinpcb(tp));
9747 
9748 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
9749 	ctf_calc_rwin(so, tp);
9750 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
9751 	if ((thflags & TH_RST) ||
9752 	    (tp->t_fin_is_rst && (thflags & TH_FIN)))
9753 		return (ctf_process_rst(m, th, so, tp));
9754 
9755 	/*
9756 	 * RFC5961 Section 4.2 Send challenge ACK for any SYN in
9757 	 * synchronized state.
9758 	 */
9759 	if (thflags & TH_SYN) {
9760 		ctf_challenge_ack(m, th, tp, iptos, &ret_val);
9761 		return (ret_val);
9762 	}
9763 	/*
9764 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment and
9765 	 * it's less than ts_recent, drop it.
9766 	 */
9767 	if ((to->to_flags & TOF_TS) != 0 && tp->ts_recent &&
9768 	    TSTMP_LT(to->to_tsval, tp->ts_recent)) {
9769 		if (ctf_ts_check(m, th, tp, tlen, thflags, &ret_val))
9770 			return (ret_val);
9771 	}
9772 	if (ctf_drop_checks(to, m, th, tp, &tlen, &thflags, &drop_hdrlen, &ret_val)) {
9773 		return (ret_val);
9774 	}
9775 	/*
9776 	 * If new data are received on a connection after the user processes
9777 	 * are gone, then we may RST the other end depending on the outcome
9778 	 * of bbr_check_data_after_close.
9779 	 * We call a new function now so we might continue and setup
9780 	 * to reset at all data being ack'd.
9781 	 */
9782 	if ((tp->t_flags & TF_CLOSED) && tlen &&
9783 	    bbr_check_data_after_close(m, bbr, tp, &tlen, th, so))
9784 		return (1);
9785 	/*
9786 	 * If last ACK falls within this segment's sequence numbers, record
9787 	 * its timestamp. NOTE: 1) That the test incorporates suggestions
9788 	 * from the latest proposal of the tcplw@cray.com list (Braden
9789 	 * 1993/04/26). 2) That updating only on newer timestamps interferes
9790 	 * with our earlier PAWS tests, so this check should be solely
9791 	 * predicated on the sequence space of this segment. 3) That we
9792 	 * modify the segment boundary check to be Last.ACK.Sent <= SEG.SEQ
9793 	 * + SEG.Len  instead of RFC1323's Last.ACK.Sent < SEG.SEQ +
9794 	 * SEG.Len, This modified check allows us to overcome RFC1323's
9795 	 * limitations as described in Stevens TCP/IP Illustrated Vol. 2
9796 	 * p.869. In such cases, we can still calculate the RTT correctly
9797 	 * when RCV.NXT == Last.ACK.Sent.
9798 	 */
9799 	if ((to->to_flags & TOF_TS) != 0 &&
9800 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
9801 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
9802 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
9803 		tp->ts_recent_age = tcp_tv_to_mssectick(&bbr->rc_tv);
9804 		tp->ts_recent = to->to_tsval;
9805 	}
9806 	/*
9807 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN flag
9808 	 * is on (half-synchronized state), then queue data for later
9809 	 * processing; else drop segment and return.
9810 	 */
9811 	if ((thflags & TH_ACK) == 0) {
9812 		if (tp->t_flags & TF_NEEDSYN) {
9813 			return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9814 			    tiwin, thflags, nxt_pkt));
9815 		} else if (tp->t_flags & TF_ACKNOW) {
9816 			ctf_do_dropafterack(m, tp, th, thflags, tlen, &ret_val);
9817 			bbr->r_wanted_output = 1;
9818 			return (ret_val);
9819 		} else {
9820 			ctf_do_drop(m, NULL);
9821 			return (0);
9822 		}
9823 	}
9824 	/*
9825 	 * Ack processing.
9826 	 */
9827 	if (bbr_process_ack(m, th, so, tp, to, tiwin, tlen, &ourfinisacked, thflags, &ret_val)) {
9828 		return (ret_val);
9829 	}
9830 	if (sbavail(&so->so_snd)) {
9831 		if (ctf_progress_timeout_check(tp, true)) {
9832 			bbr_log_progress_event(bbr, tp, tick, PROGRESS_DROP, __LINE__);
9833 			ctf_do_dropwithreset_conn(m, tp, th, BANDLIM_RST_OPENPORT, tlen);
9834 			return (1);
9835 		}
9836 	}
9837 	return (bbr_process_data(m, th, so, tp, drop_hdrlen, tlen,
9838 	    tiwin, thflags, nxt_pkt));
9839 }
9840 
9841 static void
9842 bbr_stop_all_timers(struct tcpcb *tp, struct tcp_bbr *bbr)
9843 {
9844 	/*
9845 	 * Assure no timers are running.
9846 	 */
9847 	if (tcp_timer_active(tp, TT_PERSIST)) {
9848 		/* We enter in persists, set the flag appropriately */
9849 		bbr->rc_in_persist = 1;
9850 	}
9851 	if (tcp_in_hpts(bbr->rc_tp)) {
9852 		tcp_hpts_remove(bbr->rc_tp);
9853 	}
9854 }
9855 
9856 static void
9857 bbr_google_mode_on(struct tcp_bbr *bbr)
9858 {
9859 	bbr->rc_use_google = 1;
9860 	bbr->rc_no_pacing = 0;
9861 	bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9862 	bbr->r_use_policer = bbr_policer_detection_enabled;
9863 	bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
9864 	bbr->bbr_use_rack_cheat = 0;
9865 	bbr->r_ctl.rc_incr_tmrs = 0;
9866 	bbr->r_ctl.rc_inc_tcp_oh = 0;
9867 	bbr->r_ctl.rc_inc_ip_oh = 0;
9868 	bbr->r_ctl.rc_inc_enet_oh = 0;
9869 	reset_time(&bbr->r_ctl.rc_delrate,
9870 		   BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
9871 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9872 			 (11 * USECS_IN_SECOND));
9873 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9874 }
9875 
9876 static void
9877 bbr_google_mode_off(struct tcp_bbr *bbr)
9878 {
9879 	bbr->rc_use_google = 0;
9880 	bbr->r_ctl.bbr_google_discount = 0;
9881 	bbr->no_pacing_until = bbr_no_pacing_until;
9882 	bbr->r_use_policer = 0;
9883 	if (bbr->no_pacing_until)
9884 		bbr->rc_no_pacing = 1;
9885 	else
9886 		bbr->rc_no_pacing = 0;
9887 	if (bbr_use_rack_resend_cheat)
9888 		bbr->bbr_use_rack_cheat = 1;
9889 	else
9890 		bbr->bbr_use_rack_cheat = 0;
9891 	if (bbr_incr_timers)
9892 		bbr->r_ctl.rc_incr_tmrs = 1;
9893 	else
9894 		bbr->r_ctl.rc_incr_tmrs = 0;
9895 	if (bbr_include_tcp_oh)
9896 		bbr->r_ctl.rc_inc_tcp_oh = 1;
9897 	else
9898 		bbr->r_ctl.rc_inc_tcp_oh = 0;
9899 	if (bbr_include_ip_oh)
9900 		bbr->r_ctl.rc_inc_ip_oh = 1;
9901 	else
9902 		bbr->r_ctl.rc_inc_ip_oh = 0;
9903 	if (bbr_include_enet_oh)
9904 		bbr->r_ctl.rc_inc_enet_oh = 1;
9905 	else
9906 		bbr->r_ctl.rc_inc_enet_oh = 0;
9907 	bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
9908 	reset_time(&bbr->r_ctl.rc_delrate,
9909 		   bbr_num_pktepo_for_del_limit);
9910 	reset_time_small(&bbr->r_ctl.rc_rttprop,
9911 			 (bbr_filter_len_sec * USECS_IN_SECOND));
9912 	tcp_bbr_tso_size_check(bbr, tcp_get_usecs(&bbr->rc_tv));
9913 }
9914 /*
9915  * Return 0 on success, non-zero on failure
9916  * which indicates the error (usually no memory).
9917  */
9918 static int
9919 bbr_init(struct tcpcb *tp, void **ptr)
9920 {
9921 	struct inpcb *inp = tptoinpcb(tp);
9922 	struct tcp_bbr *bbr = NULL;
9923 	uint32_t cts;
9924 
9925 	tcp_hpts_init(tp);
9926 
9927 	*ptr = uma_zalloc(bbr_pcb_zone, (M_NOWAIT | M_ZERO));
9928 	if (*ptr == NULL) {
9929 		/*
9930 		 * We need to allocate memory but cant. The INP and INP_INFO
9931 		 * locks and they are recursive (happens during setup. So a
9932 		 * scheme to drop the locks fails :(
9933 		 *
9934 		 */
9935 		return (ENOMEM);
9936 	}
9937 	bbr = (struct tcp_bbr *)*ptr;
9938 	bbr->rtt_valid = 0;
9939 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
9940 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
9941 	/* Take off any undesired flags */
9942 	tp->t_flags2 &= ~TF2_MBUF_QUEUE_READY;
9943 	tp->t_flags2 &= ~TF2_DONT_SACK_QUEUE;
9944 	tp->t_flags2 &= ~TF2_MBUF_ACKCMP;
9945 	tp->t_flags2 &= ~TF2_MBUF_L_ACKS;
9946 
9947 	TAILQ_INIT(&bbr->r_ctl.rc_map);
9948 	TAILQ_INIT(&bbr->r_ctl.rc_free);
9949 	TAILQ_INIT(&bbr->r_ctl.rc_tmap);
9950 	bbr->rc_tp = tp;
9951 	bbr->rc_inp = inp;
9952 	cts = tcp_get_usecs(&bbr->rc_tv);
9953 	tp->t_acktime = 0;
9954 	bbr->rc_allow_data_af_clo = bbr_ignore_data_after_close;
9955 	bbr->r_ctl.rc_reorder_fade = bbr_reorder_fade;
9956 	bbr->rc_tlp_threshold = bbr_tlp_thresh;
9957 	bbr->r_ctl.rc_reorder_shift = bbr_reorder_thresh;
9958 	bbr->r_ctl.rc_pkt_delay = bbr_pkt_delay;
9959 	bbr->r_ctl.rc_min_to = bbr_min_to;
9960 	bbr->rc_bbr_state = BBR_STATE_STARTUP;
9961 	bbr->r_ctl.bbr_lost_at_state = 0;
9962 	bbr->r_ctl.rc_lost_at_startup = 0;
9963 	bbr->rc_all_timers_stopped = 0;
9964 	bbr->r_ctl.rc_bbr_lastbtlbw = 0;
9965 	bbr->r_ctl.rc_pkt_epoch_del = 0;
9966 	bbr->r_ctl.rc_pkt_epoch = 0;
9967 	bbr->r_ctl.rc_lowest_rtt = 0xffffffff;
9968 	bbr->r_ctl.rc_bbr_hptsi_gain = bbr_high_gain;
9969 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
9970 	bbr->r_ctl.rc_went_idle_time = cts;
9971 	bbr->rc_pacer_started = cts;
9972 	bbr->r_ctl.rc_pkt_epoch_time = cts;
9973 	bbr->r_ctl.rc_rcvtime = cts;
9974 	bbr->r_ctl.rc_bbr_state_time = cts;
9975 	bbr->r_ctl.rc_del_time = cts;
9976 	bbr->r_ctl.rc_tlp_rxt_last_time = cts;
9977 	bbr->r_ctl.last_in_probertt = cts;
9978 	bbr->skip_gain = 0;
9979 	bbr->gain_is_limited = 0;
9980 	bbr->no_pacing_until = bbr_no_pacing_until;
9981 	if (bbr->no_pacing_until)
9982 		bbr->rc_no_pacing = 1;
9983 	if (bbr_use_google_algo) {
9984 		bbr->rc_no_pacing = 0;
9985 		bbr->rc_use_google = 1;
9986 		bbr->r_ctl.bbr_google_discount = bbr_google_discount;
9987 		bbr->r_use_policer = bbr_policer_detection_enabled;
9988 	} else {
9989 		bbr->rc_use_google = 0;
9990 		bbr->r_ctl.bbr_google_discount = 0;
9991 		bbr->r_use_policer = 0;
9992 	}
9993 	if (bbr_ts_limiting)
9994 		bbr->rc_use_ts_limit = 1;
9995 	else
9996 		bbr->rc_use_ts_limit = 0;
9997 	if (bbr_ts_can_raise)
9998 		bbr->ts_can_raise = 1;
9999 	else
10000 		bbr->ts_can_raise = 0;
10001 	if (V_tcp_delack_enabled == 1)
10002 		tp->t_delayed_ack = 2;
10003 	else if (V_tcp_delack_enabled == 0)
10004 		tp->t_delayed_ack = 0;
10005 	else if (V_tcp_delack_enabled < 100)
10006 		tp->t_delayed_ack = V_tcp_delack_enabled;
10007 	else
10008 		tp->t_delayed_ack = 2;
10009 	if (bbr->rc_use_google == 0)
10010 		bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10011 	else
10012 		bbr->r_ctl.rc_probertt_int = (USECS_IN_SECOND * 10);
10013 	bbr->r_ctl.rc_min_rto_ms = bbr_rto_min_ms;
10014 	bbr->rc_max_rto_sec = bbr_rto_max_sec;
10015 	bbr->rc_init_win = bbr_def_init_win;
10016 	if (tp->t_flags & TF_REQ_TSTMP)
10017 		bbr->rc_last_options = TCP_TS_OVERHEAD;
10018 	bbr->r_ctl.rc_pace_max_segs = tp->t_maxseg - bbr->rc_last_options;
10019 	bbr->r_ctl.rc_high_rwnd = tp->snd_wnd;
10020 	bbr->r_init_rtt = 1;
10021 
10022 	counter_u64_add(bbr_flows_nohdwr_pacing, 1);
10023 	if (bbr_allow_hdwr_pacing)
10024 		bbr->bbr_hdw_pace_ena = 1;
10025 	else
10026 		bbr->bbr_hdw_pace_ena = 0;
10027 	if (bbr_sends_full_iwnd)
10028 		bbr->bbr_init_win_cheat = 1;
10029 	else
10030 		bbr->bbr_init_win_cheat = 0;
10031 	bbr->r_ctl.bbr_utter_max = bbr_hptsi_utter_max;
10032 	bbr->r_ctl.rc_drain_pg = bbr_drain_gain;
10033 	bbr->r_ctl.rc_startup_pg = bbr_high_gain;
10034 	bbr->rc_loss_exit = bbr_exit_startup_at_loss;
10035 	bbr->r_ctl.bbr_rttprobe_gain_val = bbr_rttprobe_gain;
10036 	bbr->r_ctl.bbr_hptsi_per_second = bbr_hptsi_per_second;
10037 	bbr->r_ctl.bbr_hptsi_segments_delay_tar = bbr_hptsi_segments_delay_tar;
10038 	bbr->r_ctl.bbr_hptsi_segments_max = bbr_hptsi_segments_max;
10039 	bbr->r_ctl.bbr_hptsi_segments_floor = bbr_hptsi_segments_floor;
10040 	bbr->r_ctl.bbr_hptsi_bytes_min = bbr_hptsi_bytes_min;
10041 	bbr->r_ctl.bbr_cross_over = bbr_cross_over;
10042 	bbr->r_ctl.rc_rtt_shrinks = cts;
10043 	if (bbr->rc_use_google) {
10044 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10045 				  FILTER_TYPE_MAX,
10046 				  BBR_NUM_RTTS_FOR_GOOG_DEL_LIMIT);
10047 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10048 					FILTER_TYPE_MIN, (11 * USECS_IN_SECOND));
10049 	} else {
10050 		setup_time_filter(&bbr->r_ctl.rc_delrate,
10051 				  FILTER_TYPE_MAX,
10052 				  bbr_num_pktepo_for_del_limit);
10053 		setup_time_filter_small(&bbr->r_ctl.rc_rttprop,
10054 					FILTER_TYPE_MIN, (bbr_filter_len_sec * USECS_IN_SECOND));
10055 	}
10056 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_INIT, 0);
10057 	if (bbr_uses_idle_restart)
10058 		bbr->rc_use_idle_restart = 1;
10059 	else
10060 		bbr->rc_use_idle_restart = 0;
10061 	bbr->r_ctl.rc_bbr_cur_del_rate = 0;
10062 	bbr->r_ctl.rc_initial_hptsi_bw = bbr_initial_bw_bps;
10063 	if (bbr_resends_use_tso)
10064 		bbr->rc_resends_use_tso = 1;
10065 	if (tp->snd_una != tp->snd_max) {
10066 		/* Create a send map for the current outstanding data */
10067 		struct bbr_sendmap *rsm;
10068 
10069 		rsm = bbr_alloc(bbr);
10070 		if (rsm == NULL) {
10071 			uma_zfree(bbr_pcb_zone, *ptr);
10072 			*ptr = NULL;
10073 			return (ENOMEM);
10074 		}
10075 		rsm->r_rtt_not_allowed = 1;
10076 		rsm->r_tim_lastsent[0] = cts;
10077 		rsm->r_rtr_cnt = 1;
10078 		rsm->r_rtr_bytes = 0;
10079 		rsm->r_start = tp->snd_una;
10080 		rsm->r_end = tp->snd_max;
10081 		rsm->r_dupack = 0;
10082 		rsm->r_delivered = bbr->r_ctl.rc_delivered;
10083 		rsm->r_ts_valid = 0;
10084 		rsm->r_del_ack_ts = tp->ts_recent;
10085 		rsm->r_del_time = cts;
10086 		if (bbr->r_ctl.r_app_limited_until)
10087 			rsm->r_app_limited = 1;
10088 		else
10089 			rsm->r_app_limited = 0;
10090 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_map, rsm, r_next);
10091 		TAILQ_INSERT_TAIL(&bbr->r_ctl.rc_tmap, rsm, r_tnext);
10092 		rsm->r_in_tmap = 1;
10093 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW)
10094 			rsm->r_bbr_state = bbr_state_val(bbr);
10095 		else
10096 			rsm->r_bbr_state = 8;
10097 	}
10098 	if (bbr_use_rack_resend_cheat && (bbr->rc_use_google == 0))
10099 		bbr->bbr_use_rack_cheat = 1;
10100 	if (bbr_incr_timers && (bbr->rc_use_google == 0))
10101 		bbr->r_ctl.rc_incr_tmrs = 1;
10102 	if (bbr_include_tcp_oh && (bbr->rc_use_google == 0))
10103 		bbr->r_ctl.rc_inc_tcp_oh = 1;
10104 	if (bbr_include_ip_oh && (bbr->rc_use_google == 0))
10105 		bbr->r_ctl.rc_inc_ip_oh = 1;
10106 	if (bbr_include_enet_oh && (bbr->rc_use_google == 0))
10107 		bbr->r_ctl.rc_inc_enet_oh = 1;
10108 
10109 	bbr_log_type_statechange(bbr, cts, __LINE__);
10110 	if (TCPS_HAVEESTABLISHED(tp->t_state) &&
10111 	    (tp->t_srtt)) {
10112 		uint32_t rtt;
10113 
10114 		rtt = (TICKS_2_USEC(tp->t_srtt) >> TCP_RTT_SHIFT);
10115 		apply_filter_min_small(&bbr->r_ctl.rc_rttprop, rtt, cts);
10116 	}
10117 	/* announce the settings and state */
10118 	bbr_log_settings_change(bbr, BBR_RECOVERY_LOWRTT);
10119 	tcp_bbr_tso_size_check(bbr, cts);
10120 	/*
10121 	 * Now call the generic function to start a timer. This will place
10122 	 * the TCB on the hptsi wheel if a timer is needed with appropriate
10123 	 * flags.
10124 	 */
10125 	bbr_stop_all_timers(tp, bbr);
10126 	/*
10127 	 * Validate the timers are not in usec, if they are convert.
10128 	 * BBR should in theory move to USEC and get rid of a
10129 	 * lot of the TICKS_2 calls.. but for now we stay
10130 	 * with tick timers.
10131 	 */
10132 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
10133 	TCPT_RANGESET(tp->t_rxtcur,
10134 	    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
10135 	    tp->t_rttmin, TCPTV_REXMTMAX);
10136 	bbr_start_hpts_timer(bbr, tp, cts, 5, 0, 0);
10137 	return (0);
10138 }
10139 
10140 /*
10141  * Return 0 if we can accept the connection. Return
10142  * non-zero if we can't handle the connection. A EAGAIN
10143  * means you need to wait until the connection is up.
10144  * a EADDRNOTAVAIL means we can never handle the connection
10145  * (no SACK).
10146  */
10147 static int
10148 bbr_handoff_ok(struct tcpcb *tp)
10149 {
10150 	if ((tp->t_state == TCPS_CLOSED) ||
10151 	    (tp->t_state == TCPS_LISTEN)) {
10152 		/* Sure no problem though it may not stick */
10153 		return (0);
10154 	}
10155 	if ((tp->t_state == TCPS_SYN_SENT) ||
10156 	    (tp->t_state == TCPS_SYN_RECEIVED)) {
10157 		/*
10158 		 * We really don't know you have to get to ESTAB or beyond
10159 		 * to tell.
10160 		 */
10161 		return (EAGAIN);
10162 	}
10163 	if (tp->t_flags & TF_SENTFIN)
10164 		return (EINVAL);
10165 	if ((tp->t_flags & TF_SACK_PERMIT) || bbr_sack_not_required) {
10166 		return (0);
10167 	}
10168 	/*
10169 	 * If we reach here we don't do SACK on this connection so we can
10170 	 * never do rack.
10171 	 */
10172 	return (EINVAL);
10173 }
10174 
10175 static void
10176 bbr_fini(struct tcpcb *tp, int32_t tcb_is_purged)
10177 {
10178 	if (tp->t_fb_ptr) {
10179 		uint32_t calc;
10180 		struct tcp_bbr *bbr;
10181 		struct bbr_sendmap *rsm;
10182 
10183 		bbr = (struct tcp_bbr *)tp->t_fb_ptr;
10184 		if (bbr->r_ctl.crte)
10185 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
10186 		bbr_log_flowend(bbr);
10187 		bbr->rc_tp = NULL;
10188 		if (bbr->bbr_hdrw_pacing)
10189 			counter_u64_add(bbr_flows_whdwr_pacing, -1);
10190 		else
10191 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
10192 		if (bbr->r_ctl.crte != NULL) {
10193 			tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
10194 			bbr->r_ctl.crte = NULL;
10195 		}
10196 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10197 		while (rsm) {
10198 			TAILQ_REMOVE(&bbr->r_ctl.rc_map, rsm, r_next);
10199 			uma_zfree(bbr_zone, rsm);
10200 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_map);
10201 		}
10202 		rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10203 		while (rsm) {
10204 			TAILQ_REMOVE(&bbr->r_ctl.rc_free, rsm, r_next);
10205 			uma_zfree(bbr_zone, rsm);
10206 			rsm = TAILQ_FIRST(&bbr->r_ctl.rc_free);
10207 		}
10208 		calc = bbr->r_ctl.rc_high_rwnd - bbr->r_ctl.rc_init_rwnd;
10209 		if (calc > (bbr->r_ctl.rc_init_rwnd / 10))
10210 			BBR_STAT_INC(bbr_dynamic_rwnd);
10211 		else
10212 			BBR_STAT_INC(bbr_static_rwnd);
10213 		bbr->r_ctl.rc_free_cnt = 0;
10214 		uma_zfree(bbr_pcb_zone, tp->t_fb_ptr);
10215 		tp->t_fb_ptr = NULL;
10216 	}
10217 	/* Make sure snd_nxt is correctly set */
10218 	tp->snd_nxt = tp->snd_max;
10219 }
10220 
10221 static void
10222 bbr_set_state(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t win)
10223 {
10224 	switch (tp->t_state) {
10225 	case TCPS_SYN_SENT:
10226 		bbr->r_state = TCPS_SYN_SENT;
10227 		bbr->r_substate = bbr_do_syn_sent;
10228 		break;
10229 	case TCPS_SYN_RECEIVED:
10230 		bbr->r_state = TCPS_SYN_RECEIVED;
10231 		bbr->r_substate = bbr_do_syn_recv;
10232 		break;
10233 	case TCPS_ESTABLISHED:
10234 		bbr->r_ctl.rc_init_rwnd = max(win, bbr->rc_tp->snd_wnd);
10235 		bbr->r_state = TCPS_ESTABLISHED;
10236 		bbr->r_substate = bbr_do_established;
10237 		break;
10238 	case TCPS_CLOSE_WAIT:
10239 		bbr->r_state = TCPS_CLOSE_WAIT;
10240 		bbr->r_substate = bbr_do_close_wait;
10241 		break;
10242 	case TCPS_FIN_WAIT_1:
10243 		bbr->r_state = TCPS_FIN_WAIT_1;
10244 		bbr->r_substate = bbr_do_fin_wait_1;
10245 		break;
10246 	case TCPS_CLOSING:
10247 		bbr->r_state = TCPS_CLOSING;
10248 		bbr->r_substate = bbr_do_closing;
10249 		break;
10250 	case TCPS_LAST_ACK:
10251 		bbr->r_state = TCPS_LAST_ACK;
10252 		bbr->r_substate = bbr_do_lastack;
10253 		break;
10254 	case TCPS_FIN_WAIT_2:
10255 		bbr->r_state = TCPS_FIN_WAIT_2;
10256 		bbr->r_substate = bbr_do_fin_wait_2;
10257 		break;
10258 	case TCPS_LISTEN:
10259 	case TCPS_CLOSED:
10260 	case TCPS_TIME_WAIT:
10261 	default:
10262 		break;
10263 	};
10264 }
10265 
10266 static void
10267 bbr_substate_change(struct tcp_bbr *bbr, uint32_t cts, int32_t line, int dolog)
10268 {
10269 	/*
10270 	 * Now what state are we going into now? Is there adjustments
10271 	 * needed?
10272 	 */
10273 	int32_t old_state;
10274 
10275 	old_state = bbr_state_val(bbr);
10276 	if (bbr_state_val(bbr) == BBR_SUB_LEVEL1) {
10277 		/* Save the lowest srtt we saw in our end of the sub-state */
10278 		bbr->rc_hit_state_1 = 0;
10279 		if (bbr->r_ctl.bbr_smallest_srtt_this_state != 0xffffffff)
10280 			bbr->r_ctl.bbr_smallest_srtt_state2 = bbr->r_ctl.bbr_smallest_srtt_this_state;
10281 	}
10282 	bbr->rc_bbr_substate++;
10283 	if (bbr->rc_bbr_substate >= BBR_SUBSTATE_COUNT) {
10284 		/* Cycle back to first state-> gain */
10285 		bbr->rc_bbr_substate = 0;
10286 	}
10287 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10288 		/*
10289 		 * We enter the gain(5/4) cycle (possibly less if
10290 		 * shallow buffer detection is enabled)
10291 		 */
10292 		if (bbr->skip_gain) {
10293 			/*
10294 			 * Hardware pacing has set our rate to
10295 			 * the max and limited our b/w just
10296 			 * do level i.e. no gain.
10297 			 */
10298 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_LEVEL1];
10299 		} else if (bbr->gain_is_limited &&
10300 			   bbr->bbr_hdrw_pacing &&
10301 			   bbr->r_ctl.crte) {
10302 			/*
10303 			 * We can't gain above the hardware pacing
10304 			 * rate which is less than our rate + the gain
10305 			 * calculate the gain needed to reach the hardware
10306 			 * pacing rate..
10307 			 */
10308 			uint64_t bw, rate, gain_calc;
10309 
10310 			bw = bbr_get_bw(bbr);
10311 			rate = bbr->r_ctl.crte->rate;
10312 			if ((rate > bw) &&
10313 			    (((bw *  (uint64_t)bbr_hptsi_gain[BBR_SUB_GAIN]) / (uint64_t)BBR_UNIT) > rate)) {
10314 				gain_calc = (rate * BBR_UNIT) / bw;
10315 				if (gain_calc < BBR_UNIT)
10316 					gain_calc = BBR_UNIT;
10317 				bbr->r_ctl.rc_bbr_hptsi_gain = (uint16_t)gain_calc;
10318 			} else {
10319 				bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10320 			}
10321 		} else
10322 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_GAIN];
10323 		if ((bbr->rc_use_google == 0) && (bbr_gain_to_target == 0)) {
10324 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10325 		} else
10326 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10327 	} else if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10328 		bbr->rc_hit_state_1 = 1;
10329 		bbr->r_ctl.rc_exta_time_gd = 0;
10330 		bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10331 						     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10332 		if (bbr_state_drain_2_tar) {
10333 			bbr->r_ctl.rc_bbr_state_atflight = 0;
10334 		} else
10335 			bbr->r_ctl.rc_bbr_state_atflight = cts;
10336 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[BBR_SUB_DRAIN];
10337 	} else {
10338 		/* All other cycles hit here 2-7 */
10339 		if ((old_state == BBR_SUB_DRAIN) && bbr->rc_hit_state_1) {
10340 			if (bbr_sub_drain_slam_cwnd &&
10341 			    (bbr->rc_use_google == 0) &&
10342 			    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10343 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10344 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10345 			}
10346 			if ((cts - bbr->r_ctl.rc_bbr_state_time) > bbr_get_rtt(bbr, BBR_RTT_PROP))
10347 				bbr->r_ctl.rc_exta_time_gd += ((cts - bbr->r_ctl.rc_bbr_state_time) -
10348 							       bbr_get_rtt(bbr, BBR_RTT_PROP));
10349 			else
10350 				bbr->r_ctl.rc_exta_time_gd = 0;
10351 			if (bbr->r_ctl.rc_exta_time_gd) {
10352 				bbr->r_ctl.rc_level_state_extra = bbr->r_ctl.rc_exta_time_gd;
10353 				/* Now chop up the time for each state (div by 7) */
10354 				bbr->r_ctl.rc_level_state_extra /= 7;
10355 				if (bbr_rand_ot && bbr->r_ctl.rc_level_state_extra) {
10356 					/* Add a randomization */
10357 					bbr_randomize_extra_state_time(bbr);
10358 				}
10359 			}
10360 		}
10361 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10362 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_hptsi_gain[bbr_state_val(bbr)];
10363 	}
10364 	if (bbr->rc_use_google) {
10365 		bbr->r_ctl.rc_bbr_state_atflight = max(1, cts);
10366 	}
10367 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10368 	bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10369 	if (dolog)
10370 		bbr_log_type_statechange(bbr, cts, line);
10371 
10372 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10373 		uint32_t time_in;
10374 
10375 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10376 		if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
10377 			counter_u64_add(bbr_state_time[(old_state + 5)], time_in);
10378 		} else {
10379 			counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10380 		}
10381 	}
10382 	bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
10383 	bbr_set_state_target(bbr, __LINE__);
10384 	if (bbr_sub_drain_slam_cwnd &&
10385 	    (bbr->rc_use_google == 0) &&
10386 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10387 		/* Slam down the cwnd */
10388 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10389 		bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10390 		if (bbr_sub_drain_app_limit) {
10391 			/* Go app limited if we are on a long drain */
10392 			bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered +
10393 							  ctf_flight_size(bbr->rc_tp,
10394 							      (bbr->r_ctl.rc_sacked +
10395 							       bbr->r_ctl.rc_lost_bytes)));
10396 		}
10397 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10398 	}
10399 	if (bbr->rc_lt_use_bw) {
10400 		/* In policed mode we clamp pacing_gain to BBR_UNIT */
10401 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10402 	}
10403 	/* Google changes TSO size every cycle */
10404 	if (bbr->rc_use_google)
10405 		tcp_bbr_tso_size_check(bbr, cts);
10406 	bbr->r_ctl.gain_epoch = cts;
10407 	bbr->r_ctl.rc_bbr_state_time = cts;
10408 	bbr->r_ctl.substate_pe = bbr->r_ctl.rc_pkt_epoch;
10409 }
10410 
10411 static void
10412 bbr_set_probebw_google_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10413 {
10414 	if ((bbr_state_val(bbr) == BBR_SUB_DRAIN) &&
10415 	    (google_allow_early_out == 1) &&
10416 	    (bbr->r_ctl.rc_flight_at_input <= bbr->r_ctl.rc_target_at_state)) {
10417 		/* We have reached out target flight size possibly early */
10418 		goto change_state;
10419 	}
10420 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10421 		return;
10422 	}
10423 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_get_rtt(bbr, BBR_RTT_PROP)) {
10424 		/*
10425 		 * Must be a rttProp movement forward before
10426 		 * we can change states.
10427 		 */
10428 		return;
10429 	}
10430 	if (bbr_state_val(bbr) == BBR_SUB_GAIN) {
10431 		/*
10432 		 * The needed time has passed but for
10433 		 * the gain cycle extra rules apply:
10434 		 * 1) If we have seen loss, we exit
10435 		 * 2) If we have not reached the target
10436 		 *    we stay in GAIN (gain-to-target).
10437 		 */
10438 		if (google_consider_lost && losses)
10439 			goto change_state;
10440 		if (bbr->r_ctl.rc_target_at_state > bbr->r_ctl.rc_flight_at_input) {
10441 			return;
10442 		}
10443 	}
10444 change_state:
10445 	/* For gain we must reach our target, all others last 1 rttProp */
10446 	bbr_substate_change(bbr, cts, __LINE__, 1);
10447 }
10448 
10449 static void
10450 bbr_set_probebw_gains(struct tcp_bbr *bbr, uint32_t cts, uint32_t losses)
10451 {
10452 	uint32_t flight, bbr_cur_cycle_time;
10453 
10454 	if (bbr->rc_use_google) {
10455 		bbr_set_probebw_google_gains(bbr, cts, losses);
10456 		return;
10457 	}
10458 	if (cts == 0) {
10459 		/*
10460 		 * Never alow cts to be 0 we
10461 		 * do this so we can judge if
10462 		 * we have set a timestamp.
10463 		 */
10464 		cts = 1;
10465 	}
10466 	if (bbr_state_is_pkt_epoch)
10467 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PKTRTT);
10468 	else
10469 		bbr_cur_cycle_time = bbr_get_rtt(bbr, BBR_RTT_PROP);
10470 
10471 	if (bbr->r_ctl.rc_bbr_state_atflight == 0) {
10472 		if (bbr_state_val(bbr) == BBR_SUB_DRAIN) {
10473 			flight = ctf_flight_size(bbr->rc_tp,
10474 				     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10475 			if (bbr_sub_drain_slam_cwnd && bbr->rc_hit_state_1) {
10476 				/* Keep it slam down */
10477 				if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state) {
10478 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10479 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10480 				}
10481 				if (bbr_sub_drain_app_limit) {
10482 					/* Go app limited if we are on a long drain */
10483 					bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.rc_delivered + flight);
10484 				}
10485 			}
10486 			if (TSTMP_GT(cts, bbr->r_ctl.gain_epoch) &&
10487 			    (((cts - bbr->r_ctl.gain_epoch) > bbr_get_rtt(bbr, BBR_RTT_PROP)) ||
10488 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
10489 				/*
10490 				 * Still here after the same time as
10491 				 * the gain. We need to drain harder
10492 				 * for the next srtt. Reduce by a set amount
10493 				 * the gain drop is capped at DRAIN states
10494 				 * value (88).
10495 				 */
10496 				bbr->r_ctl.flightsize_at_drain = flight;
10497 				if (bbr_drain_drop_mul &&
10498 				    bbr_drain_drop_div &&
10499 				    (bbr_drain_drop_mul < bbr_drain_drop_div)) {
10500 					/* Use your specific drop value (def 4/5 = 20%) */
10501 					bbr->r_ctl.rc_bbr_hptsi_gain *= bbr_drain_drop_mul;
10502 					bbr->r_ctl.rc_bbr_hptsi_gain /= bbr_drain_drop_div;
10503 				} else {
10504 					/* You get drop of 20% */
10505 					bbr->r_ctl.rc_bbr_hptsi_gain *= 4;
10506 					bbr->r_ctl.rc_bbr_hptsi_gain /= 5;
10507 				}
10508 				if (bbr->r_ctl.rc_bbr_hptsi_gain <= bbr_drain_floor) {
10509 					/* Reduce our gain again to the bottom  */
10510 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
10511 				}
10512 				bbr_log_exit_gain(bbr, cts, 4);
10513 				/*
10514 				 * Extend out so we wait another
10515 				 * epoch before dropping again.
10516 				 */
10517 				bbr->r_ctl.gain_epoch = cts;
10518 			}
10519 			if (flight <= bbr->r_ctl.rc_target_at_state) {
10520 				if (bbr_sub_drain_slam_cwnd &&
10521 				    (bbr->rc_use_google == 0) &&
10522 				    (bbr->rc_tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
10523 					bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10524 					bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10525 				}
10526 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10527 				bbr_log_exit_gain(bbr, cts, 3);
10528 			}
10529 		} else {
10530 			/* Its a gain  */
10531 			if (bbr->r_ctl.rc_lost > bbr->r_ctl.bbr_lost_at_state) {
10532 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10533 				goto change_state;
10534 			}
10535 			if ((ctf_outstanding(bbr->rc_tp) >= bbr->r_ctl.rc_target_at_state) ||
10536 			    ((ctf_outstanding(bbr->rc_tp) +  bbr->rc_tp->t_maxseg - 1) >=
10537 			     bbr->rc_tp->snd_wnd)) {
10538 				bbr->r_ctl.rc_bbr_state_atflight = max(cts, 1);
10539 				bbr_log_exit_gain(bbr, cts, 2);
10540 			}
10541 		}
10542 		/**
10543 		 * We fall through and return always one of two things has
10544 		 * occurred.
10545 		 * 1) We are still not at target
10546 		 *    <or>
10547 		 * 2) We reached the target and set rc_bbr_state_atflight
10548 		 *    which means we no longer hit this block
10549 		 *    next time we are called.
10550 		 */
10551 		return;
10552 	}
10553 change_state:
10554 	if (TSTMP_LT(cts, bbr->r_ctl.rc_bbr_state_time))
10555 		return;
10556 	if ((cts - bbr->r_ctl.rc_bbr_state_time) < bbr_cur_cycle_time) {
10557 		/* Less than a full time-period has passed */
10558 		return;
10559 	}
10560 	if (bbr->r_ctl.rc_level_state_extra &&
10561 	    (bbr_state_val(bbr) > BBR_SUB_DRAIN) &&
10562 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10563 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10564 		/* Less than a full time-period + extra has passed */
10565 		return;
10566 	}
10567 	if (bbr_gain_gets_extra_too &&
10568 	    bbr->r_ctl.rc_level_state_extra &&
10569 	    (bbr_state_val(bbr) == BBR_SUB_GAIN) &&
10570 	    ((cts - bbr->r_ctl.rc_bbr_state_time) <
10571 	     (bbr_cur_cycle_time + bbr->r_ctl.rc_level_state_extra))) {
10572 		/* Less than a full time-period + extra has passed */
10573 		return;
10574 	}
10575 	bbr_substate_change(bbr, cts, __LINE__, 1);
10576 }
10577 
10578 static uint32_t
10579 bbr_get_a_state_target(struct tcp_bbr *bbr, uint32_t gain)
10580 {
10581 	uint32_t mss, tar;
10582 
10583 	if (bbr->rc_use_google) {
10584 		/* Google just uses the cwnd target */
10585 		tar = bbr_get_target_cwnd(bbr, bbr_get_bw(bbr), gain);
10586 	} else {
10587 		mss = min((bbr->rc_tp->t_maxseg - bbr->rc_last_options),
10588 			  bbr->r_ctl.rc_pace_max_segs);
10589 		/* Get the base cwnd with gain rounded to a mss */
10590 		tar = roundup(bbr_get_raw_target_cwnd(bbr, bbr_get_bw(bbr),
10591 						      gain), mss);
10592 		/* Make sure it is within our min */
10593 		if (tar < get_min_cwnd(bbr))
10594 			return (get_min_cwnd(bbr));
10595 	}
10596 	return (tar);
10597 }
10598 
10599 static void
10600 bbr_set_state_target(struct tcp_bbr *bbr, int line)
10601 {
10602 	uint32_t tar, meth;
10603 
10604 	if ((bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) &&
10605 	    ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google)) {
10606 		/* Special case using old probe-rtt method */
10607 		tar = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10608 		meth = 1;
10609 	} else {
10610 		/* Non-probe-rtt case and reduced probe-rtt  */
10611 		if ((bbr->rc_bbr_state == BBR_STATE_PROBE_BW) &&
10612 		    (bbr->r_ctl.rc_bbr_hptsi_gain > BBR_UNIT)) {
10613 			/* For gain cycle we use the hptsi gain */
10614 			tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10615 			meth = 2;
10616 		} else if ((bbr_target_is_bbunit) || bbr->rc_use_google) {
10617 			/*
10618 			 * If configured, or for google all other states
10619 			 * get BBR_UNIT.
10620 			 */
10621 			tar = bbr_get_a_state_target(bbr, BBR_UNIT);
10622 			meth = 3;
10623 		} else {
10624 			/*
10625 			 * Or we set a target based on the pacing gain
10626 			 * for non-google mode and default (non-configured).
10627 			 * Note we don't set a target goal below drain (192).
10628 			 */
10629 			if (bbr->r_ctl.rc_bbr_hptsi_gain < bbr_hptsi_gain[BBR_SUB_DRAIN])  {
10630 				tar = bbr_get_a_state_target(bbr, bbr_hptsi_gain[BBR_SUB_DRAIN]);
10631 				meth = 4;
10632 			} else {
10633 				tar = bbr_get_a_state_target(bbr, bbr->r_ctl.rc_bbr_hptsi_gain);
10634 				meth = 5;
10635 			}
10636 		}
10637 	}
10638 	bbr_log_set_of_state_target(bbr, tar, line, meth);
10639 	bbr->r_ctl.rc_target_at_state = tar;
10640 }
10641 
10642 static void
10643 bbr_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts, int32_t line)
10644 {
10645 	/* Change to probe_rtt */
10646 	uint32_t time_in;
10647 
10648 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10649 	bbr->r_ctl.flightsize_at_drain = ctf_flight_size(bbr->rc_tp,
10650 					     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
10651 	bbr->r_ctl.r_app_limited_until = (bbr->r_ctl.flightsize_at_drain
10652 					  + bbr->r_ctl.rc_delivered);
10653 	/* Setup so we force feed the filter */
10654 	if (bbr->rc_use_google || bbr_probertt_sets_rtt)
10655 		bbr->rc_prtt_set_ts = 1;
10656 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10657 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10658 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10659 	}
10660 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_ENTERPROBE, 0);
10661 	bbr->r_ctl.rc_rtt_shrinks = cts;
10662 	bbr->r_ctl.last_in_probertt = cts;
10663 	bbr->r_ctl.rc_probertt_srttchktim = cts;
10664 	bbr->r_ctl.rc_bbr_state_time = cts;
10665 	bbr->rc_bbr_state = BBR_STATE_PROBE_RTT;
10666 	/* We need to force the filter to update */
10667 
10668 	if ((bbr_sub_drain_slam_cwnd) &&
10669 	    bbr->rc_hit_state_1 &&
10670 	    (bbr->rc_use_google == 0) &&
10671 	    (bbr_state_val(bbr) == BBR_SUB_DRAIN)) {
10672 		if (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_saved_cwnd)
10673 			bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10674 	} else
10675 		bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
10676 	/* Update the lost */
10677 	bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10678 	if ((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google){
10679 		/* Set to the non-configurable default of 4 (PROBE_RTT_MIN)  */
10680 		bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
10681 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10682 		bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
10683 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10684 		bbr_log_set_of_state_target(bbr, bbr->rc_tp->snd_cwnd, __LINE__, 6);
10685 		bbr->r_ctl.rc_target_at_state = bbr->rc_tp->snd_cwnd;
10686 	} else {
10687 		/*
10688 		 * We bring it down slowly by using a hptsi gain that is
10689 		 * probably 75%. This will slowly float down our outstanding
10690 		 * without tampering with the cwnd.
10691 		 */
10692 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
10693 		bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
10694 		bbr_set_state_target(bbr, __LINE__);
10695 		if (bbr_prtt_slam_cwnd &&
10696 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
10697 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
10698 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10699 		}
10700 	}
10701 	if (ctf_flight_size(bbr->rc_tp,
10702 		(bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
10703 	    bbr->r_ctl.rc_target_at_state) {
10704 		/* We are at target */
10705 		bbr->r_ctl.rc_bbr_enters_probertt = cts;
10706 	} else {
10707 		/* We need to come down to reach target before our time begins */
10708 		bbr->r_ctl.rc_bbr_enters_probertt = 0;
10709 	}
10710 	bbr->r_ctl.rc_pe_of_prtt = bbr->r_ctl.rc_pkt_epoch;
10711 	BBR_STAT_INC(bbr_enter_probertt);
10712 	bbr_log_exit_gain(bbr, cts, 0);
10713 	bbr_log_type_statechange(bbr, cts, line);
10714 }
10715 
10716 static void
10717 bbr_check_probe_rtt_limits(struct tcp_bbr *bbr, uint32_t cts)
10718 {
10719 	/*
10720 	 * Sanity check on probe-rtt intervals.
10721 	 * In crazy situations where we are competing
10722 	 * against new-reno flows with huge buffers
10723 	 * our rtt-prop interval could come to dominate
10724 	 * things if we can't get through a full set
10725 	 * of cycles, we need to adjust it.
10726 	 */
10727 	if (bbr_can_adjust_probertt &&
10728 	    (bbr->rc_use_google == 0)) {
10729 		uint16_t val = 0;
10730 		uint32_t cur_rttp, fval, newval, baseval;
10731 
10732 		/* Are we to small and go into probe-rtt to often? */
10733 		baseval = (bbr_get_rtt(bbr, BBR_RTT_PROP) * (BBR_SUBSTATE_COUNT + 1));
10734 		cur_rttp = roundup(baseval, USECS_IN_SECOND);
10735 		fval = bbr_filter_len_sec * USECS_IN_SECOND;
10736 		if (bbr_is_ratio == 0) {
10737 			if (fval > bbr_rtt_probe_limit)
10738 				newval = cur_rttp + (fval - bbr_rtt_probe_limit);
10739 			else
10740 				newval = cur_rttp;
10741 		} else {
10742 			int mul;
10743 
10744 			mul = fval / bbr_rtt_probe_limit;
10745 			newval = cur_rttp * mul;
10746 		}
10747 		if (cur_rttp > 	bbr->r_ctl.rc_probertt_int) {
10748 			bbr->r_ctl.rc_probertt_int = cur_rttp;
10749 			reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10750 			val = 1;
10751 		} else {
10752 			/*
10753 			 * No adjustments were made
10754 			 * do we need to shrink it?
10755 			 */
10756 			if (bbr->r_ctl.rc_probertt_int > bbr_rtt_probe_limit) {
10757 				if (cur_rttp <= bbr_rtt_probe_limit) {
10758 					/*
10759 					 * Things have calmed down lets
10760 					 * shrink all the way to default
10761 					 */
10762 					bbr->r_ctl.rc_probertt_int = bbr_rtt_probe_limit;
10763 					reset_time_small(&bbr->r_ctl.rc_rttprop,
10764 							 (bbr_filter_len_sec * USECS_IN_SECOND));
10765 					cur_rttp = bbr_rtt_probe_limit;
10766 					newval = (bbr_filter_len_sec * USECS_IN_SECOND);
10767 					val = 2;
10768 				} else {
10769 					/*
10770 					 * Well does some adjustment make sense?
10771 					 */
10772 					if (cur_rttp < bbr->r_ctl.rc_probertt_int) {
10773 						/* We can reduce interval time some */
10774 						bbr->r_ctl.rc_probertt_int = cur_rttp;
10775 						reset_time_small(&bbr->r_ctl.rc_rttprop, newval);
10776 						val = 3;
10777 					}
10778 				}
10779 			}
10780 		}
10781 		if (val)
10782 			bbr_log_rtt_shrinks(bbr, cts, cur_rttp, newval, __LINE__, BBR_RTTS_RESETS_VALUES, val);
10783 	}
10784 }
10785 
10786 static void
10787 bbr_exit_probe_rtt(struct tcpcb *tp, struct tcp_bbr *bbr, uint32_t cts)
10788 {
10789 	/* Exit probe-rtt */
10790 
10791 	if (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd) {
10792 		tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
10793 		bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
10794 	}
10795 	bbr_log_exit_gain(bbr, cts, 1);
10796 	bbr->rc_hit_state_1 = 0;
10797 	bbr->r_ctl.rc_rtt_shrinks = cts;
10798 	bbr->r_ctl.last_in_probertt = cts;
10799 	bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_RTTPROBE, 0);
10800 	bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
10801 	bbr->r_ctl.r_app_limited_until = (ctf_flight_size(tp,
10802 					      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
10803 					  bbr->r_ctl.rc_delivered);
10804 	if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
10805 		uint32_t time_in;
10806 
10807 		time_in = cts - bbr->r_ctl.rc_bbr_state_time;
10808 		counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
10809 	}
10810 	if (bbr->rc_filled_pipe) {
10811 		/* Switch to probe_bw */
10812 		bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
10813 		bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
10814 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr_cwnd_gain;
10815 		bbr_substate_change(bbr, cts, __LINE__, 0);
10816 		bbr_log_type_statechange(bbr, cts, __LINE__);
10817 	} else {
10818 		/* Back to startup */
10819 		bbr->rc_bbr_state = BBR_STATE_STARTUP;
10820 		bbr->r_ctl.rc_bbr_state_time = cts;
10821 		/*
10822 		 * We don't want to give a complete free 3
10823 		 * measurements until we exit, so we use
10824 		 * the number of pe's we were in probe-rtt
10825 		 * to add to the startup_epoch. That way
10826 		 * we will still retain the old state.
10827 		 */
10828 		bbr->r_ctl.rc_bbr_last_startup_epoch += (bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_pe_of_prtt);
10829 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10830 		/* Make sure to use the lower pg when shifting back in */
10831 		if (bbr->r_ctl.rc_lost &&
10832 		    bbr_use_lower_gain_in_startup &&
10833 		    (bbr->rc_use_google == 0))
10834 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10835 		else
10836 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_startup_pg;
10837 		bbr->r_ctl.rc_bbr_cwnd_gain = bbr->r_ctl.rc_startup_pg;
10838 		/* Probably not needed but set it anyway */
10839 		bbr_set_state_target(bbr, __LINE__);
10840 		bbr_log_type_statechange(bbr, cts, __LINE__);
10841 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10842 		    bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 0);
10843 	}
10844 	bbr_check_probe_rtt_limits(bbr, cts);
10845 }
10846 
10847 static int32_t inline
10848 bbr_should_enter_probe_rtt(struct tcp_bbr *bbr, uint32_t cts)
10849 {
10850 	if ((bbr->rc_past_init_win == 1) &&
10851 	    (bbr->rc_in_persist == 0) &&
10852 	    (bbr_calc_time(cts, bbr->r_ctl.rc_rtt_shrinks) >= bbr->r_ctl.rc_probertt_int)) {
10853 		return (1);
10854 	}
10855 	if (bbr_can_force_probertt &&
10856 	    (bbr->rc_in_persist == 0) &&
10857 	    (TSTMP_GT(cts, bbr->r_ctl.last_in_probertt)) &&
10858 	    ((cts - bbr->r_ctl.last_in_probertt) > bbr->r_ctl.rc_probertt_int)) {
10859 		return (1);
10860 	}
10861 	return (0);
10862 }
10863 
10864 static int32_t
10865 bbr_google_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t  pkt_epoch)
10866 {
10867 	uint64_t btlbw, gain;
10868 	if (pkt_epoch == 0) {
10869 		/*
10870 		 * Need to be on a pkt-epoch to continue.
10871 		 */
10872 		return (0);
10873 	}
10874 	btlbw = bbr_get_full_bw(bbr);
10875 	gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10876 		 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10877 	if (btlbw >= gain) {
10878 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10879 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10880 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10881 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10882 	}
10883 	if ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)
10884 		return (1);
10885 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10886 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
10887 	return(0);
10888 }
10889 
10890 static int32_t inline
10891 bbr_state_startup(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch)
10892 {
10893 	/* Have we gained 25% in the last 3 packet based epoch's? */
10894 	uint64_t btlbw, gain;
10895 	int do_exit;
10896 	int delta, rtt_gain;
10897 
10898 	if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
10899 	    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
10900 		/*
10901 		 * This qualifies as a RTT_PROBE session since we drop the
10902 		 * data outstanding to nothing and waited more than
10903 		 * bbr_rtt_probe_time.
10904 		 */
10905 		bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
10906 		bbr_set_reduced_rtt(bbr, cts, __LINE__);
10907 	}
10908 	if (bbr_should_enter_probe_rtt(bbr, cts)) {
10909 		bbr_enter_probe_rtt(bbr, cts, __LINE__);
10910 		return (0);
10911 	}
10912 	if (bbr->rc_use_google)
10913 		return (bbr_google_startup(bbr, cts,  pkt_epoch));
10914 
10915 	if ((bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10916 	    (bbr_use_lower_gain_in_startup)) {
10917 		/* Drop to a lower gain 1.5 x since we saw loss */
10918 		bbr->r_ctl.rc_bbr_hptsi_gain = bbr_startup_lower;
10919 	}
10920 	if (pkt_epoch == 0) {
10921 		/*
10922 		 * Need to be on a pkt-epoch to continue.
10923 		 */
10924 		return (0);
10925 	}
10926 	if (bbr_rtt_gain_thresh) {
10927 		/*
10928 		 * Do we allow a flow to stay
10929 		 * in startup with no loss and no
10930 		 * gain in rtt over a set threshold?
10931 		 */
10932 		if (bbr->r_ctl.rc_pkt_epoch_rtt &&
10933 		    bbr->r_ctl.startup_last_srtt &&
10934 		    (bbr->r_ctl.rc_pkt_epoch_rtt > bbr->r_ctl.startup_last_srtt)) {
10935 			delta = bbr->r_ctl.rc_pkt_epoch_rtt - bbr->r_ctl.startup_last_srtt;
10936 			rtt_gain = (delta * 100) / bbr->r_ctl.startup_last_srtt;
10937 		} else
10938 			rtt_gain = 0;
10939 		if ((bbr->r_ctl.startup_last_srtt == 0)  ||
10940 		    (bbr->r_ctl.rc_pkt_epoch_rtt < bbr->r_ctl.startup_last_srtt))
10941 			/* First time or new lower value */
10942 			bbr->r_ctl.startup_last_srtt = bbr->r_ctl.rc_pkt_epoch_rtt;
10943 
10944 		if ((bbr->r_ctl.rc_lost == 0) &&
10945 		    (rtt_gain < bbr_rtt_gain_thresh)) {
10946 			/*
10947 			 * No loss, and we are under
10948 			 * our gain threhold for
10949 			 * increasing RTT.
10950 			 */
10951 			if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10952 				bbr->r_ctl.rc_bbr_last_startup_epoch++;
10953 			bbr_log_startup_event(bbr, cts, rtt_gain,
10954 					      delta, bbr->r_ctl.startup_last_srtt, 10);
10955 			return (0);
10956 		}
10957 	}
10958 	if ((bbr->r_ctl.r_measurement_count == bbr->r_ctl.last_startup_measure) &&
10959 	    (bbr->r_ctl.rc_lost_at_startup == bbr->r_ctl.rc_lost) &&
10960 	    (!IN_RECOVERY(bbr->rc_tp->t_flags))) {
10961 		/*
10962 		 * We only assess if we have a new measurement when
10963 		 * we have no loss and are not in recovery.
10964 		 * Drag up by one our last_startup epoch so we will hold
10965 		 * the number of non-gain we have already accumulated.
10966 		 */
10967 		if (bbr->r_ctl.rc_bbr_last_startup_epoch < bbr->r_ctl.rc_pkt_epoch)
10968 			bbr->r_ctl.rc_bbr_last_startup_epoch++;
10969 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10970 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 9);
10971 		return (0);
10972 	}
10973 	/* Case where we reduced the lost (bad retransmit) */
10974 	if (bbr->r_ctl.rc_lost_at_startup > bbr->r_ctl.rc_lost)
10975 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10976 	bbr->r_ctl.last_startup_measure = bbr->r_ctl.r_measurement_count;
10977 	btlbw = bbr_get_full_bw(bbr);
10978 	if (bbr->r_ctl.rc_bbr_hptsi_gain == bbr_startup_lower)
10979 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10980 			 (uint64_t)bbr_low_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10981 	else
10982 		gain = ((bbr->r_ctl.rc_bbr_lastbtlbw *
10983 			 (uint64_t)bbr_start_exit) / (uint64_t)100) + bbr->r_ctl.rc_bbr_lastbtlbw;
10984 	do_exit = 0;
10985 	if (btlbw > bbr->r_ctl.rc_bbr_lastbtlbw)
10986 		bbr->r_ctl.rc_bbr_lastbtlbw = btlbw;
10987 	if (btlbw >= gain) {
10988 		bbr->r_ctl.rc_bbr_last_startup_epoch = bbr->r_ctl.rc_pkt_epoch;
10989 		/* Update the lost so we won't exit in next set of tests */
10990 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
10991 		bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
10992 				      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 3);
10993 	}
10994 	if ((bbr->rc_loss_exit &&
10995 	     (bbr->r_ctl.rc_lost > bbr->r_ctl.rc_lost_at_startup) &&
10996 	     (bbr->r_ctl.rc_pkt_epoch_loss_rate > bbr_startup_loss_thresh)) &&
10997 	    ((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS)) {
10998 		/*
10999 		 * If we had no gain,  we had loss and that loss was above
11000 		 * our threshould, the rwnd is not constrained, and we have
11001 		 * had at least 3 packet epochs exit. Note that this is
11002 		 * switched off by sysctl. Google does not do this by the
11003 		 * way.
11004 		 */
11005 		if ((ctf_flight_size(bbr->rc_tp,
11006 			 (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) +
11007 		     (2 * max(bbr->r_ctl.rc_pace_max_segs, bbr->rc_tp->t_maxseg))) <= bbr->rc_tp->snd_wnd) {
11008 			do_exit = 1;
11009 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11010 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 4);
11011 		} else {
11012 			/* Just record an updated loss value */
11013 			bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11014 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11015 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 5);
11016 		}
11017 	} else
11018 		bbr->r_ctl.rc_lost_at_startup = bbr->r_ctl.rc_lost;
11019 	if (((bbr->r_ctl.rc_pkt_epoch - bbr->r_ctl.rc_bbr_last_startup_epoch) >= BBR_STARTUP_EPOCHS) ||
11020 	    do_exit) {
11021 		/* Return 1 to exit the startup state. */
11022 		return (1);
11023 	}
11024 	/* Stay in startup */
11025 	bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11026 			      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 8);
11027 	return (0);
11028 }
11029 
11030 static void
11031 bbr_state_change(struct tcp_bbr *bbr, uint32_t cts, int32_t epoch, int32_t pkt_epoch, uint32_t losses)
11032 {
11033 	/*
11034 	 * A tick occurred in the rtt epoch do we need to do anything?
11035 	 */
11036 #ifdef BBR_INVARIANTS
11037 	if ((bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
11038 	    (bbr->rc_bbr_state != BBR_STATE_DRAIN) &&
11039 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_RTT) &&
11040 	    (bbr->rc_bbr_state != BBR_STATE_IDLE_EXIT) &&
11041 	    (bbr->rc_bbr_state != BBR_STATE_PROBE_BW)) {
11042 		/* Debug code? */
11043 		panic("Unknown BBR state %d?\n", bbr->rc_bbr_state);
11044 	}
11045 #endif
11046 	if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
11047 		/* Do we exit the startup state? */
11048 		if (bbr_state_startup(bbr, cts, epoch, pkt_epoch)) {
11049 			uint32_t time_in;
11050 
11051 			bbr_log_startup_event(bbr, cts, bbr->r_ctl.rc_bbr_last_startup_epoch,
11052 					      bbr->r_ctl.rc_lost_at_startup, bbr_start_exit, 6);
11053 			bbr->rc_filled_pipe = 1;
11054 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11055 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11056 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11057 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11058 			} else
11059 				time_in = 0;
11060 			if (bbr->rc_no_pacing)
11061 				bbr->rc_no_pacing = 0;
11062 			bbr->r_ctl.rc_bbr_state_time = cts;
11063 			bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.rc_drain_pg;
11064 			bbr->rc_bbr_state = BBR_STATE_DRAIN;
11065 			bbr_set_state_target(bbr, __LINE__);
11066 			if ((bbr->rc_use_google == 0) &&
11067 			    bbr_slam_cwnd_in_main_drain) {
11068 				/* Here we don't have to worry about probe-rtt */
11069 				bbr->r_ctl.rc_saved_cwnd = bbr->rc_tp->snd_cwnd;
11070 				bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11071 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11072 			}
11073 			bbr->r_ctl.rc_bbr_cwnd_gain = bbr_high_gain;
11074 			bbr_log_type_statechange(bbr, cts, __LINE__);
11075 			if (ctf_flight_size(bbr->rc_tp,
11076 			        (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes)) <=
11077 			    bbr->r_ctl.rc_target_at_state) {
11078 				/*
11079 				 * Switch to probe_bw if we are already
11080 				 * there
11081 				 */
11082 				bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11083 				bbr_substate_change(bbr, cts, __LINE__, 0);
11084 				bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11085 				bbr_log_type_statechange(bbr, cts, __LINE__);
11086 			}
11087 		}
11088 	} else if (bbr->rc_bbr_state == BBR_STATE_IDLE_EXIT) {
11089 		uint32_t inflight;
11090 		struct tcpcb *tp;
11091 
11092 		tp = bbr->rc_tp;
11093 		inflight = ctf_flight_size(tp,
11094 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11095 		if (inflight >= bbr->r_ctl.rc_target_at_state) {
11096 			/* We have reached a flight of the cwnd target */
11097 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11098 			bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11099 			bbr->r_ctl.rc_bbr_cwnd_gain = BBR_UNIT;
11100 			bbr_set_state_target(bbr, __LINE__);
11101 			/*
11102 			 * Rig it so we don't do anything crazy and
11103 			 * start fresh with a new randomization.
11104 			 */
11105 			bbr->r_ctl.bbr_smallest_srtt_this_state = 0xffffffff;
11106 			bbr->rc_bbr_substate = BBR_SUB_LEVEL6;
11107 			bbr_substate_change(bbr, cts, __LINE__, 1);
11108 		}
11109 	} else if (bbr->rc_bbr_state == BBR_STATE_DRAIN) {
11110 		/* Has in-flight reached the bdp (or less)? */
11111 		uint32_t inflight;
11112 		struct tcpcb *tp;
11113 
11114 		tp = bbr->rc_tp;
11115 		inflight = ctf_flight_size(tp,
11116 			      (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11117 		if ((bbr->rc_use_google == 0) &&
11118 		    bbr_slam_cwnd_in_main_drain &&
11119 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11120 			/*
11121 			 * Here we don't have to worry about probe-rtt
11122 			 * re-slam it, but keep it slammed down.
11123 			 */
11124 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11125 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11126 		}
11127 		if (inflight <= bbr->r_ctl.rc_target_at_state) {
11128 			/* We have drained */
11129 			bbr->rc_bbr_state = BBR_STATE_PROBE_BW;
11130 			bbr->r_ctl.bbr_lost_at_state = bbr->r_ctl.rc_lost;
11131 			if (SEQ_GT(cts, bbr->r_ctl.rc_bbr_state_time)) {
11132 				uint32_t time_in;
11133 
11134 				time_in = cts - bbr->r_ctl.rc_bbr_state_time;
11135 				counter_u64_add(bbr_state_time[bbr->rc_bbr_state], time_in);
11136 			}
11137 			if ((bbr->rc_use_google == 0) &&
11138 			    bbr_slam_cwnd_in_main_drain &&
11139 			    (tp->snd_cwnd < bbr->r_ctl.rc_saved_cwnd)) {
11140 				/* Restore the cwnd */
11141 				tp->snd_cwnd = bbr->r_ctl.rc_saved_cwnd;
11142 				bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11143 			}
11144 			/* Setup probe-rtt has being done now RRS-HERE */
11145 			bbr->r_ctl.rc_rtt_shrinks = cts;
11146 			bbr->r_ctl.last_in_probertt = cts;
11147 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_LEAVE_DRAIN, 0);
11148 			/* Randomly pick a sub-state */
11149 			bbr->rc_bbr_substate = bbr_pick_probebw_substate(bbr, cts);
11150 			bbr_substate_change(bbr, cts, __LINE__, 0);
11151 			bbr_log_type_statechange(bbr, cts, __LINE__);
11152 		}
11153 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_RTT) {
11154 		uint32_t flight;
11155 
11156 		flight = ctf_flight_size(bbr->rc_tp,
11157 			     (bbr->r_ctl.rc_sacked + bbr->r_ctl.rc_lost_bytes));
11158 		bbr->r_ctl.r_app_limited_until = (flight + bbr->r_ctl.rc_delivered);
11159 		if (((bbr->r_ctl.bbr_rttprobe_gain_val == 0) || bbr->rc_use_google) &&
11160 		    (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11161 			/*
11162 			 * We must keep cwnd at the desired MSS.
11163 			 */
11164 			bbr->rc_tp->snd_cwnd = bbr_rtt_probe_cwndtarg * (bbr->rc_tp->t_maxseg - bbr->rc_last_options);
11165 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11166 		} else if ((bbr_prtt_slam_cwnd) &&
11167 			   (bbr->rc_tp->snd_cwnd > bbr->r_ctl.rc_target_at_state)) {
11168 			/* Re-slam it */
11169 			bbr->rc_tp->snd_cwnd = bbr->r_ctl.rc_target_at_state;
11170 			bbr_log_type_cwndupd(bbr, 0, 0, 0, 12, 0, 0, __LINE__);
11171 		}
11172 		if (bbr->r_ctl.rc_bbr_enters_probertt == 0) {
11173 			/* Has outstanding reached our target? */
11174 			if (flight <= bbr->r_ctl.rc_target_at_state) {
11175 				bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_REACHTAR, 0);
11176 				bbr->r_ctl.rc_bbr_enters_probertt = cts;
11177 				/* If time is exactly 0, be 1usec off */
11178 				if (bbr->r_ctl.rc_bbr_enters_probertt == 0)
11179 					bbr->r_ctl.rc_bbr_enters_probertt = 1;
11180 				if (bbr->rc_use_google == 0) {
11181 					/*
11182 					 * Restore any lowering that as occurred to
11183 					 * reach here
11184 					 */
11185 					if (bbr->r_ctl.bbr_rttprobe_gain_val)
11186 						bbr->r_ctl.rc_bbr_hptsi_gain = bbr->r_ctl.bbr_rttprobe_gain_val;
11187 					else
11188 						bbr->r_ctl.rc_bbr_hptsi_gain = BBR_UNIT;
11189 				}
11190 			}
11191 			if ((bbr->r_ctl.rc_bbr_enters_probertt == 0) &&
11192 			    (bbr->rc_use_google == 0) &&
11193 			    bbr->r_ctl.bbr_rttprobe_gain_val &&
11194 			    (((cts - bbr->r_ctl.rc_probertt_srttchktim) > bbr_get_rtt(bbr, bbr_drain_rtt)) ||
11195 			     (flight >= bbr->r_ctl.flightsize_at_drain))) {
11196 				/*
11197 				 * We have doddled with our current hptsi
11198 				 * gain an srtt and have still not made it
11199 				 * to target, or we have increased our flight.
11200 				 * Lets reduce the gain by xx%
11201 				 * flooring the reduce at DRAIN (based on
11202 				 * mul/div)
11203 				 */
11204 				int red;
11205 
11206 				bbr->r_ctl.flightsize_at_drain = flight;
11207 				bbr->r_ctl.rc_probertt_srttchktim = cts;
11208 				red = max((bbr->r_ctl.bbr_rttprobe_gain_val / 10), 1);
11209 				if ((bbr->r_ctl.rc_bbr_hptsi_gain - red) > max(bbr_drain_floor, 1)) {
11210 					/* Reduce our gain again */
11211 					bbr->r_ctl.rc_bbr_hptsi_gain -= red;
11212 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG, 0);
11213 				} else if (bbr->r_ctl.rc_bbr_hptsi_gain > max(bbr_drain_floor, 1)) {
11214 					/* one more chance before we give up */
11215 					bbr->r_ctl.rc_bbr_hptsi_gain = max(bbr_drain_floor, 1);
11216 					bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_SHRINK_PG_FINAL, 0);
11217 				} else {
11218 					/* At the very bottom */
11219 					bbr->r_ctl.rc_bbr_hptsi_gain = max((bbr_drain_floor-1), 1);
11220 				}
11221 			}
11222 		}
11223 		if (bbr->r_ctl.rc_bbr_enters_probertt &&
11224 		    (TSTMP_GT(cts, bbr->r_ctl.rc_bbr_enters_probertt)) &&
11225 		    ((cts - bbr->r_ctl.rc_bbr_enters_probertt) >= bbr_rtt_probe_time)) {
11226 			/* Time to exit probe RTT normally */
11227 			bbr_exit_probe_rtt(bbr->rc_tp, bbr, cts);
11228 		}
11229 	} else if (bbr->rc_bbr_state == BBR_STATE_PROBE_BW) {
11230 		if ((bbr->rc_tp->snd_una == bbr->rc_tp->snd_max) &&
11231 		    (bbr_calc_time(cts, bbr->r_ctl.rc_went_idle_time) >= bbr_rtt_probe_time)) {
11232 			/*
11233 			 * This qualifies as a RTT_PROBE session since we
11234 			 * drop the data outstanding to nothing and waited
11235 			 * more than bbr_rtt_probe_time.
11236 			 */
11237 			bbr_log_rtt_shrinks(bbr, cts, 0, 0, __LINE__, BBR_RTTS_WASIDLE, 0);
11238 			bbr_set_reduced_rtt(bbr, cts, __LINE__);
11239 		}
11240 		if (bbr_should_enter_probe_rtt(bbr, cts)) {
11241 			bbr_enter_probe_rtt(bbr, cts, __LINE__);
11242 		} else {
11243 			bbr_set_probebw_gains(bbr, cts, losses);
11244 		}
11245 	}
11246 }
11247 
11248 static void
11249 bbr_check_bbr_for_state(struct tcp_bbr *bbr, uint32_t cts, int32_t line, uint32_t losses)
11250 {
11251 	int32_t epoch = 0;
11252 
11253 	if ((cts - bbr->r_ctl.rc_rcv_epoch_start) >= bbr_get_rtt(bbr, BBR_RTT_PROP)) {
11254 		bbr_set_epoch(bbr, cts, line);
11255 		/* At each epoch doe lt bw sampling */
11256 		epoch = 1;
11257 	}
11258 	bbr_state_change(bbr, cts, epoch, bbr->rc_is_pkt_epoch_now, losses);
11259 }
11260 
11261 static int
11262 bbr_do_segment_nounlock(struct tcpcb *tp, struct mbuf *m, struct tcphdr *th,
11263     int32_t drop_hdrlen, int32_t tlen, uint8_t iptos, int32_t nxt_pkt,
11264     struct timeval *tv)
11265 {
11266 	struct inpcb *inp = tptoinpcb(tp);
11267 	struct socket *so = tptosocket(tp);
11268 	int32_t thflags, retval;
11269 	uint32_t cts, lcts;
11270 	uint32_t tiwin;
11271 	struct tcpopt to;
11272 	struct tcp_bbr *bbr;
11273 	struct bbr_sendmap *rsm;
11274 	struct timeval ltv;
11275 	int32_t did_out = 0;
11276 	uint16_t nsegs;
11277 	int32_t prev_state;
11278 	uint32_t lost;
11279 
11280 	nsegs = max(1, m->m_pkthdr.lro_nsegs);
11281 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
11282 	/* add in our stats */
11283 	kern_prefetch(bbr, &prev_state);
11284 	prev_state = 0;
11285 	thflags = tcp_get_flags(th);
11286 	/*
11287 	 * If this is either a state-changing packet or current state isn't
11288 	 * established, we require a write lock on tcbinfo.  Otherwise, we
11289 	 * allow the tcbinfo to be in either alocked or unlocked, as the
11290 	 * caller may have unnecessarily acquired a write lock due to a
11291 	 * race.
11292 	 */
11293 	INP_WLOCK_ASSERT(tptoinpcb(tp));
11294 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
11295 	    __func__));
11296 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
11297 	    __func__));
11298 
11299 	tp->t_rcvtime = ticks;
11300 	/*
11301 	 * Unscale the window into a 32-bit value. For the SYN_SENT state
11302 	 * the scale is zero.
11303 	 */
11304 	tiwin = th->th_win << tp->snd_scale;
11305 #ifdef STATS
11306 	stats_voi_update_abs_ulong(tp->t_stats, VOI_TCP_FRWIN, tiwin);
11307 #endif
11308 
11309 	if (m->m_flags & M_TSTMP) {
11310 		/* Prefer the hardware timestamp if present */
11311 		struct timespec ts;
11312 
11313 		mbuf_tstmp2timespec(m, &ts);
11314 		bbr->rc_tv.tv_sec = ts.tv_sec;
11315 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11316 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11317 	} else if (m->m_flags & M_TSTMP_LRO) {
11318 		/* Next the arrival timestamp */
11319 		struct timespec ts;
11320 
11321 		mbuf_tstmp2timespec(m, &ts);
11322 		bbr->rc_tv.tv_sec = ts.tv_sec;
11323 		bbr->rc_tv.tv_usec = ts.tv_nsec / 1000;
11324 		bbr->r_ctl.rc_rcvtime = cts = tcp_tv_to_usectick(&bbr->rc_tv);
11325 	} else {
11326 		/*
11327 		 * Ok just get the current time.
11328 		 */
11329 		bbr->r_ctl.rc_rcvtime = lcts = cts = tcp_get_usecs(&bbr->rc_tv);
11330 	}
11331 	/*
11332 	 * Parse options on any incoming segment.
11333 	 */
11334 	tcp_dooptions(&to, (u_char *)(th + 1),
11335 	    (th->th_off << 2) - sizeof(struct tcphdr),
11336 	    (thflags & TH_SYN) ? TO_SYN : 0);
11337 	if (tp->t_flags2 & TF2_PROC_SACK_PROHIBIT) {
11338 		/*
11339 		 * We don't look at sack's from the
11340 		 * peer because the MSS is too small which
11341 		 * can subject us to an attack.
11342 		 */
11343 		to.to_flags &= ~TOF_SACK;
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 (tp->t_flags & TF_FASTOPEN) {
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;
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 ((tp->t_flags & TF_FASTOPEN) &&
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 ((tp->t_flags & TF_FASTOPEN) &&
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 ((tp->t_flags & TF_FASTOPEN) &&
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) && !(tp->t_flags & TF_FASTOPEN))
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 ((tp->t_flags & TF_FASTOPEN) &&
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 ((tp->t_flags & TF_FASTOPEN) && 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 	if (lgb) {
13594 		lgb->tlb_errno = error;
13595 		lgb = NULL;
13596 	}
13597 
13598 out:
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 					if (tp->t_maxseg < V_tcp_mssdflt) {
13795 						/*
13796 						 * The MSS is so small we should not
13797 						 * process incoming SACK's since we are
13798 						 * subject to attack in such a case.
13799 						 */
13800 						tp->t_flags2 |= TF2_PROC_SACK_PROHIBIT;
13801 					} else {
13802 						tp->t_flags2 &= ~TF2_PROC_SACK_PROHIBIT;
13803 					}
13804 					bbr_log_msgsize_fail(bbr, tp, len, maxseg, mtu, 0, tso, cts);
13805 				}
13806 				/*
13807 				 * Nuke all other things that can interfere
13808 				 * with slot
13809 				 */
13810 				if ((tot_len + len) && (len >= tp->t_maxseg)) {
13811 					slot = bbr_get_pacing_delay(bbr,
13812 					    bbr->r_ctl.rc_bbr_hptsi_gain,
13813 					    (tot_len + len), cts, 0);
13814 					if (slot < bbr_error_base_paceout)
13815 						slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13816 				} else
13817 					slot = (bbr_error_base_paceout + 2) << bbr->oerror_cnt;
13818 				bbr->rc_output_starts_timer = 1;
13819 				bbr_start_hpts_timer(bbr, tp, cts, 10, slot,
13820 				    tot_len);
13821 				return (error);
13822 			}
13823 		case EPERM:
13824 		case EACCES:
13825 			tp->t_softerror = error;
13826 			/* FALLTHROUGH */
13827 		case EHOSTDOWN:
13828 		case EHOSTUNREACH:
13829 		case ENETDOWN:
13830 		case ENETUNREACH:
13831 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
13832 				tp->t_softerror = error;
13833 			}
13834 			/* FALLTHROUGH */
13835 		default:
13836 			slot = (bbr_error_base_paceout + 3) << bbr->oerror_cnt;
13837 			bbr->rc_output_starts_timer = 1;
13838 			bbr_start_hpts_timer(bbr, tp, cts, 11, slot, 0);
13839 			return (error);
13840 		}
13841 #ifdef STATS
13842 	} else if (((tp->t_flags & TF_GPUTINPROG) == 0) &&
13843 		    len &&
13844 		    (rsm == NULL) &&
13845 	    (bbr->rc_in_persist == 0)) {
13846 		tp->gput_seq = bbr_seq;
13847 		tp->gput_ack = bbr_seq +
13848 		    min(sbavail(&so->so_snd) - sb_offset, sendwin);
13849 		tp->gput_ts = cts;
13850 		tp->t_flags |= TF_GPUTINPROG;
13851 #endif
13852 	}
13853 	KMOD_TCPSTAT_INC(tcps_sndtotal);
13854 	if ((bbr->bbr_hdw_pace_ena) &&
13855 	    (bbr->bbr_attempt_hdwr_pace == 0) &&
13856 	    (bbr->rc_past_init_win) &&
13857 	    (bbr->rc_bbr_state != BBR_STATE_STARTUP) &&
13858 	    (get_filter_value(&bbr->r_ctl.rc_delrate)) &&
13859 	    (inp->inp_route.ro_nh &&
13860 	     inp->inp_route.ro_nh->nh_ifp)) {
13861 		/*
13862 		 * We are past the initial window and
13863 		 * have at least one measurement so we
13864 		 * could use hardware pacing if its available.
13865 		 * We have an interface and we have not attempted
13866 		 * to setup hardware pacing, lets try to now.
13867 		 */
13868 		uint64_t rate_wanted;
13869 		int err = 0;
13870 
13871 		rate_wanted = bbr_get_hardware_rate(bbr);
13872 		bbr->bbr_attempt_hdwr_pace = 1;
13873 		bbr->r_ctl.crte = tcp_set_pacing_rate(bbr->rc_tp,
13874 						      inp->inp_route.ro_nh->nh_ifp,
13875 						      rate_wanted,
13876 						      (RS_PACING_GEQ|RS_PACING_SUB_OK),
13877 						      &err, NULL);
13878 		if (bbr->r_ctl.crte) {
13879 			bbr_type_log_hdwr_pacing(bbr,
13880 						 bbr->r_ctl.crte->ptbl->rs_ifp,
13881 						 rate_wanted,
13882 						 bbr->r_ctl.crte->rate,
13883 						 __LINE__, cts, err);
13884 			BBR_STAT_INC(bbr_hdwr_rl_add_ok);
13885 			counter_u64_add(bbr_flows_nohdwr_pacing, -1);
13886 			counter_u64_add(bbr_flows_whdwr_pacing, 1);
13887 			bbr->bbr_hdrw_pacing = 1;
13888 			/* Now what is our gain status? */
13889 			if (bbr->r_ctl.crte->rate < rate_wanted) {
13890 				/* We have a problem */
13891 				bbr_setup_less_of_rate(bbr, cts,
13892 						       bbr->r_ctl.crte->rate, rate_wanted);
13893 			} else {
13894 				/* We are good */
13895 				bbr->gain_is_limited = 0;
13896 				bbr->skip_gain = 0;
13897 			}
13898 			tcp_bbr_tso_size_check(bbr, cts);
13899 		} else {
13900 			bbr_type_log_hdwr_pacing(bbr,
13901 						 inp->inp_route.ro_nh->nh_ifp,
13902 						 rate_wanted,
13903 						 0,
13904 						 __LINE__, cts, err);
13905 			BBR_STAT_INC(bbr_hdwr_rl_add_fail);
13906 		}
13907 	}
13908 	if (bbr->bbr_hdrw_pacing) {
13909 		/*
13910 		 * Worry about cases where the route
13911 		 * changes or something happened that we
13912 		 * lost our hardware pacing possibly during
13913 		 * the last ip_output call.
13914 		 */
13915 		if (inp->inp_snd_tag == NULL) {
13916 			/* A change during ip output disabled hw pacing? */
13917 			bbr->bbr_hdrw_pacing = 0;
13918 		} else if ((inp->inp_route.ro_nh == NULL) ||
13919 		    (inp->inp_route.ro_nh->nh_ifp != inp->inp_snd_tag->ifp)) {
13920 			/*
13921 			 * We had an interface or route change,
13922 			 * detach from the current hdwr pacing
13923 			 * and setup to re-attempt next go
13924 			 * round.
13925 			 */
13926 			bbr->bbr_hdrw_pacing = 0;
13927 			bbr->bbr_attempt_hdwr_pace = 0;
13928 			tcp_rel_pacing_rate(bbr->r_ctl.crte, bbr->rc_tp);
13929 			tcp_bbr_tso_size_check(bbr, cts);
13930 		}
13931 	}
13932 	/*
13933 	 * Data sent (as far as we can tell). If this advertises a larger
13934 	 * window than any other segment, then remember the size of the
13935 	 * advertised window. Any pending ACK has now been sent.
13936 	 */
13937 	if (SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
13938 		tp->rcv_adv = tp->rcv_nxt + recwin;
13939 
13940 	tp->last_ack_sent = tp->rcv_nxt;
13941 	if ((error == 0) &&
13942 	    (bbr->r_ctl.rc_pace_max_segs > tp->t_maxseg) &&
13943 	    (doing_tlp == 0) &&
13944 	    (tso == 0) &&
13945 	    (len > 0) &&
13946 	    ((flags & TH_RST) == 0) &&
13947 	    ((flags & TH_SYN) == 0) &&
13948 	    (IN_RECOVERY(tp->t_flags) == 0) &&
13949 	    (bbr->rc_in_persist == 0) &&
13950 	    (tot_len < bbr->r_ctl.rc_pace_max_segs)) {
13951 		/*
13952 		 * For non-tso we need to goto again until we have sent out
13953 		 * enough data to match what we are hptsi out every hptsi
13954 		 * interval.
13955 		 */
13956 		if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
13957 			/* Make sure snd_nxt is drug up */
13958 			tp->snd_nxt = tp->snd_max;
13959 		}
13960 		if (rsm != NULL) {
13961 			rsm = NULL;
13962 			goto skip_again;
13963 		}
13964 		rsm = NULL;
13965 		sack_rxmit = 0;
13966 		tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13967 		goto again;
13968 	}
13969 skip_again:
13970 	if ((error == 0) && (flags & TH_FIN))
13971 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_FIN);
13972 	if ((error == 0) && (flags & TH_RST))
13973 		tcp_log_end_status(tp, TCP_EI_STATUS_SERVER_RST);
13974 	if (((flags & (TH_RST | TH_SYN | TH_FIN)) == 0) && tot_len) {
13975 		/*
13976 		 * Calculate/Re-Calculate the hptsi slot in usecs based on
13977 		 * what we have sent so far
13978 		 */
13979 		slot = bbr_get_pacing_delay(bbr, bbr->r_ctl.rc_bbr_hptsi_gain, tot_len, cts, 0);
13980 		if (bbr->rc_no_pacing)
13981 			slot = 0;
13982 	}
13983 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
13984 enobufs:
13985 	if (bbr->rc_use_google == 0)
13986 		bbr_check_bbr_for_state(bbr, cts, __LINE__, 0);
13987 	bbr_cwnd_limiting(tp, bbr, ctf_flight_size(tp, (bbr->r_ctl.rc_sacked +
13988 							bbr->r_ctl.rc_lost_bytes)));
13989 	bbr->rc_output_starts_timer = 1;
13990 	if (bbr->bbr_use_rack_cheat &&
13991 	    (more_to_rxt ||
13992 	     ((bbr->r_ctl.rc_resend = bbr_check_recovery_mode(tp, bbr, cts)) != NULL))) {
13993 		/* Rack cheats and shotguns out all rxt's 1ms apart */
13994 		if (slot > 1000)
13995 			slot = 1000;
13996 	}
13997 	if (bbr->bbr_hdrw_pacing && (bbr->hw_pacing_set == 0)) {
13998 		/*
13999 		 * We don't change the tso size until some number of sends
14000 		 * to give the hardware commands time to get down
14001 		 * to the interface.
14002 		 */
14003 		bbr->r_ctl.bbr_hdwr_cnt_noset_snt++;
14004 		if (bbr->r_ctl.bbr_hdwr_cnt_noset_snt >= bbr_hdwr_pacing_delay_cnt) {
14005 			bbr->hw_pacing_set = 1;
14006 			tcp_bbr_tso_size_check(bbr, cts);
14007 		}
14008 	}
14009 	bbr_start_hpts_timer(bbr, tp, cts, 12, slot, tot_len);
14010 	if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
14011 		/* Make sure snd_nxt is drug up */
14012 		tp->snd_nxt = tp->snd_max;
14013 	}
14014 	return (error);
14015 
14016 }
14017 
14018 /*
14019  * See bbr_output_wtime() for return values.
14020  */
14021 static int
14022 bbr_output(struct tcpcb *tp)
14023 {
14024 	int32_t ret;
14025 	struct timeval tv;
14026 
14027 	NET_EPOCH_ASSERT();
14028 
14029 	INP_WLOCK_ASSERT(tptoinpcb(tp));
14030 	(void)tcp_get_usecs(&tv);
14031 	ret = bbr_output_wtime(tp, &tv);
14032 	return (ret);
14033 }
14034 
14035 static void
14036 bbr_mtu_chg(struct tcpcb *tp)
14037 {
14038 	struct tcp_bbr *bbr;
14039 	struct bbr_sendmap *rsm, *frsm = NULL;
14040 	uint32_t maxseg;
14041 
14042 	/*
14043 	 * The MTU has changed. a) Clear the sack filter. b) Mark everything
14044 	 * over the current size as SACK_PASS so a retransmit will occur.
14045 	 */
14046 
14047 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14048 	maxseg = tp->t_maxseg - bbr->rc_last_options;
14049 	sack_filter_clear(&bbr->r_ctl.bbr_sf, tp->snd_una);
14050 	TAILQ_FOREACH(rsm, &bbr->r_ctl.rc_map, r_next) {
14051 		/* Don't mess with ones acked (by sack?) */
14052 		if (rsm->r_flags & BBR_ACKED)
14053 			continue;
14054 		if ((rsm->r_end - rsm->r_start) > maxseg) {
14055 			/*
14056 			 * We mark sack-passed on all the previous large
14057 			 * sends we did. This will force them to retransmit.
14058 			 */
14059 			rsm->r_flags |= BBR_SACK_PASSED;
14060 			if (((rsm->r_flags & BBR_MARKED_LOST) == 0) &&
14061 			    bbr_is_lost(bbr, rsm, bbr->r_ctl.rc_rcvtime)) {
14062 				bbr->r_ctl.rc_lost_bytes += rsm->r_end - rsm->r_start;
14063 				bbr->r_ctl.rc_lost += rsm->r_end - rsm->r_start;
14064 				rsm->r_flags |= BBR_MARKED_LOST;
14065 			}
14066 			if (frsm == NULL)
14067 				frsm = rsm;
14068 		}
14069 	}
14070 	if (frsm) {
14071 		bbr->r_ctl.rc_resend = frsm;
14072 	}
14073 }
14074 
14075 static int
14076 bbr_pru_options(struct tcpcb *tp, int flags)
14077 {
14078 	if (flags & PRUS_OOB)
14079 		return (EOPNOTSUPP);
14080 	return (0);
14081 }
14082 
14083 static void
14084 bbr_switch_failed(struct tcpcb *tp)
14085 {
14086 	/*
14087 	 * If a switch fails we only need to
14088 	 * make sure mbuf_queuing is still in place.
14089 	 * We also need to make sure we are still in
14090 	 * ticks granularity (though we should probably
14091 	 * change bbr to go to USECs).
14092 	 *
14093 	 * For timers we need to see if we are still in the
14094 	 * pacer (if our flags are up) if so we are good, if
14095 	 * not we need to get back into the pacer.
14096 	 */
14097 	struct timeval tv;
14098 	uint32_t cts;
14099 	uint32_t toval;
14100 	struct tcp_bbr *bbr;
14101 	struct hpts_diag diag;
14102 
14103 	tp->t_flags2 |= TF2_CANNOT_DO_ECN;
14104 	tp->t_flags2 |= TF2_SUPPORTS_MBUFQ;
14105 	tcp_change_time_units(tp, TCP_TMR_GRANULARITY_TICKS);
14106 	if (tp->t_in_hpts > IHPTS_NONE) {
14107 		return;
14108 	}
14109 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14110 	cts = tcp_get_usecs(&tv);
14111 	if (bbr->r_ctl.rc_hpts_flags & PACE_PKT_OUTPUT) {
14112 		if (TSTMP_GT(bbr->rc_pacer_started, cts)) {
14113 			toval = bbr->rc_pacer_started - cts;
14114 		} else {
14115 			/* one slot please */
14116 			toval = HPTS_TICKS_PER_SLOT;
14117 		}
14118 	} else if (bbr->r_ctl.rc_hpts_flags & PACE_TMR_MASK) {
14119 		if (TSTMP_GT(bbr->r_ctl.rc_timer_exp, cts)) {
14120 			toval = bbr->r_ctl.rc_timer_exp - cts;
14121 		} else {
14122 			/* one slot please */
14123 			toval = HPTS_TICKS_PER_SLOT;
14124 		}
14125 	} else
14126 		toval = HPTS_TICKS_PER_SLOT;
14127 	(void)tcp_hpts_insert_diag(tp, HPTS_USEC_TO_SLOTS(toval),
14128 				   __LINE__, &diag);
14129 	bbr_log_hpts_diag(bbr, cts, &diag);
14130 }
14131 
14132 struct tcp_function_block __tcp_bbr = {
14133 	.tfb_tcp_block_name = __XSTRING(STACKNAME),
14134 	.tfb_tcp_output = bbr_output,
14135 	.tfb_do_queued_segments = ctf_do_queued_segments,
14136 	.tfb_do_segment_nounlock = bbr_do_segment_nounlock,
14137 	.tfb_tcp_do_segment = bbr_do_segment,
14138 	.tfb_tcp_ctloutput = bbr_ctloutput,
14139 	.tfb_tcp_fb_init = bbr_init,
14140 	.tfb_tcp_fb_fini = bbr_fini,
14141 	.tfb_tcp_timer_stop_all = bbr_stopall,
14142 	.tfb_tcp_rexmit_tmr = bbr_remxt_tmr,
14143 	.tfb_tcp_handoff_ok = bbr_handoff_ok,
14144 	.tfb_tcp_mtu_chg = bbr_mtu_chg,
14145 	.tfb_pru_options = bbr_pru_options,
14146 	.tfb_switch_failed = bbr_switch_failed,
14147 	.tfb_flags = TCP_FUNC_OUTPUT_CANDROP,
14148 };
14149 
14150 /*
14151  * bbr_ctloutput() must drop the inpcb lock before performing copyin on
14152  * socket option arguments.  When it re-acquires the lock after the copy, it
14153  * has to revalidate that the connection is still valid for the socket
14154  * option.
14155  */
14156 static int
14157 bbr_set_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14158 {
14159 	struct epoch_tracker et;
14160 	struct inpcb *inp = tptoinpcb(tp);
14161 	struct tcp_bbr *bbr;
14162 	int32_t error = 0, optval;
14163 
14164 	switch (sopt->sopt_level) {
14165 	case IPPROTO_IPV6:
14166 	case IPPROTO_IP:
14167 		return (tcp_default_ctloutput(tp, sopt));
14168 	}
14169 
14170 	switch (sopt->sopt_name) {
14171 	case TCP_RACK_PACE_MAX_SEG:
14172 	case TCP_RACK_MIN_TO:
14173 	case TCP_RACK_REORD_THRESH:
14174 	case TCP_RACK_REORD_FADE:
14175 	case TCP_RACK_TLP_THRESH:
14176 	case TCP_RACK_PKT_DELAY:
14177 	case TCP_BBR_ALGORITHM:
14178 	case TCP_BBR_TSLIMITS:
14179 	case TCP_BBR_IWINTSO:
14180 	case TCP_BBR_RECFORCE:
14181 	case TCP_BBR_STARTUP_PG:
14182 	case TCP_BBR_DRAIN_PG:
14183 	case TCP_BBR_RWND_IS_APP:
14184 	case TCP_BBR_PROBE_RTT_INT:
14185 	case TCP_BBR_PROBE_RTT_GAIN:
14186 	case TCP_BBR_PROBE_RTT_LEN:
14187 	case TCP_BBR_STARTUP_LOSS_EXIT:
14188 	case TCP_BBR_USEDEL_RATE:
14189 	case TCP_BBR_MIN_RTO:
14190 	case TCP_BBR_MAX_RTO:
14191 	case TCP_BBR_PACE_PER_SEC:
14192 	case TCP_DELACK:
14193 	case TCP_BBR_PACE_DEL_TAR:
14194 	case TCP_BBR_SEND_IWND_IN_TSO:
14195 	case TCP_BBR_EXTRA_STATE:
14196 	case TCP_BBR_UTTER_MAX_TSO:
14197 	case TCP_BBR_MIN_TOPACEOUT:
14198 	case TCP_BBR_FLOOR_MIN_TSO:
14199 	case TCP_BBR_TSTMP_RAISES:
14200 	case TCP_BBR_POLICER_DETECT:
14201 	case TCP_BBR_USE_RACK_CHEAT:
14202 	case TCP_DATA_AFTER_CLOSE:
14203 	case TCP_BBR_HDWR_PACE:
14204 	case TCP_BBR_PACE_SEG_MAX:
14205 	case TCP_BBR_PACE_SEG_MIN:
14206 	case TCP_BBR_PACE_CROSS:
14207 	case TCP_BBR_PACE_OH:
14208 	case TCP_BBR_TMR_PACE_OH:
14209 	case TCP_BBR_RACK_RTT_USE:
14210 	case TCP_BBR_RETRAN_WTSO:
14211 		break;
14212 	default:
14213 		return (tcp_default_ctloutput(tp, sopt));
14214 		break;
14215 	}
14216 	INP_WUNLOCK(inp);
14217 	error = sooptcopyin(sopt, &optval, sizeof(optval), sizeof(optval));
14218 	if (error)
14219 		return (error);
14220 	INP_WLOCK(inp);
14221 	if (inp->inp_flags & INP_DROPPED) {
14222 		INP_WUNLOCK(inp);
14223 		return (ECONNRESET);
14224 	}
14225 	if (tp->t_fb != &__tcp_bbr) {
14226 		INP_WUNLOCK(inp);
14227 		return (ENOPROTOOPT);
14228 	}
14229 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14230 	switch (sopt->sopt_name) {
14231 	case TCP_BBR_PACE_PER_SEC:
14232 		BBR_OPTS_INC(tcp_bbr_pace_per_sec);
14233 		bbr->r_ctl.bbr_hptsi_per_second = optval;
14234 		break;
14235 	case TCP_BBR_PACE_DEL_TAR:
14236 		BBR_OPTS_INC(tcp_bbr_pace_del_tar);
14237 		bbr->r_ctl.bbr_hptsi_segments_delay_tar = optval;
14238 		break;
14239 	case TCP_BBR_PACE_SEG_MAX:
14240 		BBR_OPTS_INC(tcp_bbr_pace_seg_max);
14241 		bbr->r_ctl.bbr_hptsi_segments_max = optval;
14242 		break;
14243 	case TCP_BBR_PACE_SEG_MIN:
14244 		BBR_OPTS_INC(tcp_bbr_pace_seg_min);
14245 		bbr->r_ctl.bbr_hptsi_bytes_min = optval;
14246 		break;
14247 	case TCP_BBR_PACE_CROSS:
14248 		BBR_OPTS_INC(tcp_bbr_pace_cross);
14249 		bbr->r_ctl.bbr_cross_over = optval;
14250 		break;
14251 	case TCP_BBR_ALGORITHM:
14252 		BBR_OPTS_INC(tcp_bbr_algorithm);
14253 		if (optval && (bbr->rc_use_google == 0)) {
14254 			/* Turn on the google mode */
14255 			bbr_google_mode_on(bbr);
14256 			if ((optval > 3) && (optval < 500)) {
14257 				/*
14258 				 * Must be at least greater than .3%
14259 				 * and must be less than 50.0%.
14260 				 */
14261 				bbr->r_ctl.bbr_google_discount = optval;
14262 			}
14263 		} else if ((optval == 0) && (bbr->rc_use_google == 1)) {
14264 			/* Turn off the google mode */
14265 			bbr_google_mode_off(bbr);
14266 		}
14267 		break;
14268 	case TCP_BBR_TSLIMITS:
14269 		BBR_OPTS_INC(tcp_bbr_tslimits);
14270 		if (optval == 1)
14271 			bbr->rc_use_ts_limit = 1;
14272 		else if (optval == 0)
14273 			bbr->rc_use_ts_limit = 0;
14274 		else
14275 			error = EINVAL;
14276 		break;
14277 
14278 	case TCP_BBR_IWINTSO:
14279 		BBR_OPTS_INC(tcp_bbr_iwintso);
14280 		if ((optval >= 0) && (optval < 128)) {
14281 			uint32_t twin;
14282 
14283 			bbr->rc_init_win = optval;
14284 			twin = bbr_initial_cwnd(bbr, tp);
14285 			if ((bbr->rc_past_init_win == 0) && (twin > tp->snd_cwnd))
14286 				tp->snd_cwnd = twin;
14287 			else
14288 				error = EBUSY;
14289 		} else
14290 			error = EINVAL;
14291 		break;
14292 	case TCP_BBR_STARTUP_PG:
14293 		BBR_OPTS_INC(tcp_bbr_startup_pg);
14294 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE)) {
14295 			bbr->r_ctl.rc_startup_pg = optval;
14296 			if (bbr->rc_bbr_state == BBR_STATE_STARTUP) {
14297 				bbr->r_ctl.rc_bbr_hptsi_gain = optval;
14298 			}
14299 		} else
14300 			error = EINVAL;
14301 		break;
14302 	case TCP_BBR_DRAIN_PG:
14303 		BBR_OPTS_INC(tcp_bbr_drain_pg);
14304 		if ((optval > 0) && (optval < BBR_MAX_GAIN_VALUE))
14305 			bbr->r_ctl.rc_drain_pg = optval;
14306 		else
14307 			error = EINVAL;
14308 		break;
14309 	case TCP_BBR_PROBE_RTT_LEN:
14310 		BBR_OPTS_INC(tcp_bbr_probertt_len);
14311 		if (optval <= 1)
14312 			reset_time_small(&bbr->r_ctl.rc_rttprop, (optval * USECS_IN_SECOND));
14313 		else
14314 			error = EINVAL;
14315 		break;
14316 	case TCP_BBR_PROBE_RTT_GAIN:
14317 		BBR_OPTS_INC(tcp_bbr_probertt_gain);
14318 		if (optval <= BBR_UNIT)
14319 			bbr->r_ctl.bbr_rttprobe_gain_val = optval;
14320 		else
14321 			error = EINVAL;
14322 		break;
14323 	case TCP_BBR_PROBE_RTT_INT:
14324 		BBR_OPTS_INC(tcp_bbr_probe_rtt_int);
14325 		if (optval > 1000)
14326 			bbr->r_ctl.rc_probertt_int = optval;
14327 		else
14328 			error = EINVAL;
14329 		break;
14330 	case TCP_BBR_MIN_TOPACEOUT:
14331 		BBR_OPTS_INC(tcp_bbr_topaceout);
14332 		if (optval == 0) {
14333 			bbr->no_pacing_until = 0;
14334 			bbr->rc_no_pacing = 0;
14335 		} else if (optval <= 0x00ff) {
14336 			bbr->no_pacing_until = optval;
14337 			if ((bbr->r_ctl.rc_pkt_epoch < bbr->no_pacing_until) &&
14338 			    (bbr->rc_bbr_state == BBR_STATE_STARTUP)){
14339 				/* Turn on no pacing */
14340 				bbr->rc_no_pacing = 1;
14341 			}
14342 		} else
14343 			error = EINVAL;
14344 		break;
14345 	case TCP_BBR_STARTUP_LOSS_EXIT:
14346 		BBR_OPTS_INC(tcp_bbr_startup_loss_exit);
14347 		bbr->rc_loss_exit = optval;
14348 		break;
14349 	case TCP_BBR_USEDEL_RATE:
14350 		error = EINVAL;
14351 		break;
14352 	case TCP_BBR_MIN_RTO:
14353 		BBR_OPTS_INC(tcp_bbr_min_rto);
14354 		bbr->r_ctl.rc_min_rto_ms = optval;
14355 		break;
14356 	case TCP_BBR_MAX_RTO:
14357 		BBR_OPTS_INC(tcp_bbr_max_rto);
14358 		bbr->rc_max_rto_sec = optval;
14359 		break;
14360 	case TCP_RACK_MIN_TO:
14361 		/* Minimum time between rack t-o's in ms */
14362 		BBR_OPTS_INC(tcp_rack_min_to);
14363 		bbr->r_ctl.rc_min_to = optval;
14364 		break;
14365 	case TCP_RACK_REORD_THRESH:
14366 		/* RACK reorder threshold (shift amount) */
14367 		BBR_OPTS_INC(tcp_rack_reord_thresh);
14368 		if ((optval > 0) && (optval < 31))
14369 			bbr->r_ctl.rc_reorder_shift = optval;
14370 		else
14371 			error = EINVAL;
14372 		break;
14373 	case TCP_RACK_REORD_FADE:
14374 		/* Does reordering fade after ms time */
14375 		BBR_OPTS_INC(tcp_rack_reord_fade);
14376 		bbr->r_ctl.rc_reorder_fade = optval;
14377 		break;
14378 	case TCP_RACK_TLP_THRESH:
14379 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14380 		BBR_OPTS_INC(tcp_rack_tlp_thresh);
14381 		if (optval)
14382 			bbr->rc_tlp_threshold = optval;
14383 		else
14384 			error = EINVAL;
14385 		break;
14386 	case TCP_BBR_USE_RACK_CHEAT:
14387 		BBR_OPTS_INC(tcp_use_rackcheat);
14388 		if (bbr->rc_use_google) {
14389 			error = EINVAL;
14390 			break;
14391 		}
14392 		BBR_OPTS_INC(tcp_rack_cheat);
14393 		if (optval)
14394 			bbr->bbr_use_rack_cheat = 1;
14395 		else
14396 			bbr->bbr_use_rack_cheat = 0;
14397 		break;
14398 	case TCP_BBR_FLOOR_MIN_TSO:
14399 		BBR_OPTS_INC(tcp_utter_max_tso);
14400 		if ((optval >= 0) && (optval < 40))
14401 			bbr->r_ctl.bbr_hptsi_segments_floor = optval;
14402 		else
14403 			error = EINVAL;
14404 		break;
14405 	case TCP_BBR_UTTER_MAX_TSO:
14406 		BBR_OPTS_INC(tcp_utter_max_tso);
14407 		if ((optval >= 0) && (optval < 0xffff))
14408 			bbr->r_ctl.bbr_utter_max = optval;
14409 		else
14410 			error = EINVAL;
14411 		break;
14412 
14413 	case TCP_BBR_EXTRA_STATE:
14414 		BBR_OPTS_INC(tcp_extra_state);
14415 		if (optval)
14416 			bbr->rc_use_idle_restart = 1;
14417 		else
14418 			bbr->rc_use_idle_restart = 0;
14419 		break;
14420 	case TCP_BBR_SEND_IWND_IN_TSO:
14421 		BBR_OPTS_INC(tcp_iwnd_tso);
14422 		if (optval) {
14423 			bbr->bbr_init_win_cheat = 1;
14424 			if (bbr->rc_past_init_win == 0) {
14425 				uint32_t cts;
14426 				cts = tcp_get_usecs(&bbr->rc_tv);
14427 				tcp_bbr_tso_size_check(bbr, cts);
14428 			}
14429 		} else
14430 			bbr->bbr_init_win_cheat = 0;
14431 		break;
14432 	case TCP_BBR_HDWR_PACE:
14433 		BBR_OPTS_INC(tcp_hdwr_pacing);
14434 		if (optval){
14435 			bbr->bbr_hdw_pace_ena = 1;
14436 			bbr->bbr_attempt_hdwr_pace = 0;
14437 		} else {
14438 			bbr->bbr_hdw_pace_ena = 0;
14439 #ifdef RATELIMIT
14440 			if (bbr->r_ctl.crte != NULL) {
14441 				tcp_rel_pacing_rate(bbr->r_ctl.crte, tp);
14442 				bbr->r_ctl.crte = NULL;
14443 			}
14444 #endif
14445 		}
14446 		break;
14447 
14448 	case TCP_DELACK:
14449 		BBR_OPTS_INC(tcp_delack);
14450 		if (optval < 100) {
14451 			if (optval == 0) /* off */
14452 				tp->t_delayed_ack = 0;
14453 			else if (optval == 1) /* on which is 2 */
14454 				tp->t_delayed_ack = 2;
14455 			else /* higher than 2 and less than 100 */
14456 				tp->t_delayed_ack = optval;
14457 			if (tp->t_flags & TF_DELACK) {
14458 				tp->t_flags &= ~TF_DELACK;
14459 				tp->t_flags |= TF_ACKNOW;
14460 				NET_EPOCH_ENTER(et);
14461 				bbr_output(tp);
14462 				NET_EPOCH_EXIT(et);
14463 			}
14464 		} else
14465 			error = EINVAL;
14466 		break;
14467 	case TCP_RACK_PKT_DELAY:
14468 		/* RACK added ms i.e. rack-rtt + reord + N */
14469 		BBR_OPTS_INC(tcp_rack_pkt_delay);
14470 		bbr->r_ctl.rc_pkt_delay = optval;
14471 		break;
14472 
14473 	case TCP_BBR_RETRAN_WTSO:
14474 		BBR_OPTS_INC(tcp_retran_wtso);
14475 		if (optval)
14476 			bbr->rc_resends_use_tso = 1;
14477 		else
14478 			bbr->rc_resends_use_tso = 0;
14479 		break;
14480 	case TCP_DATA_AFTER_CLOSE:
14481 		BBR_OPTS_INC(tcp_data_ac);
14482 		if (optval)
14483 			bbr->rc_allow_data_af_clo = 1;
14484 		else
14485 			bbr->rc_allow_data_af_clo = 0;
14486 		break;
14487 	case TCP_BBR_POLICER_DETECT:
14488 		BBR_OPTS_INC(tcp_policer_det);
14489 		if (bbr->rc_use_google == 0)
14490 			error = EINVAL;
14491 		else if (optval)
14492 			bbr->r_use_policer = 1;
14493 		else
14494 			bbr->r_use_policer = 0;
14495 		break;
14496 
14497 	case TCP_BBR_TSTMP_RAISES:
14498 		BBR_OPTS_INC(tcp_ts_raises);
14499 		if (optval)
14500 			bbr->ts_can_raise = 1;
14501 		else
14502 			bbr->ts_can_raise = 0;
14503 		break;
14504 	case TCP_BBR_TMR_PACE_OH:
14505 		BBR_OPTS_INC(tcp_pacing_oh_tmr);
14506 		if (bbr->rc_use_google) {
14507 			error = EINVAL;
14508 		} else {
14509 			if (optval)
14510 				bbr->r_ctl.rc_incr_tmrs = 1;
14511 			else
14512 				bbr->r_ctl.rc_incr_tmrs = 0;
14513 		}
14514 		break;
14515 	case TCP_BBR_PACE_OH:
14516 		BBR_OPTS_INC(tcp_pacing_oh);
14517 		if (bbr->rc_use_google) {
14518 			error = EINVAL;
14519 		} else {
14520 			if (optval > (BBR_INCL_TCP_OH|
14521 				      BBR_INCL_IP_OH|
14522 				      BBR_INCL_ENET_OH)) {
14523 				error = EINVAL;
14524 				break;
14525 			}
14526 			if (optval & BBR_INCL_TCP_OH)
14527 				bbr->r_ctl.rc_inc_tcp_oh = 1;
14528 			else
14529 				bbr->r_ctl.rc_inc_tcp_oh = 0;
14530 			if (optval & BBR_INCL_IP_OH)
14531 				bbr->r_ctl.rc_inc_ip_oh = 1;
14532 			else
14533 				bbr->r_ctl.rc_inc_ip_oh = 0;
14534 			if (optval & BBR_INCL_ENET_OH)
14535 				bbr->r_ctl.rc_inc_enet_oh = 1;
14536 			else
14537 				bbr->r_ctl.rc_inc_enet_oh = 0;
14538 		}
14539 		break;
14540 	default:
14541 		return (tcp_default_ctloutput(tp, sopt));
14542 		break;
14543 	}
14544 	tcp_log_socket_option(tp, sopt->sopt_name, optval, error);
14545 	INP_WUNLOCK(inp);
14546 	return (error);
14547 }
14548 
14549 /*
14550  * return 0 on success, error-num on failure
14551  */
14552 static int
14553 bbr_get_sockopt(struct tcpcb *tp, struct sockopt *sopt)
14554 {
14555 	struct inpcb *inp = tptoinpcb(tp);
14556 	struct tcp_bbr *bbr;
14557 	int32_t error, optval;
14558 
14559 	bbr = (struct tcp_bbr *)tp->t_fb_ptr;
14560 	if (bbr == NULL) {
14561 		INP_WUNLOCK(inp);
14562 		return (EINVAL);
14563 	}
14564 	/*
14565 	 * Because all our options are either boolean or an int, we can just
14566 	 * pull everything into optval and then unlock and copy. If we ever
14567 	 * add a option that is not a int, then this will have quite an
14568 	 * impact to this routine.
14569 	 */
14570 	switch (sopt->sopt_name) {
14571 	case TCP_BBR_PACE_PER_SEC:
14572 		optval = bbr->r_ctl.bbr_hptsi_per_second;
14573 		break;
14574 	case TCP_BBR_PACE_DEL_TAR:
14575 		optval = bbr->r_ctl.bbr_hptsi_segments_delay_tar;
14576 		break;
14577 	case TCP_BBR_PACE_SEG_MAX:
14578 		optval = bbr->r_ctl.bbr_hptsi_segments_max;
14579 		break;
14580 	case TCP_BBR_MIN_TOPACEOUT:
14581 		optval = bbr->no_pacing_until;
14582 		break;
14583 	case TCP_BBR_PACE_SEG_MIN:
14584 		optval = bbr->r_ctl.bbr_hptsi_bytes_min;
14585 		break;
14586 	case TCP_BBR_PACE_CROSS:
14587 		optval = bbr->r_ctl.bbr_cross_over;
14588 		break;
14589 	case TCP_BBR_ALGORITHM:
14590 		optval = bbr->rc_use_google;
14591 		break;
14592 	case TCP_BBR_TSLIMITS:
14593 		optval = bbr->rc_use_ts_limit;
14594 		break;
14595 	case TCP_BBR_IWINTSO:
14596 		optval = bbr->rc_init_win;
14597 		break;
14598 	case TCP_BBR_STARTUP_PG:
14599 		optval = bbr->r_ctl.rc_startup_pg;
14600 		break;
14601 	case TCP_BBR_DRAIN_PG:
14602 		optval = bbr->r_ctl.rc_drain_pg;
14603 		break;
14604 	case TCP_BBR_PROBE_RTT_INT:
14605 		optval = bbr->r_ctl.rc_probertt_int;
14606 		break;
14607 	case TCP_BBR_PROBE_RTT_LEN:
14608 		optval = (bbr->r_ctl.rc_rttprop.cur_time_limit / USECS_IN_SECOND);
14609 		break;
14610 	case TCP_BBR_PROBE_RTT_GAIN:
14611 		optval = bbr->r_ctl.bbr_rttprobe_gain_val;
14612 		break;
14613 	case TCP_BBR_STARTUP_LOSS_EXIT:
14614 		optval = bbr->rc_loss_exit;
14615 		break;
14616 	case TCP_BBR_USEDEL_RATE:
14617 		error = EINVAL;
14618 		break;
14619 	case TCP_BBR_MIN_RTO:
14620 		optval = bbr->r_ctl.rc_min_rto_ms;
14621 		break;
14622 	case TCP_BBR_MAX_RTO:
14623 		optval = bbr->rc_max_rto_sec;
14624 		break;
14625 	case TCP_RACK_PACE_MAX_SEG:
14626 		/* Max segments in a pace */
14627 		optval = bbr->r_ctl.rc_pace_max_segs;
14628 		break;
14629 	case TCP_RACK_MIN_TO:
14630 		/* Minimum time between rack t-o's in ms */
14631 		optval = bbr->r_ctl.rc_min_to;
14632 		break;
14633 	case TCP_RACK_REORD_THRESH:
14634 		/* RACK reorder threshold (shift amount) */
14635 		optval = bbr->r_ctl.rc_reorder_shift;
14636 		break;
14637 	case TCP_RACK_REORD_FADE:
14638 		/* Does reordering fade after ms time */
14639 		optval = bbr->r_ctl.rc_reorder_fade;
14640 		break;
14641 	case TCP_BBR_USE_RACK_CHEAT:
14642 		/* Do we use the rack cheat for rxt */
14643 		optval = bbr->bbr_use_rack_cheat;
14644 		break;
14645 	case TCP_BBR_FLOOR_MIN_TSO:
14646 		optval = bbr->r_ctl.bbr_hptsi_segments_floor;
14647 		break;
14648 	case TCP_BBR_UTTER_MAX_TSO:
14649 		optval = bbr->r_ctl.bbr_utter_max;
14650 		break;
14651 	case TCP_BBR_SEND_IWND_IN_TSO:
14652 		/* Do we send TSO size segments initially */
14653 		optval = bbr->bbr_init_win_cheat;
14654 		break;
14655 	case TCP_BBR_EXTRA_STATE:
14656 		optval = bbr->rc_use_idle_restart;
14657 		break;
14658 	case TCP_RACK_TLP_THRESH:
14659 		/* RACK TLP theshold i.e. srtt+(srtt/N) */
14660 		optval = bbr->rc_tlp_threshold;
14661 		break;
14662 	case TCP_RACK_PKT_DELAY:
14663 		/* RACK added ms i.e. rack-rtt + reord + N */
14664 		optval = bbr->r_ctl.rc_pkt_delay;
14665 		break;
14666 	case TCP_BBR_RETRAN_WTSO:
14667 		optval = bbr->rc_resends_use_tso;
14668 		break;
14669 	case TCP_DATA_AFTER_CLOSE:
14670 		optval = bbr->rc_allow_data_af_clo;
14671 		break;
14672 	case TCP_DELACK:
14673 		optval = tp->t_delayed_ack;
14674 		break;
14675 	case TCP_BBR_HDWR_PACE:
14676 		optval = bbr->bbr_hdw_pace_ena;
14677 		break;
14678 	case TCP_BBR_POLICER_DETECT:
14679 		optval = bbr->r_use_policer;
14680 		break;
14681 	case TCP_BBR_TSTMP_RAISES:
14682 		optval = bbr->ts_can_raise;
14683 		break;
14684 	case TCP_BBR_TMR_PACE_OH:
14685 		optval = bbr->r_ctl.rc_incr_tmrs;
14686 		break;
14687 	case TCP_BBR_PACE_OH:
14688 		optval = 0;
14689 		if (bbr->r_ctl.rc_inc_tcp_oh)
14690 			optval |= BBR_INCL_TCP_OH;
14691 		if (bbr->r_ctl.rc_inc_ip_oh)
14692 			optval |= BBR_INCL_IP_OH;
14693 		if (bbr->r_ctl.rc_inc_enet_oh)
14694 			optval |= BBR_INCL_ENET_OH;
14695 		break;
14696 	default:
14697 		return (tcp_default_ctloutput(tp, sopt));
14698 		break;
14699 	}
14700 	INP_WUNLOCK(inp);
14701 	error = sooptcopyout(sopt, &optval, sizeof optval);
14702 	return (error);
14703 }
14704 
14705 /*
14706  * return 0 on success, error-num on failure
14707  */
14708 static int
14709 bbr_ctloutput(struct tcpcb *tp, struct sockopt *sopt)
14710 {
14711 	if (sopt->sopt_dir == SOPT_SET) {
14712 		return (bbr_set_sockopt(tp, sopt));
14713 	} else if (sopt->sopt_dir == SOPT_GET) {
14714 		return (bbr_get_sockopt(tp, sopt));
14715 	} else {
14716 		panic("%s: sopt_dir $%d", __func__, sopt->sopt_dir);
14717 	}
14718 }
14719 
14720 static const char *bbr_stack_names[] = {
14721 	__XSTRING(STACKNAME),
14722 #ifdef STACKALIAS
14723 	__XSTRING(STACKALIAS),
14724 #endif
14725 };
14726 
14727 static bool bbr_mod_inited = false;
14728 
14729 static int
14730 tcp_addbbr(module_t mod, int32_t type, void *data)
14731 {
14732 	int32_t err = 0;
14733 	int num_stacks;
14734 
14735 	switch (type) {
14736 	case MOD_LOAD:
14737 		printf("Attempting to load " __XSTRING(MODNAME) "\n");
14738 		bbr_zone = uma_zcreate(__XSTRING(MODNAME) "_map",
14739 		    sizeof(struct bbr_sendmap),
14740 		    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
14741 		bbr_pcb_zone = uma_zcreate(__XSTRING(MODNAME) "_pcb",
14742 		    sizeof(struct tcp_bbr),
14743 		    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
14744 		sysctl_ctx_init(&bbr_sysctl_ctx);
14745 		bbr_sysctl_root = SYSCTL_ADD_NODE(&bbr_sysctl_ctx,
14746 		    SYSCTL_STATIC_CHILDREN(_net_inet_tcp),
14747 		    OID_AUTO,
14748 #ifdef STACKALIAS
14749 		    __XSTRING(STACKALIAS),
14750 #else
14751 		    __XSTRING(STACKNAME),
14752 #endif
14753 		    CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
14754 		    "");
14755 		if (bbr_sysctl_root == NULL) {
14756 			printf("Failed to add sysctl node\n");
14757 			err = EFAULT;
14758 			goto free_uma;
14759 		}
14760 		bbr_init_sysctls();
14761 		num_stacks = nitems(bbr_stack_names);
14762 		err = register_tcp_functions_as_names(&__tcp_bbr, M_WAITOK,
14763 		    bbr_stack_names, &num_stacks);
14764 		if (err) {
14765 			printf("Failed to register %s stack name for "
14766 			    "%s module\n", bbr_stack_names[num_stacks],
14767 			    __XSTRING(MODNAME));
14768 			sysctl_ctx_free(&bbr_sysctl_ctx);
14769 	free_uma:
14770 			uma_zdestroy(bbr_zone);
14771 			uma_zdestroy(bbr_pcb_zone);
14772 			bbr_counter_destroy();
14773 			printf("Failed to register " __XSTRING(MODNAME)
14774 			    " module err:%d\n", err);
14775 			return (err);
14776 		}
14777 		tcp_lro_reg_mbufq();
14778 		bbr_mod_inited = true;
14779 		printf(__XSTRING(MODNAME) " is now available\n");
14780 		break;
14781 	case MOD_QUIESCE:
14782 		err = deregister_tcp_functions(&__tcp_bbr, true, false);
14783 		break;
14784 	case MOD_UNLOAD:
14785 		err = deregister_tcp_functions(&__tcp_bbr, false, true);
14786 		if (err == EBUSY)
14787 			break;
14788 		if (bbr_mod_inited) {
14789 			uma_zdestroy(bbr_zone);
14790 			uma_zdestroy(bbr_pcb_zone);
14791 			sysctl_ctx_free(&bbr_sysctl_ctx);
14792 			bbr_counter_destroy();
14793 			printf(__XSTRING(MODNAME)
14794 			    " is now no longer available\n");
14795 			bbr_mod_inited = false;
14796 		}
14797 		tcp_lro_dereg_mbufq();
14798 		err = 0;
14799 		break;
14800 	default:
14801 		return (EOPNOTSUPP);
14802 	}
14803 	return (err);
14804 }
14805 
14806 static moduledata_t tcp_bbr = {
14807 	.name = __XSTRING(MODNAME),
14808 	    .evhand = tcp_addbbr,
14809 	    .priv = 0
14810 };
14811 
14812 MODULE_VERSION(MODNAME, 1);
14813 DECLARE_MODULE(MODNAME, tcp_bbr, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
14814 MODULE_DEPEND(MODNAME, tcphpts, 1, 1, 1);
14815